text,length,is_long_context,metric_val,label_metric "// // Copyright © 2017 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #include ""LoadedNetwork.hpp"" #include ""Layer.hpp"" #include ""Graph.hpp"" #include #include ""Profiling.hpp"" #include ""HeapProfiling.hpp"" #include ""WorkingMemHandle.hpp"" #include #include #include #include #include #include #include #include #include namespace armnn { using namespace std; using namespace armnn::profiling; namespace { template std::string ToErrorMessage(const char * prefix, const ExceptionType & error) { std::stringstream ss; ss << prefix << "" "" << error.what(); return ss.str(); } void AddLayerStructure(std::unique_ptr& timelineUtils, const Layer& layer, ProfilingGuid networkGuid) { // Add layer to the post-optimisation network structure std::string layerName = layer.GetNameStr().empty() ? """" : layer.GetNameStr(); timelineUtils->CreateNamedTypedChildEntity(layer.GetGuid(), networkGuid, layerName, LabelsAndEventClasses::LAYER_GUID); for (auto&& input : layer.GetInputSlots()) { const IOutputSlot* source = input.GetConnectedOutputSlot(); ARMNN_ASSERT(source != NULL); timelineUtils->CreateConnectionRelationship(ProfilingRelationshipType::RetentionLink, source->GetOwningLayerGuid(), layer.GetGuid()); } } void AddWorkloadStructure(std::unique_ptr& timelineUtils, std::unique_ptr& workload, const Layer& layer) { // Add workload to the post-optimisation network structure timelineUtils->CreateTypedEntity(workload->GetGuid(), LabelsAndEventClasses::WORKLOAD_GUID); timelineUtils->MarkEntityWithLabel(workload->GetGuid(), layer.GetBackendId().Get(), LabelsAndEventClasses::BACKENDID_GUID); // Link the workload to the layer timelineUtils->CreateRelationship(ProfilingRelationshipType::RetentionLink, layer.GetGuid(), workload->GetGuid(), LabelsAndEventClasses::CHILD_GUID); } } // anonymous std::unique_ptr LoadedNetwork::MakeLoadedNetwork(std::unique_ptr net, std::string& errorMessage, const INetworkProperties& networkProperties, profiling::ProfilingService& profilingService) { std::unique_ptr loadedNetwork; auto Fail = [&](const std::exception& error) -> std::unique_ptr { errorMessage = ToErrorMessage(""An error occurred when preparing the network workloads: "", error); ARMNN_LOG(error) << errorMessage; return std::unique_ptr(); }; try { loadedNetwork.reset(new LoadedNetwork(std::move(net), networkProperties, profilingService)); } catch (const armnn::RuntimeException& error) { return Fail(error); } catch (const armnn::Exception& error) { return Fail(error); } catch (const std::runtime_error& error) { return Fail(error); } return loadedNetwork; } LoadedNetwork::LoadedNetwork(std::unique_ptr net, const INetworkProperties& networkProperties, profiling::ProfilingService& profilingService) : m_OptimizedNetwork(std::move(net)), m_NetworkProperties(networkProperties), m_TensorHandleFactoryRegistry(), m_ProfilingService(profilingService) { ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, ""LoadedNetwork""); // Get the profiler and register it for the current thread. const std::shared_ptr& profiler = m_OptimizedNetwork->GetProfiler(); ProfilerManager::GetInstance().RegisterProfiler(profiler.get()); profiler->EnableProfiling(networkProperties.m_ProfilingEnabled); profiler->EnableNetworkDetailsToStdOut(networkProperties.m_OutputNetworkDetailsMethod); //First create tensor handlers, backends and workload factories. //Handlers are created before workloads are. //Because workload creation can modify some of the handlers, //(for example the splitter and concat layers). bool useExternalMemoryManager = false; bool useInternalMemoryManager = false; Graph& order = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().TopologicalSort(); for (auto&& layer : order) { auto const& backendId = layer->GetBackendId(); if (m_Backends.count(backendId) == 0) { auto createBackend = BackendRegistryInstance().GetFactory(backendId); auto it = m_Backends.emplace(std::make_pair(backendId, createBackend())); IBackendInternal* backend = it.first->second.get(); if (networkProperties.m_AsyncEnabled && !HasCapability(BackendOptions::BackendOption{""AsyncExecution"", true}, backend->GetCapabilities())) { std::string er = backend->GetId(); er += "" does not support AsyncExecution""; throw BackendCapabilityException(er); } if (networkProperties.m_AsyncEnabled && !HasCapability(BackendOptions::BackendOption{""ExternallyManagedMemory"", true}, backend->GetCapabilities())) { std::string er = backend->GetId(); er += "" does not support ExternallyManagedMemory\\n""; er += ""AsyncEnabled networks require all backends to support ExternallyManagedMemory""; throw BackendCapabilityException(er); } if (HasCapability(BackendOptions::BackendOption{""ExternallyManagedMemory"", true},backend->GetCapabilities()) && (m_NetworkProperties.m_ExternalMemoryManagementEnabled || m_NetworkProperties.m_AsyncEnabled)) { m_SupportsExternallyManagedMemory[backend->GetId()] = true; useExternalMemoryManager = true; } else { m_SupportsExternallyManagedMemory[backend->GetId()] = false; useInternalMemoryManager = true; } IBackendInternal::IWorkloadFactoryPtr workloadFactory; if (backend->SupportsTensorAllocatorAPI()) { workloadFactory = backend->CreateWorkloadFactory( m_TensorHandleFactoryRegistry, m_OptimizedNetwork->pOptimizedNetworkImpl->GetModelOptions(), static_cast(m_NetworkProperties.m_InputSource), static_cast(m_NetworkProperties.m_OutputSource)); } else { m_BackendMemoryMangers.emplace_back(backend->CreateMemoryManager()); workloadFactory = backend->CreateWorkloadFactory( m_BackendMemoryMangers.back(), m_OptimizedNetwork->pOptimizedNetworkImpl->GetModelOptions()); } m_WorkloadFactories[backendId ] = std::move(workloadFactory); } } if (!networkProperties.m_AsyncEnabled) { for (auto&& layer : order) { auto& workloadFactory = GetWorkloadFactory(*layer); bool supportsExternalManager = m_SupportsExternallyManagedMemory[layer->GetBackendId()]; switch (layer->GetType()) { case LayerType::Input: case LayerType::MemImport: { // If IsImportEnabled is true then we need to set IsMemoryManaged // to false when creating TensorHandles layer->CreateTensorHandles(m_TensorHandleFactoryRegistry, workloadFactory, !supportsExternalManager && !m_NetworkProperties.m_ImportEnabled); break; } case LayerType::Constant: { layer->CreateTensorHandles(m_TensorHandleFactoryRegistry, workloadFactory, true); break; } default: { // Look for a layer with 1 OutputSlot which has 1 connection and that connection is an Output Layer // If Export is enabled disable memory management so we can export, otherwise we do a copy if ((layer->GetNumOutputSlots() == 1) && (layer->GetOutputSlots()[0].GetNumConnections() == 1) && (layer->GetOutputSlots()[0].GetConnection(0)->GetOwningLayer().GetType() == LayerType::Output)) { layer->CreateTensorHandles(m_TensorHandleFactoryRegistry, workloadFactory, !supportsExternalManager && !m_NetworkProperties.m_ExportEnabled); } else { layer->CreateTensorHandles(m_TensorHandleFactoryRegistry, workloadFactory, !supportsExternalManager); } } } } } ProfilingGuid networkGuid = m_OptimizedNetwork->GetGuid(); std::unique_ptr timelineUtils = TimelineUtilityMethods::GetTimelineUtils(m_ProfilingService); if (timelineUtils) { timelineUtils->CreateTypedEntity(networkGuid, LabelsAndEventClasses::NETWORK_GUID); // Mark the network with a start of life event timelineUtils->RecordEvent(networkGuid, LabelsAndEventClasses::ARMNN_PROFILING_SOL_EVENT_CLASS); // and with the process ID int processID = armnnUtils::Processes::GetCurrentId(); std::stringstream ss; ss << processID; timelineUtils->MarkEntityWithLabel(networkGuid, ss.str(), LabelsAndEventClasses::PROCESS_ID_GUID); } //Then create workloads. { ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, ""LoadNetwork_CreateWorkloads""); for (auto&& layer: order) { if (timelineUtils) { // Add layer to the post-optimisation network structure AddLayerStructure(timelineUtils, *layer, networkGuid); } const IWorkloadFactory& workloadFactory = GetWorkloadFactory(*layer); switch (layer->GetType()) { case LayerType::Input: case LayerType::Output: { // Inputs and outputs are treated in a special way - see EnqueueInput() and EnqueueOutput(). break; } default: { auto workload = layer->CreateWorkload(workloadFactory); if (!workload) { const char* const layerName = layer->GetNameStr().length() != 0 ? layer->GetName() : """"; throw InvalidArgumentException( fmt::format(""No workload created for layer (name: '{0}' type: '{1}') (compute '{2}')"", layerName, static_cast(layer->GetType()), layer->GetBackendId().Get() )); } if (timelineUtils) { // Add workload to the post-optimisation network structure AddWorkloadStructure(timelineUtils, workload, *layer); } // For async networks ConstantWorkloads are managed exclusively by LoadedNetwork // and are separated out from the other workloads if((networkProperties.m_AsyncEnabled || useExternalMemoryManager) && layer->GetType() == LayerType::Constant) { m_ConstantTensorHandles[layer->GetGuid()] = layer->GetOutputSlot(0).GetOutputHandler().GetData(); m_ConstantWorkloads[layer->GetGuid()] = std::move(workload); } else { m_WorkloadQueue.push_back(std::move(workload)); } // release the constant data in the layer.. layer->ReleaseConstantData(); break; } } } } for (auto&& workloadFactory : m_WorkloadFactories) { workloadFactory.second->AfterWorkloadsCreated(); } if (timelineUtils) { // Commit to send the post-optimisation network structure timelineUtils->Commit(); } if (useExternalMemoryManager) { if (networkProperties.m_AsyncEnabled) { CreateMemoryProfileAsync(); } else { CreateMemoryProfile(); } auto backendStrategyMap = BackendRegistryInstance().GetMemoryOptimizerStrategies(); for (auto& backendMemoryProfile : m_MemBlockMap) { const BackendId& backendId = backendMemoryProfile.first; if (backendStrategyMap.find(backendId) != backendStrategyMap.end()) { m_MemBinMap[backendId] = backendStrategyMap[backendId]->Optimize(backendMemoryProfile.second); } else { m_MemBinMap[backendId] = m_ConstantStrategy->Optimize(backendMemoryProfile.second); } } if (!networkProperties.m_AsyncEnabled) { m_ExternalMemoryManager = CreateExternalMemoryManger(m_TensorMemory); // Sort m_TensorMemory, so it's order matches m_Tensorhandles std::sort(m_TensorMemory.begin(), m_TensorMemory.end(), [](const std::pair, MemorySource>& lhs, const std::pair, MemorySource>& rhs) { return lhs.first->m_OutputSlotId < rhs.first->m_OutputSlotId; }); } } // Now that the intermediate tensor memory has been set-up, // do any post allocation configuration for each workload. if (!networkProperties.m_AsyncEnabled) { if (useInternalMemoryManager) { // Set up memory. m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().AllocateDynamicBuffers(); } for (auto &workload : m_WorkloadQueue) { workload->PostAllocationConfigure(); } } if (useExternalMemoryManager) { if (!networkProperties.m_AsyncEnabled) { AllocateAndExecuteConstantWorkloads(); } else { AllocateAndExecuteConstantWorkloadsAsync(); } } } void LoadedNetwork::AllocateAndExecuteConstantWorkloads() { ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, ""LoadNetwork_AllocateAndExecuteConstants""); for (auto& pair : m_ConstantWorkloads) { auto tensorHandle = m_ConstantTensorHandles[pair.first]; tensorHandle->Allocate(); pair.second->Execute(); } } void LoadedNetwork::AllocateAndExecuteConstantWorkloadsAsync() { ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, ""LoadNetwork_AllocateAndExecuteConstants""); Graph& order = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph(); for (auto&& layer : order) { if (layer->GetType() == LayerType::Constant) { const auto& outSlot = layer->GetOutputSlots()[0]; const auto factoryId = outSlot.GetTensorHandleFactoryId(); ARMNN_ASSERT(factoryId != ITensorHandleFactory::LegacyFactoryId); auto& workloadFactory = GetWorkloadFactory(*layer); layer->CreateTensorHandles(m_TensorHandleFactoryRegistry, workloadFactory); ITensorHandle* tensorHandle = outSlot.GetOutputHandler().GetData(); m_ConstantTensorHandles[layer->GetGuid()] = tensorHandle; tensorHandle->Allocate(); WorkingMemDescriptor memDesc; memDesc.m_Outputs.push_back(tensorHandle); m_ConstantWorkloads[layer->GetGuid()]->ExecuteAsync(memDesc); } } } void LoadedNetwork::SendNetworkStructure() { ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, ""LoadNetwork_SendNetworkStructure""); Graph& order = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().TopologicalSort(); ProfilingGuid networkGuid = m_OptimizedNetwork->GetGuid(); std::unique_ptr timelineUtils = TimelineUtilityMethods::GetTimelineUtils(m_ProfilingService); timelineUtils->CreateTypedEntity(networkGuid, LabelsAndEventClasses::NETWORK_GUID); for (auto&& layer : order) { // Add layer to the post-optimisation network structure AddLayerStructure(timelineUtils, *layer, networkGuid); switch (layer->GetType()) { case LayerType::Input: case LayerType::Output: { // Inputs and outputs are treated in a special way - see EnqueueInput() and EnqueueOutput(). break; } default: { for (auto& workload : m_WorkloadQueue) { // Add workload to the post-optimisation network structure AddWorkloadStructure(timelineUtils, workload, *layer); } break; } } } // Commit to send the post-optimisation network structure timelineUtils->Commit(); } profiling::ProfilingGuid LoadedNetwork::GetNetworkGuid() { return m_OptimizedNetwork->GetGuid(); } TensorInfo LoadedNetwork::GetInputTensorInfo(LayerBindingId layerId) const { for (auto&& inputLayer : m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().GetInputLayers()) { ARMNN_ASSERT_MSG(inputLayer->GetNumOutputSlots() == 1, ""Input layer should have exactly 1 output slot""); if (inputLayer->GetBindingId() == layerId) { return inputLayer->GetOutputSlot(0).GetTensorInfo(); } } throw InvalidArgumentException(fmt::format(""No input layer is associated with id {}"", layerId)); } TensorInfo LoadedNetwork::GetOutputTensorInfo(LayerBindingId layerId) const { for (auto&& outputLayer : m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().GetOutputLayers()) { ARMNN_ASSERT_MSG(outputLayer->GetNumInputSlots() == 1, ""Output layer should have exactly 1 input slot""); ARMNN_ASSERT_MSG(outputLayer->GetInputSlot(0).GetConnection(), ""Input slot on Output layer must be connected""); if (outputLayer->GetBindingId() == layerId) { return outputLayer->GetInputSlot(0).GetConnection()->GetTensorInfo(); } } throw InvalidArgumentException(fmt::format(""No output layer is associated with id {}"", layerId)); } const IWorkloadFactory& LoadedNetwork::GetWorkloadFactory(const Layer& layer) const { const IWorkloadFactory* workloadFactory = nullptr; auto it = m_WorkloadFactories.find(layer.GetBackendId()); if (it == m_WorkloadFactories.end()) { throw RuntimeException(fmt::format(""No workload factory for {0} to be used for layer: {1}"", layer.GetBackendId().Get(), layer.GetNameStr()), CHECK_LOCATION()); } workloadFactory = it->second.get(); ARMNN_ASSERT_MSG(workloadFactory, ""No workload factory""); std::string reasonIfUnsupported; ARMNN_ASSERT_MSG(IWorkloadFactory::IsLayerSupported(layer, {}, reasonIfUnsupported, m_OptimizedNetwork->pOptimizedNetworkImpl->GetModelOptions()), ""Factory does not support layer""); IgnoreUnused(reasonIfUnsupported); return *workloadFactory; } namespace { // Non-copyable class owning accelerator-specific tensor data. class TensorPin { public: TensorPin(std::unique_ptr handle, const TensorInfo& info, LayerBindingId id) : m_TensorHandle(std::move(handle)) , m_TensorInfo(info) , m_Id(id) { } ITensorHandle* GetTensorHandle() const { return m_TensorHandle.get(); } const TensorInfo& GetTensorInfo() const { return m_TensorInfo; } LayerBindingId GetBindingId() const { return m_Id; } private: std::unique_ptr m_TensorHandle; TensorInfo m_TensorInfo; LayerBindingId m_Id; }; static const TensorPin& GetTensorPin(LayerBindingId id, const std::vector& pins, char const* bindingPointDesc) { auto it = std::find_if(pins.begin(), pins.end(), [id](const TensorPin& pin) { return pin.GetBindingId() == id; }); if (it != pins.end()) { return *it; } else { throw InvalidArgumentException(fmt::format(""No tensor supplied for {0} {1}"", bindingPointDesc, id)); } } // Stores data that needs to be kept accessible for the entire execution of a workload. class WorkloadData { public: WorkloadData(const InputTensors& inputTensors, const OutputTensors& outputTensors) { m_InputTensorPins.reserve(inputTensors.size()); m_OutputTensorPins.reserve(outputTensors.size()); for (auto inputTensorPair : inputTensors) { auto inputTensor = inputTensorPair.second; std::unique_ptr tensorHandle = std::make_unique(inputTensor.GetInfo(),inputTensor.GetMemoryArea()); LayerBindingId layerId = inputTensorPair.first; m_InputTensorPins.emplace_back(std::move(tensorHandle), inputTensor.GetInfo(), layerId); } for (auto outputTensorPair : outputTensors) { auto outputTensor = outputTensorPair.second; std::unique_ptr tensorHandle = std::make_unique(outputTensor.GetInfo(), outputTensor.GetMemoryArea()); LayerBindingId layerId = outputTensorPair.first; m_OutputTensorPins.emplace_back(std::move(tensorHandle), outputTensor.GetInfo(), layerId); } } const TensorPin& GetInputTensorPin(LayerBindingId id) const { return GetTensorPin(id, m_InputTensorPins, ""input""); } const TensorPin& GetOutputTensorPin(LayerBindingId id) const { return GetTensorPin(id, m_OutputTensorPins, ""output""); } private: std::vector m_InputTensorPins; std::vector m_OutputTensorPins; }; } Status LoadedNetwork::EnqueueWorkload(const InputTensors& inputTensors, const OutputTensors& outputTensors) { const Graph& graph = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph(); // Walk graph to determine the order of execution. if (graph.GetNumLayers() < 2) { ARMNN_LOG(warning) << ""IRuntime::EnqueueWorkload()::Less than two nodes in graph""; return Status::Failure; } // Data that must be kept alive for the entire execution of the workload. WorkloadData workloadData(inputTensors, outputTensors); if (graph.GetNumInputs() != inputTensors.size()) { throw InvalidArgumentException(""Number of inputs provided does not match network.""); } // For each input to the network, call EnqueueInput with the data passed by the user. { ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, ""PrepareInputs""); m_InputQueue.clear(); m_InputQueue.reserve(graph.GetNumInputs()); for (const BindableLayer* inputLayer : graph.GetInputLayers()) { const TensorPin& pin = workloadData.GetInputTensorPin(inputLayer->GetBindingId()); EnqueueInput(*inputLayer, pin.GetTensorHandle(), pin.GetTensorInfo()); } } // For each output to the network, call EnqueueOutput with the data passed by the user. { ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, ""PrepareOutputs""); m_OutputQueue.clear(); m_OutputQueue.reserve(graph.GetNumOutputs()); for (const BindableLayer* outputLayer : graph.GetOutputLayers()) { const TensorPin& pin = workloadData.GetOutputTensorPin(outputLayer->GetBindingId()); EnqueueOutput(*outputLayer, pin.GetTensorHandle(), pin.GetTensorInfo()); } } std::unique_ptr timelineUtils = TimelineUtilityMethods::GetTimelineUtils(m_ProfilingService); ProfilingGuid inferenceGuid = m_ProfilingService.GetNextGuid(); if (timelineUtils) { // Add inference timeline trace if profiling is enabled. ProfilingGuid networkGuid = m_OptimizedNetwork->GetGuid(); timelineUtils->CreateTypedEntity(inferenceGuid, LabelsAndEventClasses::INFERENCE_GUID); timelineUtils->CreateRelationship(ProfilingRelationshipType::RetentionLink, networkGuid, inferenceGuid, LabelsAndEventClasses::EXECUTION_OF_GUID); timelineUtils->RecordEvent(inferenceGuid, LabelsAndEventClasses::ARMNN_PROFILING_SOL_EVENT_CLASS); } bool executionSucceeded = true; { if (m_ProfilingService.IsProfilingEnabled()) { m_ProfilingService.IncrementCounterValue(armnn::profiling::INFERENCES_RUN); } ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, ""Execute""); ARMNN_SCOPED_HEAP_PROFILING(""Executing""); executionSucceeded = Execute(timelineUtils, inferenceGuid); } if (timelineUtils) { // Add end of life of the inference timeline if profiling is enabled. timelineUtils->RecordEvent(inferenceGuid, LabelsAndEventClasses::ARMNN_PROFILING_EOL_EVENT_CLASS); timelineUtils->Commit(); } return executionSucceeded ? Status::Success : Status::Failure; } void LoadedNetwork::EnqueueInput(const BindableLayer& layer, ITensorHandle* tensorHandle, const TensorInfo& tensorInfo) { if (layer.GetType() != LayerType::Input) { throw InvalidArgumentException(""EnqueueInput: given layer not an InputLayer""); } if (tensorHandle == nullptr) { throw InvalidArgumentException(""EnqueueInput: tensorHandle must not be NULL""); } InputQueueDescriptor inputQueueDescriptor; WorkloadInfo info; inputQueueDescriptor.m_Inputs.push_back(tensorHandle); info.m_InputTensorInfos.push_back(tensorInfo); ARMNN_ASSERT_MSG(layer.GetNumOutputSlots() == 1, ""Can only handle Input Layer with one output""); const OutputHandler& handler = layer.GetOutputHandler(); const TensorInfo& outputTensorInfo = handler.GetTensorInfo(); ITensorHandle* outputTensorHandle = handler.GetData(); ARMNN_ASSERT_MSG(outputTensorHandle != nullptr, ""Data should have been allocated.""); inputQueueDescriptor.m_Outputs.push_back(outputTensorHandle); info.m_OutputTensorInfos.push_back(outputTensorInfo); MemorySourceFlags importFlags = outputTensorHandle->GetImportFlags(); bool needMemCopy = true; if (m_NetworkProperties.m_ImportEnabled) // Try import the input tensor { if(CheckFlag(importFlags, m_NetworkProperties.m_InputSource)) { needMemCopy = false; // This assumes a CPU Tensor handle void* mem = tensorHandle->Map(false); if (outputTensorHandle->Import(mem, m_NetworkProperties.m_InputSource)) { tensorHandle->Unmap(); return; // No need for a workload since the import has been done. } tensorHandle->Unmap(); throw MemoryImportException(""EnqueueInput: Memory Import failed""); } } if (needMemCopy) { // Create a mem copy workload for input since we did not import std::unique_ptr inputWorkload = std::make_unique(inputQueueDescriptor, info); ARMNN_ASSERT_MSG(inputWorkload, ""No input workload created""); std::unique_ptr timelineUtils = TimelineUtilityMethods::GetTimelineUtils(m_ProfilingService); if (timelineUtils) { // Add Input Workload to the post-optimisation network structure AddWorkloadStructure(timelineUtils, inputWorkload, layer); timelineUtils->Commit(); } m_InputQueue.push_back(move(inputWorkload)); } } void LoadedNetwork::EnqueueOutput(const BindableLayer& layer, ITensorHandle* tensorHandle, const TensorInfo& tensorInfo) { if (layer.GetType() != LayerType::Output) { throw InvalidArgumentException(""EnqueueOutput: given layer not an OutputLayer""); } if (tensorHandle == nullptr) { throw InvalidArgumentException(""EnqueueOutput: tensorHandle must not be NULL""); } OutputQueueDescriptor outputQueueDescriptor; WorkloadInfo info; outputQueueDescriptor.m_Outputs.push_back(tensorHandle); info.m_OutputTensorInfos.push_back(tensorInfo); ARMNN_ASSERT_MSG(layer.GetNumInputSlots() == 1, ""Output Layer should have exactly one input.""); // Gets the output handler from the previous node. const OutputHandler& outputHandler = layer.GetInputSlots()[0].GetConnectedOutputSlot()->GetOutputHandler(); const TensorInfo& inputTensorInfo = outputHandler.GetTensorInfo(); ITensorHandle* inputTensorHandle = outputHandler.GetData(); ARMNN_ASSERT_MSG(inputTensorHandle != nullptr, ""Data should have been allocated.""); // Try import the output tensor. // Note: We can only import the output pointer if all of the following hold true: // a) The imported pointer is aligned sufficiently // b) The tensor has zero padding // c) There is only one connection to the OutputSlot and it is to an OutputLayer. // d) The output pointer is allocated via malloc. (Other types will be supported in a later release) // e) m_IsExportEnabled must be set to true bool needMemCopy = true; if (m_NetworkProperties.m_ExportEnabled && (layer.GetInputSlots()[0].GetConnectedOutputSlot()->GetNumConnections() == 1)) { if(layer.GetInputSlots()[0].GetConnectedOutputSlot()->GetOwningLayer().GetType() != LayerType::Input) { MemorySourceFlags importFlags = inputTensorHandle->GetImportFlags(); if (CheckFlag(importFlags, m_NetworkProperties.m_OutputSource)) { needMemCopy = false; void *mem = tensorHandle->Map(false); bool importOk = inputTensorHandle->Import(mem, m_NetworkProperties.m_OutputSource); tensorHandle->Unmap(); if (importOk) { // Insert synchronization workload MemSyncQueueDescriptor syncDesc; syncDesc.m_Inputs.push_back(inputTensorHandle); info.m_InputTensorInfos.push_back(inputTensorInfo); auto syncWorkload = std::make_unique(syncDesc, info); ARMNN_ASSERT_MSG(syncWorkload, ""No sync workload created""); m_OutputQueue.push_back(move(syncWorkload)); } else { throw MemoryExportException(""EnqueueOutput: Memory Export failed""); } } } } if (needMemCopy) { // If we got here then we didn't export the memory, so add an output workload which performs a memcopy. outputQueueDescriptor.m_Inputs.push_back(inputTensorHandle); info.m_InputTensorInfos.push_back(inputTensorInfo); std::unique_ptr outputWorkload = std::make_unique(outputQueueDescriptor, info); ARMNN_ASSERT_MSG(outputWorkload, ""No output workload created""); std::unique_ptr timelineUtils = TimelineUtilityMethods::GetTimelineUtils(m_ProfilingService); if (timelineUtils) { // Add Output Workload to the post-optimisation network structure AddWorkloadStructure(timelineUtils, outputWorkload, layer); timelineUtils->Commit(); } m_OutputQueue.push_back(move(outputWorkload)); } } void LoadedNetwork::AllocateWorkingMemory(std::lock_guard& lock) { ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, ""Working Memory Allocation""); // this unused parameter makes sure we can only call this function with a valid lock IgnoreUnused(lock); if (m_IsWorkingMemAllocated) { return; } if (m_ExternalMemoryManager) { m_ExternalMemoryManager->Allocate(); for (unsigned int i = 0; i < m_TensorMemory.size(); ++i) { m_Tensorhandles[i]->Import(m_TensorMemory[i].first->m_Data, m_TensorMemory[i].second); } } for (auto&& memoryManager : m_BackendMemoryMangers) { if (memoryManager) { memoryManager->Acquire(); } } m_TensorHandleFactoryRegistry.AquireMemory(); m_IsWorkingMemAllocated = true; } void LoadedNetwork::FreeWorkingMemory() { std::lock_guard lockGuard(m_WorkingMemMutex); if (!m_IsWorkingMemAllocated) { return; } if (m_ExternalMemoryManager) { m_ExternalMemoryManager->Deallocate(); } // Informs the memory managers to release memory in its respective memory group for (auto&& memoryManager : m_BackendMemoryMangers) { if (memoryManager) { memoryManager->Release(); } } m_TensorHandleFactoryRegistry.ReleaseMemory(); m_IsWorkingMemAllocated = false; } bool LoadedNetwork::Execute(std::unique_ptr& timelineUtils, profiling::ProfilingGuid inferenceGuid) { bool success = true; auto Fail = [&](const std::exception& error) { ARMNN_LOG(error) << ""An error occurred attempting to execute a workload: "" << error.what(); success = false; }; try { std::lock_guard lockGuard(m_WorkingMemMutex); AllocateWorkingMemory(lockGuard); ProfilingDynamicGuid workloadInferenceID(0); auto ExecuteQueue = [&timelineUtils, &workloadInferenceID, &inferenceGuid](WorkloadQueue& queue) { for (auto& workload : queue) { if(timelineUtils) { workloadInferenceID = timelineUtils->RecordWorkloadInferenceAndStartOfLifeEvent(workload->GetGuid(), inferenceGuid); } workload->Execute(); if(timelineUtils) { timelineUtils->RecordEndOfLifeEvent(workloadInferenceID); } } }; ExecuteQueue(m_InputQueue); ExecuteQueue(m_WorkloadQueue); ExecuteQueue(m_OutputQueue); } catch (const RuntimeException& error) { Fail(error); } catch (const std::runtime_error& error) { Fail(error); } return success; } void LoadedNetwork::EnqueueInput(const ConstTensor& inputTensor, ITensorHandle* inputTensorHandle) { if (m_NetworkProperties.m_ImportEnabled) // Try import the input tensor { MemorySourceFlags importFlags = inputTensorHandle->GetImportFlags(); if (CheckFlag(importFlags, m_NetworkProperties.m_InputSource) ) { std::unique_ptr tensorHandle = std::make_unique(inputTensor.GetInfo(), inputTensor.GetMemoryArea()); void* mem = tensorHandle->Map(false); if (inputTensorHandle->Import(mem, m_NetworkProperties.m_InputSource)) { tensorHandle->Unmap(); return; } tensorHandle->Unmap(); throw MemoryImportException(""EnqueueInput: Memory Import failed""); } else { throw MemoryImportException(""EnqueueInput: Memory Import failed, backend does not support Import""); } } else { std::unique_ptr tensorHandle = std::make_unique(inputTensor.GetInfo(), inputTensor.GetMemoryArea()); auto copyFunc = [](void* dst, const void* src, size_t size) { memcpy(dst, src, size); }; CopyTensorContentsGeneric(tensorHandle.get(), inputTensorHandle, copyFunc); } } // Note: We can only import the output pointer if all of the following hold true: // a) The imported pointer is aligned sufficiently // b) The tensor has zero padding // c) There is only one connection to the OutputSlot and it is to an OutputLayer. // d) The output pointer is allocated via malloc. (Other types will be supported in a later release) // e) m_IsExportEnabled must be set to true void LoadedNetwork::ImportOutputTensor(const Tensor& outputTensor, ITensorHandle* outputTensorHandle) { ARMNN_ASSERT_MSG(outputTensorHandle != nullptr, ""Data should have been allocated.""); MemorySourceFlags importFlags = outputTensorHandle->GetImportFlags(); if (CheckFlag(importFlags, m_NetworkProperties.m_OutputSource)) { std::unique_ptr tensorHandle = std::make_unique(outputTensor.GetInfo(), outputTensor.GetMemoryArea()); void* mem = tensorHandle->Map(false); bool importOk = outputTensorHandle->Import(mem, m_NetworkProperties.m_OutputSource); tensorHandle->Unmap(); if (!importOk) { throw MemoryExportException(""ImportOutputTensor: Memory Export failed""); } } else { throw MemoryExportException(""ImportOutputTensor: Memory Export failed, attempting to export Input Layer""); } } void CopyToOutputTensor(const Tensor& outputTensor, ITensorHandle* outputTensorHandle) { auto copyFunc = [](void* dst, const void* src, size_t size) { memcpy(dst, src, size); }; std::unique_ptr tensorHandle = std::make_unique(outputTensor.GetInfo(), outputTensor.GetMemoryArea()); CopyTensorContentsGeneric(outputTensorHandle, tensorHandle.get(), copyFunc); } const armnn::ConstTensor GetInputTensor(const LayerBindingId layerId, const InputTensors& inputTensors) { for (auto inputTensorPair : inputTensors) { LayerBindingId id = inputTensorPair.first; if (id == layerId) { return inputTensorPair.second; } } throw InvalidArgumentException(""Input does not exist.""); } const armnn::Tensor GetOutputTensor(const LayerBindingId layerId, const OutputTensors& outputTensors) { for (auto outputTensorPair : outputTensors) { LayerBindingId id = outputTensorPair.first; if (id == layerId) { return outputTensorPair.second; } } throw InvalidArgumentException(""Output does not exist.""); } std::vector LoadedNetwork::ImportInputs(const InputTensors& inputTensors) { if (!m_NetworkProperties.m_ImportEnabled) // Try import the input tensor { throw MemoryImportException(""ImportInputs: Memory Import failed, NetworkProperties.m_ImportEnabled""); } std::vector importedInputs; Graph& graph = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().TopologicalSort(); for (auto inputTensor : inputTensors) { auto layerBindingId = inputTensor.first; auto it = std::find_if(graph.GetInputLayers().begin(), graph.GetInputLayers().end(), [=](auto* layer) { return layer->GetBindingId() == layerBindingId; }); if (it == graph.GetInputLayers().end()) { throw MemoryImportException(fmt::format(""ImportInputs: Memory Import failed, unknown LayerBindingId: {}"", layerBindingId)); } const Layer* layer = *it; if (layer->GetType() != LayerType::Input) { throw InvalidArgumentException(""ImportInputs: given layer not an InputLayer""); } auto& backend = m_Backends.at(layer->GetBackendId()); if (!HasCapability(BackendOptions::BackendOption{""PreImportIOTensors"", true}, backend->GetCapabilities())) { std::string er = backend->GetId(); er += "" does not have PreImportIOTensors capability""; throw BackendCapabilityException(er); } const OutputSlot& outputSlot = layer->GetOutputSlots()[0]; ITensorHandleFactory::FactoryId factoryId = outputSlot.GetTensorHandleFactoryId(); const TensorInfo& tensorInfo = outputSlot.GetTensorInfo(); ITensorHandleFactory* handleFactory = m_TensorHandleFactoryRegistry.GetFactory(factoryId); ARMNN_ASSERT(handleFactory); ImportedTensorHandlePin importedTensorHandlePin{layerBindingId, handleFactory->CreateTensorHandle(tensorInfo, false)}; ITensorHandle* tensorHandle = importedTensorHandlePin.m_TensorHandle.get(); if (!CheckFlag(tensorHandle->GetImportFlags(), m_NetworkProperties.m_InputSource)) { throw MemoryImportException( fmt::format(""ImportInputs: Memory Import failed, backend: {} does not support importing from source {}"" , factoryId, m_NetworkProperties.m_InputSource)); } std::unique_ptr passThroughTensorHandle = std::make_unique(inputTensor.second.GetInfo(), inputTensor.second.GetMemoryArea()); if (tensorHandle->Import(passThroughTensorHandle->Map(), m_NetworkProperties.m_InputSource)) { importedInputs.push_back(m_CurImportedInputId++); passThroughTensorHandle->Unmap(); } else { passThroughTensorHandle->Unmap(); throw MemoryImportException(""ImportInputs: Memory Import failed""); } m_PreImportedInputHandles.push_back(std::move(importedTensorHandlePin)); } return importedInputs; } std::vector LoadedNetwork::ImportOutputs(const OutputTensors& outputTensors) { if (!m_NetworkProperties.m_ExportEnabled) // Try import the output tensor { throw MemoryImportException(""ImportOutputs: Memory Import failed, NetworkProperties.m_ImportEnabled""); } std::vector importedOutputs; Graph& graph = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().TopologicalSort(); for (const auto& outputTensor : outputTensors) { auto layerBindingId = outputTensor.first; auto it = std::find_if(graph.GetOutputLayers().begin(), graph.GetOutputLayers().end(), [=](auto* layer) { return layer->GetBindingId() == layerBindingId; }); if (it == graph.GetOutputLayers().end()) { throw MemoryImportException(fmt::format(""ImportOutputs: Memory Import failed, unknown LayerBindingId: {}"", layerBindingId)); } const Layer* layer = *it; if (layer->GetType() != LayerType::Output) { throw InvalidArgumentException(""ImportOutputs: given layer not an OutputLayer""); } auto& backend = m_Backends.at(layer->GetBackendId()); if (!HasCapability(BackendOptions::BackendOption{""PreImportIOTensors"", true}, backend->GetCapabilities())) { std::string er = backend->GetId(); er += "" does not have PreImportIOTensors capability""; throw BackendCapabilityException(er); } const InputSlot& inputSlot = layer->GetInputSlots()[0]; ITensorHandleFactory::FactoryId factoryId = inputSlot.GetConnectedOutputSlot()->GetTensorHandleFactoryId(); const TensorInfo& tensorInfo = inputSlot.GetConnectedOutputSlot()->GetTensorInfo(); ITensorHandleFactory* handleFactory = m_TensorHandleFactoryRegistry.GetFactory(factoryId); ARMNN_ASSERT(handleFactory); ImportedTensorHandlePin importedTensorHandlePin{layerBindingId, handleFactory->CreateTensorHandle(tensorInfo, false)}; ITensorHandle* tensorHandle = importedTensorHandlePin.m_TensorHandle.get(); if (!CheckFlag(tensorHandle->GetImportFlags(), m_NetworkProperties.m_OutputSource)) { throw MemoryImportException(fmt::format(""ImportInputs: Memory Import failed, backend: "" ""{} does not support importing from source {}"" , factoryId, m_NetworkProperties.m_OutputSource)); } if (tensorHandle->Import(outputTensor.second.GetMemoryArea(), m_NetworkProperties.m_OutputSource)) { importedOutputs.push_back(m_CurImportedOutputId++); } else { throw MemoryImportException(""ImportInputs: Memory Import failed""); } m_PreImportedOutputHandles.push_back(std::move(importedTensorHandlePin)); } return importedOutputs; } void LoadedNetwork::ClearImportedInputs(const std::vector inputIds) { for (auto id : inputIds) { if (id > m_PreImportedInputHandles.size()) { throw InvalidArgumentException(fmt::format(""ClearImportedInputs::Unknown ImportedInputId: {}"", id)); } auto& importedTensorHandle = m_PreImportedInputHandles[id].m_TensorHandle; if (!importedTensorHandle) { throw InvalidArgumentException( fmt::format(""ClearImportedInputs::ImportedInput with id: {} has already been deleted"", id)); } // Call Unimport then destroy the tensorHandle importedTensorHandle->Unimport(); importedTensorHandle = {}; } } void LoadedNetwork::ClearImportedOutputs(const std::vector outputIds) { for (auto id : outputIds) { if (id > m_PreImportedOutputHandles.size()) { throw InvalidArgumentException(fmt::format(""ClearImportedOutputs::Unknown ImportedOutputId: {}"", id)); } auto& importedTensorHandle = m_PreImportedOutputHandles[id].m_TensorHandle; if (!importedTensorHandle) { throw InvalidArgumentException( fmt::format(""ClearImportedOutputs::ImportedOutput with id: {} has already been deleted"", id)); } // Call Unimport then destroy the tensorHandle importedTensorHandle->Unimport(); importedTensorHandle = {}; } } Status LoadedNetwork::Execute(const InputTensors& inputTensors, const OutputTensors& outputTensors, IWorkingMemHandle& iWorkingMemHandle, std::vector preImportedInputs, std::vector preImportedOutputs) { const Graph& graph = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph(); if (inputTensors.size() + preImportedInputs.size() != graph.GetNumInputs()) { if (preImportedInputs.empty()) { throw InvalidArgumentException(""LoadedNetwork::Execute: Number of inputs provided does not match network.""); } else { throw InvalidArgumentException(""LoadedNetwork::Execute: "" ""Number of inputs + preImportedInputs provided does not match network.""); } } if (outputTensors.size() + preImportedOutputs.size() != graph.GetNumOutputs()) { if (preImportedOutputs.empty()) { throw InvalidArgumentException(""LoadedNetwork::Execute: "" ""Number of outputs provided does not match network.""); } else { throw InvalidArgumentException(""LoadedNetwork::Execute: "" ""Number of outputs + preImportedOutputs provided does not match network.""); } } WorkingMemHandle& workingMemHandle = dynamic_cast(iWorkingMemHandle); // Collect all the given LayerBindingIds and check them for duplicates and unknowns. std::vector& bindingIds = workingMemHandle.GetBindingIdVector(); unsigned int index = 0; for (auto pair : inputTensors) { bindingIds[index++] = pair.first; } for (ImportedInputId id : preImportedInputs) { bindingIds[index++] = ValidateImportedInputID(id); } for (auto pair : outputTensors) { bindingIds[index++] = pair.first; } for (ImportedOutputId id : preImportedOutputs) { bindingIds[index++] = ValidateImportedOutputID(id); } workingMemHandle.ValidateBindingIds(); auto resetMemHandle = [&]() { for (ImportedInputId id: preImportedInputs) { const LayerBindingId layerBindingId = m_PreImportedInputHandles[id].m_LayerBindingId; auto inputHandle = workingMemHandle.GetInputHandle(layerBindingId); auto inputConnections = workingMemHandle.GetInputConnections(layerBindingId); for (auto it : inputConnections) { *it = inputHandle; } } for (ImportedOutputId id: preImportedOutputs) { const LayerBindingId layerBindingId = m_PreImportedOutputHandles[id].m_LayerBindingId; auto outputHandle = workingMemHandle.GetOutputHandle(layerBindingId); auto outputConnections = workingMemHandle.GetOutputConnection(layerBindingId); for (auto it : outputConnections) { *it = outputHandle; } } }; std::unique_ptr timelineUtils = profiling::TimelineUtilityMethods::GetTimelineUtils(m_ProfilingService); profiling::ProfilingGuid inferenceGuid = m_ProfilingService.GetNextGuid(); if (timelineUtils) { // Add inference timeline trace if profiling is enabled. profiling::ProfilingGuid networkGuid = m_OptimizedNetwork->GetGuid(); timelineUtils->CreateTypedEntity(inferenceGuid, profiling::LabelsAndEventClasses::INFERENCE_GUID); timelineUtils->CreateRelationship(profiling::ProfilingRelationshipType::RetentionLink, networkGuid, inferenceGuid, profiling::LabelsAndEventClasses::EXECUTION_OF_GUID); timelineUtils->RecordEvent(inferenceGuid, profiling::LabelsAndEventClasses::ARMNN_PROFILING_SOL_EVENT_CLASS); } bool executionSucceeded = true; if (timelineUtils) { // Add end of life of the inference timeline if profiling is enabled. timelineUtils->RecordEvent(inferenceGuid, profiling::LabelsAndEventClasses::ARMNN_PROFILING_EOL_EVENT_CLASS); timelineUtils->Commit(); } if (!workingMemHandle.IsAllocated()) { workingMemHandle.Allocate(); } { ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, ""PrepareInputs""); for (auto pair : inputTensors) { EnqueueInput(pair.second, workingMemHandle.GetInputHandle(pair.first)); } // Swap in the pre-imported inputs if any for (ImportedInputId id : preImportedInputs) { const ImportedTensorHandlePin& importedInputPin = m_PreImportedInputHandles[id]; const LayerBindingId layerBindingId = m_PreImportedInputHandles[id].m_LayerBindingId; const auto& preimportedHandle = importedInputPin.m_TensorHandle; auto inputConnections = workingMemHandle.GetInputConnections(layerBindingId); for (auto it : inputConnections) { *it = preimportedHandle.get(); } } } { ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, ""PrepareOutputs""); if (m_NetworkProperties.m_ExportEnabled) { for (auto pair: outputTensors) { ImportOutputTensor(pair.second, workingMemHandle.GetOutputHandle(pair.first)); } } for (ImportedOutputId id : preImportedOutputs) { const ImportedTensorHandlePin& importedOutputPin = m_PreImportedOutputHandles[id]; const LayerBindingId layerBindingId = m_PreImportedOutputHandles[id].m_LayerBindingId; const auto& preimportedHandle = importedOutputPin.m_TensorHandle; auto outputConnections = workingMemHandle.GetOutputConnection(layerBindingId); for (auto it : outputConnections) { *it = preimportedHandle.get(); } } } auto Fail = [&](const std::exception& error) { ARMNN_LOG(error) << ""An error occurred attempting to execute a workload: "" << error.what(); executionSucceeded = false; }; profiling::ProfilingDynamicGuid workloadInferenceID(0); try { for (unsigned int i = 0; i < m_WorkloadQueue.size(); ++i) { auto& workload = m_WorkloadQueue[i]; if (timelineUtils) { workloadInferenceID = timelineUtils->RecordWorkloadInferenceAndStartOfLifeEvent(workload->GetGuid(), inferenceGuid); } workload->ExecuteAsync(workingMemHandle.GetWorkingMemDescriptorAt(i)); if (timelineUtils) { timelineUtils->RecordEndOfLifeEvent(workloadInferenceID); } } } catch (const RuntimeException& error) { resetMemHandle(); Fail(error); } catch (const std::runtime_error& error) { resetMemHandle(); Fail(error); } catch (...) { resetMemHandle(); throw; } if (!m_NetworkProperties.m_ExportEnabled) { for (auto pair: outputTensors) { CopyToOutputTensor(pair.second, workingMemHandle.GetOutputHandle(pair.first)); } } else { ARMNN_SCOPED_PROFILING_EVENT(Compute::Undefined, ""SyncMemGeneric_Execute""); workingMemHandle.MemSyncOutputs(); } resetMemHandle(); return executionSucceeded ? Status::Success : Status::Failure; } /// Create a new unique WorkingMemHandle object. Create multiple handles if you wish to have /// overlapped Execution by calling this function from different threads. std::unique_ptr LoadedNetwork::CreateWorkingMemHandle(NetworkId networkId) { Graph& order = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph(); // Tensors that will need to be allocated internally within armnn std::vector> managedTensorHandles; // Tensors that will be allocated externally by the user std::vector> unmanagedTensorHandles; std::vector workingMemDescriptors; std::unordered_map workingMemDescriptorMap; auto GetTensorHandle = [&](Layer* layer, const OutputSlot& outputSlot) { ITensorHandleFactory::FactoryId factoryId = outputSlot.GetTensorHandleFactoryId(); const TensorInfo& tensorInfo = outputSlot.GetTensorInfo(); if (factoryId == ITensorHandleFactory::LegacyFactoryId) { BackendId id = layer->GetBackendId(); ARMNN_NO_DEPRECATE_WARN_BEGIN return m_WorkloadFactories.at(id)->CreateTensorHandle(tensorInfo, false); ARMNN_NO_DEPRECATE_WARN_END } else { ITensorHandleFactory* handleFactory = m_TensorHandleFactoryRegistry.GetFactory(factoryId); ARMNN_ASSERT(handleFactory); return handleFactory->CreateTensorHandle(tensorInfo, false); } }; struct HandleInfo { ITensorHandle* m_TensorHandle; bool m_IsInputLayerHandle = false; bool m_IsOutputLayerHandle = false; WorkingMemHandle::InputMemDescriptorCoords m_InputMemDescriptorCoords; WorkingMemHandle::OutputMemDescriptorCoords m_OutputMemDescriptorCoords; }; std::unordered_map outputToHandleInfoMap; unsigned int layerIndex = 0; for (auto&& layer : order) { // Constant layers execution and management is handled during loaded network construction if (layer->GetType() == LayerType::Constant) { continue; } WorkingMemDescriptor workingMemDescriptor; bool isMemoryManaged = true; bool isInputLayer = false; bool isOutputLayer = false; bool isConnectedToOutputLayer = false; if (layer->GetType() == LayerType::Input || layer->GetType() == LayerType::MemImport) { // Input layers/workloads will not be executed so the descriptor is not added to workingMemDescriptors // However we will still need to manage the tensorHandle isInputLayer = true; isMemoryManaged = !m_NetworkProperties.m_ImportEnabled; } else if (layer->GetType() == LayerType::Output) { isOutputLayer = true; } unsigned int slotIndex = 0; // Create a tensor handle for each output slot of a layer // Once we create it, we start managing its lifetime for (auto& slot : layer->GetOutputSlots()) { for (unsigned int i = 0; i < slot.GetNumConnections(); ++i) { if ((slot.GetConnection(i)->GetOwningLayer().GetType() == LayerType::Output)) { if (!isConnectedToOutputLayer) { isConnectedToOutputLayer = true; // If Export is enabled disable memory management, so we can export, otherwise we do a copy isMemoryManaged = !m_NetworkProperties.m_ExportEnabled; } else { // Importing in this case would likely cause unexpected behaviour, so we disallow it. ARMNN_LOG(warning) << fmt::format(""Layer name: '{0}' guid: '{1}' has two or more OutputLayers connected to it. "" ""This will prevent importing on the connected OutputLayers."", layer->GetName(), layer->GetGuid()); isMemoryManaged = true; } } } ITensorHandle* tensorHandle; if (isMemoryManaged) { managedTensorHandles.emplace_back(GetTensorHandle(layer, slot)); tensorHandle = managedTensorHandles.back().get(); } else { unmanagedTensorHandles.emplace_back(GetTensorHandle(layer, slot)); tensorHandle = unmanagedTensorHandles.back().get(); } workingMemDescriptor.m_Outputs.push_back(tensorHandle); HandleInfo& handleInfo = outputToHandleInfoMap[&slot]; handleInfo.m_TensorHandle = tensorHandle; // Store the coordinates of the current layer's OutputSlot that is connected to the OutputLayer if (isConnectedToOutputLayer) { handleInfo.m_IsOutputLayerHandle = true; handleInfo.m_OutputMemDescriptorCoords.m_OutputSlotCoords = {layerIndex, slotIndex}; } // Store the LayerBindingId of the InputLayer if (isInputLayer) { handleInfo.m_IsInputLayerHandle = true; LayerBindingId bindingId = static_cast(layer)->GetBindingId(); handleInfo.m_InputMemDescriptorCoords.m_LayerBindingId = bindingId; } slotIndex++; } // Loop through the input slots in the same layer and decrement the reference counter associated // to each tensor handle we encounter. // Once it reaches zero, the lifetime of the tensor handle has ended, and we mark its memory as available // so that the next tensor handle with a non overlapping lifetime can share its memory. for (auto& slot : layer->GetInputSlots()) { ARMNN_ASSERT(slot.GetConnection()); auto outputSlot = slot.GetConnectedOutputSlot(); auto key = outputSlot->GetOwningLayer().GetGuid(); // Constant layers execution and management is handled during loaded network construction auto found = m_ConstantTensorHandles.find(key); if (found != m_ConstantTensorHandles.end()) { ITensorHandle* tensorHandle = found->second; workingMemDescriptor.m_Inputs.push_back(tensorHandle); // Odd case where a constant layer is connected to an output layer // We will need to create a HandleInfo to track it if (isOutputLayer) { LayerBindingId bindingId = static_cast(layer)->GetBindingId(); HandleInfo& handleInfo = outputToHandleInfoMap[outputSlot]; handleInfo.m_TensorHandle = tensorHandle; handleInfo.m_IsOutputLayerHandle = true; handleInfo.m_OutputMemDescriptorCoords.m_LayerBindingIds.push_back(bindingId); handleInfo.m_OutputMemDescriptorCoords.m_InputSlotCoords.push_back({layerIndex, 0}); } continue; } HandleInfo& handleInfo = outputToHandleInfoMap.at(outputSlot); ITensorHandle* inputTensorHandle = handleInfo.m_TensorHandle; workingMemDescriptor.m_Inputs.push_back(inputTensorHandle); // Store the LayerBindingId of the OutputLayer if (isOutputLayer) { LayerBindingId bindingId = static_cast(layer)->GetBindingId(); handleInfo.m_OutputMemDescriptorCoords.m_LayerBindingIds.push_back(bindingId); handleInfo.m_OutputMemDescriptorCoords.m_InputSlotCoords.push_back({layerIndex, 0}); } // In this case the layer is not an Output Layer but shares its input tensorhandle with an OutputLayer // It will need to be updated as well, if we swap out the tensorhandle else if (handleInfo.m_IsOutputLayerHandle) { handleInfo.m_OutputMemDescriptorCoords.m_InputSlotCoords.push_back({layerIndex, slot.GetSlotIndex()}); } // Store the coordinates of the InputSlots connected to the InputLayer // There can be more than one InputSlot connected to an InputLayer, so we use a vector if (handleInfo.m_IsInputLayerHandle) { std::pair connectionLocation{layerIndex, slot.GetSlotIndex()}; handleInfo.m_InputMemDescriptorCoords.m_InputSlotCoords.emplace_back(connectionLocation); } } workingMemDescriptorMap.insert({layer->GetGuid(), workingMemDescriptor}); // Input/Output layers/workloads will not be executed, so the descriptor is not added to workingMemDescriptors // However we will still need to manage the tensorHandle if (!isInputLayer) { workingMemDescriptors.push_back(workingMemDescriptor); layerIndex++; } } std::vector, MemorySource>> tensorMemory; auto externalMemoryManager = CreateExternalMemoryManger(tensorMemory); // Sort m_TensorMemory, so it's order matches the outputSlot order std::sort(tensorMemory.begin(), tensorMemory.end(), [](const std::pair, MemorySource>& lhs, const std::pair, MemorySource>& rhs) { return lhs.first->m_OutputSlotId < rhs.first->m_OutputSlotId; }); std::vector inputConnectionsInfo; std::vector outputConnectionsInfo; for (const auto& handleInfo: outputToHandleInfoMap) { if (handleInfo.second.m_IsOutputLayerHandle) { outputConnectionsInfo.emplace_back(handleInfo.second.m_OutputMemDescriptorCoords); } if (handleInfo.second.m_IsInputLayerHandle) { inputConnectionsInfo.emplace_back(handleInfo.second.m_InputMemDescriptorCoords); } } return std::make_unique(networkId, inputConnectionsInfo, outputConnectionsInfo, workingMemDescriptors, workingMemDescriptorMap, std::move(externalMemoryManager), std::move(tensorMemory), std::move(managedTensorHandles), std::move(unmanagedTensorHandles)); } void LoadedNetwork::RegisterDebugCallback(const DebugCallbackFunction& func) { for (auto&& workloadPtr: m_WorkloadQueue) { workloadPtr.get()->RegisterDebugCallback(func); } } void LoadedNetwork::CreateMemoryProfileAsync() { struct PartialBlock { unsigned int m_StartOfLife; unsigned int m_Lifetime; size_t m_MemSize; unsigned int m_Index; BackendId m_BackendId; }; auto align = [](size_t numToAlign) { const size_t alignment = sizeof(float); return ((numToAlign + alignment - 1) / alignment) * alignment; }; std::unordered_map memBlockTrackerMap; const bool inputImportingEnabled = m_NetworkProperties.m_InputSource != MemorySource::Undefined; const bool outputImportingEnabled = m_NetworkProperties.m_OutputSource != MemorySource::Undefined; unsigned int timestep = 0; unsigned int outputIndex = 0; Graph& order = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().TopologicalSort(); for (auto&& layer : order) { const LayerType& layerType = layer->GetType(); // Don't manage memory if importing. if (layerType == LayerType::Input && inputImportingEnabled) { continue; } // Don't manage memory if importing. if (layerType == LayerType::Output && outputImportingEnabled && layer->GetInputSlot(0).GetConnectedOutputSlot()->GetNumConnections() == 1) { continue; } // Because Constant Layer memory can not be shared, the memory must persist for the lifetime of execution, // management is done separately. if (layerType == LayerType::Constant) { continue; } BackendId backendId = layer->GetBackendId(); for (auto& outputSlot : layer->GetOutputSlots()) { if (!m_SupportsExternallyManagedMemory[backendId]) { continue; } PartialBlock partialBlock; partialBlock.m_StartOfLife = timestep; size_t alignedSize = align(outputSlot.GetOutputHandler().GetTensorInfo().GetNumBytes()); partialBlock.m_MemSize = alignedSize; partialBlock.m_Index = outputIndex++; partialBlock.m_Lifetime = outputSlot.GetNumConnections(); partialBlock.m_BackendId = backendId; if (partialBlock.m_Lifetime == 0) { m_MemBlockMap[partialBlock.m_BackendId].emplace_back(partialBlock.m_StartOfLife, partialBlock.m_StartOfLife, partialBlock.m_MemSize, 0, partialBlock.m_Index); } else { memBlockTrackerMap[&outputSlot] = partialBlock; } } for (auto& inputSlot : layer->GetInputSlots()) { const Layer& connectedInputLayer = inputSlot.GetConnectedOutputSlot()->GetOwningLayer(); const LayerType& owningLayerType = connectedInputLayer.GetType(); if (owningLayerType == LayerType::Constant) { continue; } if (inputImportingEnabled && owningLayerType == LayerType::Input) { continue; } auto outputSlot = inputSlot.GetConnectedOutputSlot(); PartialBlock& partialBlock = memBlockTrackerMap.at(outputSlot); auto& lifetime = partialBlock.m_Lifetime; --lifetime; if (lifetime == 0) { m_MemBlockMap[partialBlock.m_BackendId].emplace_back(partialBlock.m_StartOfLife, timestep, partialBlock.m_MemSize, 0, partialBlock.m_Index); } } ++timestep; } } void LoadedNetwork::CreateMemoryProfile() { // Finds the first TensorHandle ancestor of a SubTensorHandle. If the ITensorHandle provided // is a TensorHandle, the function just returns it auto TraceSubTensorHandleAncestry = [](ITensorHandle* const subTensorHandle) { ITensorHandle* ancestor = subTensorHandle; while (ancestor && ancestor->GetParent()) { ancestor = ancestor->GetParent(); } return ancestor; }; struct PartialBlock { unsigned int m_StartOfLife; unsigned int m_Lifetime; size_t m_MemSize; unsigned int m_Index; BackendId m_BackendId; }; auto align = [](size_t numToAlign) { const size_t alignment = sizeof(float); return ((numToAlign + alignment - 1) / alignment) * alignment; }; std::unordered_map memBlockTrackerMap; const bool inputImportingEnabled = m_NetworkProperties.m_InputSource != MemorySource::Undefined; const bool outputImportingEnabled = m_NetworkProperties.m_OutputSource != MemorySource::Undefined; unsigned int timestep = 0; unsigned int outputIndex = 0; Graph& order = m_OptimizedNetwork->pOptimizedNetworkImpl->GetGraph().TopologicalSort(); for (auto&& layer : order) { const LayerType& layerType = layer->GetType(); // Don't manage memory if importing. if (layerType == LayerType::Input && inputImportingEnabled) { continue; } // Don't manage memory if importing. if (layerType == LayerType::Output && outputImportingEnabled && layer->GetInputSlot(0).GetConnectedOutputSlot()->GetNumConnections() == 1) { continue; } // Because Constant Layer memory can not be shared, the memory must persist for the lifetime of execution, // management is done separately. if (layerType == LayerType::Constant) { continue; } BackendId backendId = layer->GetBackendId(); for (auto& outputSlot : layer->GetOutputSlots()) { if (!m_SupportsExternallyManagedMemory[backendId]) { continue; } ITensorHandle* tensorHandle = outputSlot.GetOutputHandler().GetData(); tensorHandle = TraceSubTensorHandleAncestry(tensorHandle); if (memBlockTrackerMap.find(tensorHandle) == memBlockTrackerMap.end()) { PartialBlock partialBlock; partialBlock.m_StartOfLife = timestep; size_t alignedSize = align(outputSlot.GetOutputHandler().GetTensorInfo().GetNumBytes()); partialBlock.m_MemSize = alignedSize; partialBlock.m_Index = outputIndex++; partialBlock.m_Lifetime = outputSlot.GetNumConnections(); partialBlock.m_BackendId = backendId; if (partialBlock.m_Lifetime == 0) { m_MemBlockMap[partialBlock.m_BackendId].emplace_back(partialBlock.m_StartOfLife, partialBlock.m_StartOfLife, partialBlock.m_MemSize, 0, partialBlock.m_Index); } else { memBlockTrackerMap[tensorHandle] = partialBlock; } m_Tensorhandles.push_back(tensorHandle); } else { memBlockTrackerMap.at(tensorHandle).m_Lifetime += outputSlot.GetNumConnections(); } } for (auto& inputSlot : layer->GetInputSlots()) { const Layer& connectedInputLayer = inputSlot.GetConnectedOutputSlot()->GetOwningLayer(); const LayerType& owningLayerType = connectedInputLayer.GetType(); if (owningLayerType == LayerType::Constant) { continue; } if (inputImportingEnabled && owningLayerType == LayerType::Input) { continue; } if (!m_SupportsExternallyManagedMemory[connectedInputLayer.GetBackendId()]) { continue; } auto outputSlot = inputSlot.GetConnectedOutputSlot(); ITensorHandle* tensorHandle = outputSlot->GetOutputHandler().GetData(); tensorHandle = TraceSubTensorHandleAncestry(tensorHandle); PartialBlock& partialBlock = memBlockTrackerMap.at(tensorHandle); auto& lifetime = partialBlock.m_Lifetime; --lifetime; if (lifetime == 0) { m_MemBlockMap[partialBlock.m_BackendId].emplace_back(partialBlock.m_StartOfLife, timestep, partialBlock.m_MemSize, 0, partialBlock.m_Index); } } ++timestep; } } std::unique_ptr LoadedNetwork::CreateExternalMemoryManger( std::vector, MemorySource>>& tensorMemoryVec) { std::unique_ptr memoryManager = std::make_unique(); auto allocatorMap = BackendRegistryInstance().GetAllocators(); for (auto& backend : m_MemBinMap) { std::vector bufferStorageVec; std::shared_ptr backendAllocator; if (allocatorMap.find(backend.first) != allocatorMap.end()) { backendAllocator = allocatorMap[backend.first]; } else { backendAllocator = m_Backends[backend.first]->GetDefaultAllocator(); } for (auto& memBin : backend.second) { BufferStorage bufferStorage; bufferStorage.m_BufferSize = memBin.m_MemSize; bufferStorage.m_TensorMemoryVector.reserve(memBin.m_MemBlocks.size()); for (auto& memBlock : memBin.m_MemBlocks) { auto tensorMemory = std::make_shared(TensorMemory{memBlock.m_Offset, memBlock.m_Index}); tensorMemoryVec.emplace_back(tensorMemory, backendAllocator->GetMemorySourceType()); bufferStorage.m_TensorMemoryVector.emplace_back(tensorMemory); } bufferStorageVec.emplace_back(std::move(bufferStorage)); } memoryManager->StoreMemToAllocate(bufferStorageVec, backendAllocator, 4); } return memoryManager; } LayerBindingId LoadedNetwork::ValidateImportedInputID(ImportedInputId id) { try { const auto& importedTensorHandlePin = m_PreImportedInputHandles.at(id); if (!importedTensorHandlePin.m_TensorHandle) { throw InvalidArgumentException(fmt::format(""LoadedNetwork::Execute:"" ""PreImportedInput: {} has been deleted"", id)); } return importedTensorHandlePin.m_LayerBindingId; } catch (const std::out_of_range&) { throw InvalidArgumentException(fmt::format(""LoadedNetwork::Execute: Unknown ImportedInputId: {}"", id)); } } LayerBindingId LoadedNetwork::ValidateImportedOutputID(ImportedOutputId id) { try { const auto& importedTensorHandlePin = m_PreImportedOutputHandles.at(id); if (!importedTensorHandlePin.m_TensorHandle) { throw InvalidArgumentException(fmt::format(""LoadedNetwork::Execute: "" ""PreImportedOutput: {} has been deleted"", id)); } return importedTensorHandlePin.m_LayerBindingId; } catch (const std::out_of_range&) { throw InvalidArgumentException(fmt::format(""LoadedNetwork::Execute: Unknown ImportedOutputId: {}"", id)); } } } ",16150,True,3114.420364391024,median "/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: Oliver Henrich (University of Strathclyde, Glasgow) ------------------------------------------------------------------------- */ #include #include #include #include #include ""pair_oxdna_hbond.h"" #include ""mf_oxdna.h"" #include ""atom.h"" #include ""comm.h"" #include ""force.h"" #include ""neighbor.h"" #include ""neigh_list.h"" #include ""neigh_request.h"" #include ""update.h"" #include ""integrate.h"" #include ""math_const.h"" #include ""memory.h"" #include ""error.h"" #include ""atom_vec_ellipsoid.h"" #include ""math_extra.h"" using namespace LAMMPS_NS; using namespace MathConst; using namespace MFOxdna; // sequence-specific base-pairing strength // A:0 C:1 G:2 T:3, 5'- (i,j) -3' static const double alpha_hb[4][4] = {{1.00000,1.00000,1.00000,0.82915}, {1.00000,1.00000,1.15413,1.00000}, {1.00000,1.15413,1.00000,1.00000}, {0.82915,1.00000,1.00000,1.00000}}; /* ---------------------------------------------------------------------- */ PairOxdnaHbond::PairOxdnaHbond(LAMMPS *lmp) : Pair(lmp) { single_enable = 0; writedata = 1; } /* ---------------------------------------------------------------------- */ PairOxdnaHbond::~PairOxdnaHbond() { if (allocated) { memory->destroy(setflag); memory->destroy(cutsq); memory->destroy(epsilon_hb); memory->destroy(a_hb); memory->destroy(cut_hb_0); memory->destroy(cut_hb_c); memory->destroy(cut_hb_lo); memory->destroy(cut_hb_hi); memory->destroy(cut_hb_lc); memory->destroy(cut_hb_hc); memory->destroy(cutsq_hb_hc); memory->destroy(b_hb_lo); memory->destroy(b_hb_hi); memory->destroy(shift_hb); memory->destroy(a_hb1); memory->destroy(theta_hb1_0); memory->destroy(dtheta_hb1_ast); memory->destroy(b_hb1); memory->destroy(dtheta_hb1_c); memory->destroy(a_hb2); memory->destroy(theta_hb2_0); memory->destroy(dtheta_hb2_ast); memory->destroy(b_hb2); memory->destroy(dtheta_hb2_c); memory->destroy(a_hb3); memory->destroy(theta_hb3_0); memory->destroy(dtheta_hb3_ast); memory->destroy(b_hb3); memory->destroy(dtheta_hb3_c); memory->destroy(a_hb4); memory->destroy(theta_hb4_0); memory->destroy(dtheta_hb4_ast); memory->destroy(b_hb4); memory->destroy(dtheta_hb4_c); memory->destroy(a_hb7); memory->destroy(theta_hb7_0); memory->destroy(dtheta_hb7_ast); memory->destroy(b_hb7); memory->destroy(dtheta_hb7_c); memory->destroy(a_hb8); memory->destroy(theta_hb8_0); memory->destroy(dtheta_hb8_ast); memory->destroy(b_hb8); memory->destroy(dtheta_hb8_c); } } /* ---------------------------------------------------------------------- compute function for oxDNA pair interactions hb=hydrogen bonding site ------------------------------------------------------------------------- */ void PairOxdnaHbond::compute(int eflag, int vflag) { double delf[3],delta[3],deltb[3]; // force, torque increment; double evdwl,fpair,finc,tpair,factor_lj; double delr_hb[3],delr_hb_norm[3],rsq_hb,r_hb,rinv_hb; double theta1,t1dir[3],cost1; double theta2,t2dir[3],cost2; double theta3,t3dir[3],cost3; double theta4,t4dir[3],cost4; double theta7,t7dir[3],cost7; double theta8,t8dir[3],cost8; // distance COM-hbonding site double d_chb=+0.4; // vectors COM-h-bonding site in lab frame double ra_chb[3],rb_chb[3]; // quaternions and Cartesian unit vectors in lab frame double *qa,ax[3],ay[3],az[3]; double *qb,bx[3],by[3],bz[3]; double **x = atom->x; double **f = atom->f; double **torque = atom->torque; int *type = atom->type; int nlocal = atom->nlocal; int newton_pair = force->newton_pair; int *alist,*blist,*numneigh,**firstneigh; double *special_lj = force->special_lj; AtomVecEllipsoid *avec = (AtomVecEllipsoid *) atom->style_match(""ellipsoid""); AtomVecEllipsoid::Bonus *bonus = avec->bonus; int a,b,ia,ib,anum,bnum,atype,btype; double f1,f4t1,f4t4,f4t2,f4t3,f4t7,f4t8; double df1,df4t1,df4t4,df4t2,df4t3,df4t7,df4t8; evdwl = 0.0; ev_init(eflag,vflag); anum = list->inum; alist = list->ilist; numneigh = list->numneigh; firstneigh = list->firstneigh; // loop over pair interaction neighbors of my atoms for (ia = 0; ia < anum; ia++) { a = alist[ia]; atype = type[a]; qa=bonus[a].quat; MathExtra::q_to_exyz(qa,ax,ay,az); ra_chb[0] = d_chb*ax[0]; ra_chb[1] = d_chb*ax[1]; ra_chb[2] = d_chb*ax[2]; blist = firstneigh[a]; bnum = numneigh[a]; for (ib = 0; ib < bnum; ib++) { b = blist[ib]; factor_lj = special_lj[sbmask(b)]; // = 0 for nearest neighbors b &= NEIGHMASK; btype = type[b]; qb=bonus[b].quat; MathExtra::q_to_exyz(qb,bx,by,bz); rb_chb[0] = d_chb*bx[0]; rb_chb[1] = d_chb*bx[1]; rb_chb[2] = d_chb*bx[2]; // vector h-bonding site b to a delr_hb[0] = x[a][0] + ra_chb[0] - x[b][0] - rb_chb[0]; delr_hb[1] = x[a][1] + ra_chb[1] - x[b][1] - rb_chb[1]; delr_hb[2] = x[a][2] + ra_chb[2] - x[b][2] - rb_chb[2]; rsq_hb = delr_hb[0]*delr_hb[0] + delr_hb[1]*delr_hb[1] + delr_hb[2]*delr_hb[2]; r_hb = sqrt(rsq_hb); rinv_hb = 1.0/r_hb; delr_hb_norm[0] = delr_hb[0] * rinv_hb; delr_hb_norm[1] = delr_hb[1] * rinv_hb; delr_hb_norm[2] = delr_hb[2] * rinv_hb; f1 = F1(r_hb, epsilon_hb[atype][btype], a_hb[atype][btype], cut_hb_0[atype][btype], cut_hb_lc[atype][btype], cut_hb_hc[atype][btype], cut_hb_lo[atype][btype], cut_hb_hi[atype][btype], b_hb_lo[atype][btype], b_hb_hi[atype][btype], shift_hb[atype][btype]); // early rejection criterium if (f1) { cost1 = -1.0*MathExtra::dot3(ax,bx); if (cost1 > 1.0) cost1 = 1.0; if (cost1 < -1.0) cost1 = -1.0; theta1 = acos(cost1); f4t1 = F4(theta1, a_hb1[atype][btype], theta_hb1_0[atype][btype], dtheta_hb1_ast[atype][btype], b_hb1[atype][btype], dtheta_hb1_c[atype][btype]); // early rejection criterium if (f4t1) { cost2 = -1.0*MathExtra::dot3(ax,delr_hb_norm); if (cost2 > 1.0) cost2 = 1.0; if (cost2 < -1.0) cost2 = -1.0; theta2 = acos(cost2); f4t2 = F4(theta2, a_hb2[atype][btype], theta_hb2_0[atype][btype], dtheta_hb2_ast[atype][btype], b_hb2[atype][btype], dtheta_hb2_c[atype][btype]); // early rejection criterium if (f4t2) { cost3 = MathExtra::dot3(bx,delr_hb_norm); if (cost3 > 1.0) cost3 = 1.0; if (cost3 < -1.0) cost3 = -1.0; theta3 = acos(cost3); f4t3 = F4(theta3, a_hb3[atype][btype], theta_hb3_0[atype][btype], dtheta_hb3_ast[atype][btype], b_hb3[atype][btype], dtheta_hb3_c[atype][btype]); // early rejection criterium if (f4t3) { cost4 = MathExtra::dot3(az,bz); if (cost4 > 1.0) cost4 = 1.0; if (cost4 < -1.0) cost4 = -1.0; theta4 = acos(cost4); f4t4 = F4(theta4, a_hb4[atype][btype], theta_hb4_0[atype][btype], dtheta_hb4_ast[atype][btype], b_hb4[atype][btype], dtheta_hb4_c[atype][btype]); // early rejection criterium if (f4t4) { cost7 = -1.0*MathExtra::dot3(az,delr_hb_norm); if (cost7 > 1.0) cost7 = 1.0; if (cost7 < -1.0) cost7 = -1.0; theta7 = acos(cost7); f4t7 = F4(theta7, a_hb7[atype][btype], theta_hb7_0[atype][btype], dtheta_hb7_ast[atype][btype], b_hb7[atype][btype], dtheta_hb7_c[atype][btype]); // early rejection criterium if (f4t7) { cost8 = MathExtra::dot3(bz,delr_hb_norm); if (cost8 > 1.0) cost8 = 1.0; if (cost8 < -1.0) cost8 = -1.0; theta8 = acos(cost8); f4t8 = F4(theta8, a_hb8[atype][btype], theta_hb8_0[atype][btype], dtheta_hb8_ast[atype][btype], b_hb8[atype][btype], dtheta_hb8_c[atype][btype]); evdwl = f1 * f4t1 * f4t2 * f4t3 * f4t4 * f4t7 * f4t8 * factor_lj; // early rejection criterium if (evdwl) { df1 = DF1(r_hb, epsilon_hb[atype][btype], a_hb[atype][btype], cut_hb_0[atype][btype], cut_hb_lc[atype][btype], cut_hb_hc[atype][btype], cut_hb_lo[atype][btype], cut_hb_hi[atype][btype], b_hb_lo[atype][btype], b_hb_hi[atype][btype]); df4t1 = DF4(theta1, a_hb1[atype][btype], theta_hb1_0[atype][btype], dtheta_hb1_ast[atype][btype], b_hb1[atype][btype], dtheta_hb1_c[atype][btype])/sin(theta1); df4t2 = DF4(theta2, a_hb2[atype][btype], theta_hb2_0[atype][btype], dtheta_hb2_ast[atype][btype], b_hb2[atype][btype], dtheta_hb2_c[atype][btype])/sin(theta2); df4t3 = DF4(theta3, a_hb3[atype][btype], theta_hb3_0[atype][btype], dtheta_hb3_ast[atype][btype], b_hb3[atype][btype], dtheta_hb3_c[atype][btype])/sin(theta3); df4t4 = DF4(theta4, a_hb4[atype][btype], theta_hb4_0[atype][btype], dtheta_hb4_ast[atype][btype], b_hb4[atype][btype], dtheta_hb4_c[atype][btype])/sin(theta4); df4t7 = DF4(theta7, a_hb7[atype][btype], theta_hb7_0[atype][btype], dtheta_hb7_ast[atype][btype], b_hb7[atype][btype], dtheta_hb7_c[atype][btype])/sin(theta7); df4t8 = DF4(theta8, a_hb8[atype][btype], theta_hb8_0[atype][btype], dtheta_hb8_ast[atype][btype], b_hb8[atype][btype], dtheta_hb8_c[atype][btype])/sin(theta8); // force, torque and virial contribution for forces between h-bonding sites fpair = 0.0; delf[0] = 0.0; delf[1] = 0.0; delf[2] = 0.0; delta[0] = 0.0; delta[1] = 0.0; delta[2] = 0.0; deltb[0] = 0.0; deltb[1] = 0.0; deltb[2] = 0.0; // radial force finc = -df1 * f4t1 * f4t2 * f4t3 * f4t4 * f4t7 * f4t8 * factor_lj; fpair += finc; delf[0] += delr_hb[0] * finc; delf[1] += delr_hb[1] * finc; delf[2] += delr_hb[2] * finc; // theta2 force if (theta2) { finc = -f1 * f4t1 * df4t2 * f4t3 * f4t4 * f4t7 * f4t8 * rinv_hb * factor_lj; fpair += finc; delf[0] += (delr_hb_norm[0]*cost2 + ax[0]) * finc; delf[1] += (delr_hb_norm[1]*cost2 + ax[1]) * finc; delf[2] += (delr_hb_norm[2]*cost2 + ax[2]) * finc; } // theta3 force if (theta3) { finc = -f1 * f4t1 * f4t2 * df4t3 * f4t4 * f4t7 * f4t8 * rinv_hb * factor_lj; fpair += finc; delf[0] += (delr_hb_norm[0]*cost3 - bx[0]) * finc; delf[1] += (delr_hb_norm[1]*cost3 - bx[1]) * finc; delf[2] += (delr_hb_norm[2]*cost3 - bx[2]) * finc; } // theta7 force if (theta7) { finc = -f1 * f4t1 * f4t2 * f4t3 * f4t4 * df4t7 * f4t8 * rinv_hb * factor_lj; fpair += finc; delf[0] += (delr_hb_norm[0]*cost7 + az[0]) * finc; delf[1] += (delr_hb_norm[1]*cost7 + az[1]) * finc; delf[2] += (delr_hb_norm[2]*cost7 + az[2]) * finc; } // theta8 force if (theta8) { finc = -f1 * f4t1 * f4t2 * f4t3 * f4t4 * f4t7 * df4t8 * rinv_hb * factor_lj; fpair += finc; delf[0] += (delr_hb_norm[0]*cost8 - bz[0]) * finc; delf[1] += (delr_hb_norm[1]*cost8 - bz[1]) * finc; delf[2] += (delr_hb_norm[2]*cost8 - bz[2]) * finc; } // increment forces and torques f[a][0] += delf[0]; f[a][1] += delf[1]; f[a][2] += delf[2]; MathExtra::cross3(ra_chb,delf,delta); torque[a][0] += delta[0]; torque[a][1] += delta[1]; torque[a][2] += delta[2]; if (newton_pair || b < nlocal) { f[b][0] -= delf[0]; f[b][1] -= delf[1]; f[b][2] -= delf[2]; MathExtra::cross3(rb_chb,delf,deltb); torque[b][0] -= deltb[0]; torque[b][1] -= deltb[1]; torque[b][2] -= deltb[2]; } // increment energy and virial // NOTE: The virial is calculated on the 'molecular' basis. // (see G. Ciccotti and J.P. Ryckaert, Comp. Phys. Rep. 4, 345-392 (1986)) if (evflag) ev_tally_xyz(a,b,nlocal,newton_pair,evdwl,0.0, delf[0],delf[1],delf[2],x[a][0]-x[b][0],x[a][1]-x[b][1],x[a][2]-x[b][2]); // pure torques not expressible as r x f delta[0] = 0.0; delta[1] = 0.0; delta[2] = 0.0; deltb[0] = 0.0; deltb[1] = 0.0; deltb[2] = 0.0; // theta1 torque if (theta1) { tpair = -f1 * df4t1 * f4t2 * f4t3 * f4t4 * f4t7 * f4t8 * factor_lj; MathExtra::cross3(ax,bx,t1dir); delta[0] += t1dir[0]*tpair; delta[1] += t1dir[1]*tpair; delta[2] += t1dir[2]*tpair; deltb[0] += t1dir[0]*tpair; deltb[1] += t1dir[1]*tpair; deltb[2] += t1dir[2]*tpair; } // theta2 torque if (theta2) { tpair = -f1 * f4t1 * df4t2 * f4t3 * f4t4 * f4t7 * f4t8 * factor_lj; MathExtra::cross3(ax,delr_hb_norm,t2dir); delta[0] += t2dir[0]*tpair; delta[1] += t2dir[1]*tpair; delta[2] += t2dir[2]*tpair; } // theta3 torque if (theta3) { tpair = -f1 * f4t1 * f4t2 * df4t3 * f4t4 * f4t7 * f4t8 * factor_lj; MathExtra::cross3(bx,delr_hb_norm,t3dir); deltb[0] += t3dir[0]*tpair; deltb[1] += t3dir[1]*tpair; deltb[2] += t3dir[2]*tpair; } // theta4 torque if (theta4) { tpair = -f1 * f4t1 * f4t2 * f4t3 * df4t4 * f4t7 * f4t8 * factor_lj; MathExtra::cross3(bz,az,t4dir); delta[0] += t4dir[0]*tpair; delta[1] += t4dir[1]*tpair; delta[2] += t4dir[2]*tpair; deltb[0] += t4dir[0]*tpair; deltb[1] += t4dir[1]*tpair; deltb[2] += t4dir[2]*tpair; } // theta7 torque if (theta7) { tpair = -f1 * f4t1 * f4t2 * f4t3 * f4t4 * df4t7 * f4t8 * factor_lj; MathExtra::cross3(az,delr_hb_norm,t7dir); delta[0] += t7dir[0]*tpair; delta[1] += t7dir[1]*tpair; delta[2] += t7dir[2]*tpair; } // theta8 torque if (theta8) { tpair = -f1 * f4t1 * f4t2 * f4t3 * f4t4 * f4t7 * df4t8 * factor_lj; MathExtra::cross3(bz,delr_hb_norm,t8dir); deltb[0] += t8dir[0]*tpair; deltb[1] += t8dir[1]*tpair; deltb[2] += t8dir[2]*tpair; } // increment torques torque[a][0] += delta[0]; torque[a][1] += delta[1]; torque[a][2] += delta[2]; if (newton_pair || b < nlocal) { torque[b][0] -= deltb[0]; torque[b][1] -= deltb[1]; torque[b][2] -= deltb[2]; } } } } } } } }// end early rejection criteria } } if (vflag_fdotr) virial_fdotr_compute(); } /* ---------------------------------------------------------------------- allocate all arrays ------------------------------------------------------------------------- */ void PairOxdnaHbond::allocate() { allocated = 1; int n = atom->ntypes; memory->create(setflag,n+1,n+1,""pair:setflag""); for (int i = 1; i <= n; i++) for (int j = i; j <= n; j++) setflag[i][j] = 0; memory->create(cutsq,n+1,n+1,""pair:cutsq""); memory->create(epsilon_hb,n+1,n+1,""pair:epsilon_hb""); memory->create(a_hb,n+1,n+1,""pair:a_hb""); memory->create(cut_hb_0,n+1,n+1,""pair:cut_hb_0""); memory->create(cut_hb_c,n+1,n+1,""pair:cut_hb_c""); memory->create(cut_hb_lo,n+1,n+1,""pair:cut_hb_lo""); memory->create(cut_hb_hi,n+1,n+1,""pair:cut_hb_hi""); memory->create(cut_hb_lc,n+1,n+1,""pair:cut_hb_lc""); memory->create(cut_hb_hc,n+1,n+1,""pair:cut_hb_hc""); memory->create(b_hb_lo,n+1,n+1,""pair:b_hb_lo""); memory->create(b_hb_hi,n+1,n+1,""pair:b_hb_hi""); memory->create(shift_hb,n+1,n+1,""pair:shift_hb""); memory->create(cutsq_hb_hc,n+1,n+1,""pair:cutsq_hb_hc""); memory->create(a_hb1,n+1,n+1,""pair:a_hb1""); memory->create(theta_hb1_0,n+1,n+1,""pair:theta_hb1_0""); memory->create(dtheta_hb1_ast,n+1,n+1,""pair:dtheta_hb1_ast""); memory->create(b_hb1,n+1,n+1,""pair:b_hb1""); memory->create(dtheta_hb1_c,n+1,n+1,""pair:dtheta_hb1_c""); memory->create(a_hb2,n+1,n+1,""pair:a_hb2""); memory->create(theta_hb2_0,n+1,n+1,""pair:theta_hb2_0""); memory->create(dtheta_hb2_ast,n+1,n+1,""pair:dtheta_hb2_ast""); memory->create(b_hb2,n+1,n+1,""pair:b_hb2""); memory->create(dtheta_hb2_c,n+1,n+1,""pair:dtheta_hb2_c""); memory->create(a_hb3,n+1,n+1,""pair:a_hb3""); memory->create(theta_hb3_0,n+1,n+1,""pair:theta_hb3_0""); memory->create(dtheta_hb3_ast,n+1,n+1,""pair:dtheta_hb3_ast""); memory->create(b_hb3,n+1,n+1,""pair:b_hb3""); memory->create(dtheta_hb3_c,n+1,n+1,""pair:dtheta_hb3_c""); memory->create(a_hb4,n+1,n+1,""pair:a_hb4""); memory->create(theta_hb4_0,n+1,n+1,""pair:theta_hb4_0""); memory->create(dtheta_hb4_ast,n+1,n+1,""pair:dtheta_hb4_ast""); memory->create(b_hb4,n+1,n+1,""pair:b_hb4""); memory->create(dtheta_hb4_c,n+1,n+1,""pair:dtheta_hb4_c""); memory->create(a_hb7,n+1,n+1,""pair:a_hb7""); memory->create(theta_hb7_0,n+1,n+1,""pair:theta_hb7_0""); memory->create(dtheta_hb7_ast,n+1,n+1,""pair:dtheta_hb7_ast""); memory->create(b_hb7,n+1,n+1,""pair:b_hb7""); memory->create(dtheta_hb7_c,n+1,n+1,""pair:dtheta_hb7_c""); memory->create(a_hb8,n+1,n+1,""pair:a_hb8""); memory->create(theta_hb8_0,n+1,n+1,""pair:theta_hb8_0""); memory->create(dtheta_hb8_ast,n+1,n+1,""pair:dtheta_hb8_ast""); memory->create(b_hb8,n+1,n+1,""pair:b_hb8""); memory->create(dtheta_hb8_c,n+1,n+1,""pair:dtheta_hb8_c""); } /* ---------------------------------------------------------------------- global settings ------------------------------------------------------------------------- */ void PairOxdnaHbond::settings(int narg, char **/*arg*/) { if (narg != 0) error->all(FLERR,""Illegal pair_style command""); } /* ---------------------------------------------------------------------- set coeffs for one or more type pairs ------------------------------------------------------------------------- */ void PairOxdnaHbond::coeff(int narg, char **arg) { int count; if (narg != 27) error->all(FLERR,""Incorrect args for pair coefficients in oxdna/hbond""); if (!allocated) allocate(); int ilo,ihi,jlo,jhi; force->bounds(FLERR,arg[0],atom->ntypes,ilo,ihi); force->bounds(FLERR,arg[1],atom->ntypes,jlo,jhi); // h-bonding interaction count = 0; double epsilon_hb_one, a_hb_one, cut_hb_0_one, cut_hb_c_one, cut_hb_lo_one, cut_hb_hi_one; double b_hb_lo_one, b_hb_hi_one, cut_hb_lc_one, cut_hb_hc_one, tmp, shift_hb_one; double a_hb1_one, theta_hb1_0_one, dtheta_hb1_ast_one; double b_hb1_one, dtheta_hb1_c_one; double a_hb2_one, theta_hb2_0_one, dtheta_hb2_ast_one; double b_hb2_one, dtheta_hb2_c_one; double a_hb3_one, theta_hb3_0_one, dtheta_hb3_ast_one; double b_hb3_one, dtheta_hb3_c_one; double a_hb4_one, theta_hb4_0_one, dtheta_hb4_ast_one; double b_hb4_one, dtheta_hb4_c_one; double a_hb7_one, theta_hb7_0_one, dtheta_hb7_ast_one; double b_hb7_one, dtheta_hb7_c_one; double a_hb8_one, theta_hb8_0_one, dtheta_hb8_ast_one; double b_hb8_one, dtheta_hb8_c_one; if (strcmp(arg[2], ""seqav"") != 0 && strcmp(arg[2], ""seqdep"") != 0) { error->all(FLERR,""Incorrect setting, select seqav or seqdep in oxdna/hbond""); } if (strcmp(arg[2],""seqav"") == 0) seqdepflag = 0; if (strcmp(arg[2],""seqdep"") == 0) seqdepflag = 1; epsilon_hb_one = force->numeric(FLERR,arg[3]); a_hb_one = force->numeric(FLERR,arg[4]); cut_hb_0_one = force->numeric(FLERR,arg[5]); cut_hb_c_one = force->numeric(FLERR,arg[6]); cut_hb_lo_one = force->numeric(FLERR,arg[7]); cut_hb_hi_one = force->numeric(FLERR,arg[8]); a_hb1_one = force->numeric(FLERR,arg[9]); theta_hb1_0_one = force->numeric(FLERR,arg[10]); dtheta_hb1_ast_one = force->numeric(FLERR,arg[11]); a_hb2_one = force->numeric(FLERR,arg[12]); theta_hb2_0_one = force->numeric(FLERR,arg[13]); dtheta_hb2_ast_one = force->numeric(FLERR,arg[14]); a_hb3_one = force->numeric(FLERR,arg[15]); theta_hb3_0_one = force->numeric(FLERR,arg[16]); dtheta_hb3_ast_one = force->numeric(FLERR,arg[17]); a_hb4_one = force->numeric(FLERR,arg[18]); theta_hb4_0_one = force->numeric(FLERR,arg[19]); dtheta_hb4_ast_one = force->numeric(FLERR,arg[20]); a_hb7_one = force->numeric(FLERR,arg[21]); theta_hb7_0_one = force->numeric(FLERR,arg[22]); dtheta_hb7_ast_one = force->numeric(FLERR,arg[23]); a_hb8_one = force->numeric(FLERR,arg[24]); theta_hb8_0_one = force->numeric(FLERR,arg[25]); dtheta_hb8_ast_one = force->numeric(FLERR,arg[26]); b_hb_lo_one = 2*a_hb_one*exp(-a_hb_one*(cut_hb_lo_one-cut_hb_0_one))* 2*a_hb_one*exp(-a_hb_one*(cut_hb_lo_one-cut_hb_0_one))* (1-exp(-a_hb_one*(cut_hb_lo_one-cut_hb_0_one)))* (1-exp(-a_hb_one*(cut_hb_lo_one-cut_hb_0_one)))/ (4*((1-exp(-a_hb_one*(cut_hb_lo_one -cut_hb_0_one)))* (1-exp(-a_hb_one*(cut_hb_lo_one-cut_hb_0_one)))- (1-exp(-a_hb_one*(cut_hb_c_one -cut_hb_0_one)))* (1-exp(-a_hb_one*(cut_hb_c_one-cut_hb_0_one))))); cut_hb_lc_one = cut_hb_lo_one - a_hb_one*exp(-a_hb_one*(cut_hb_lo_one-cut_hb_0_one))* (1-exp(-a_hb_one*(cut_hb_lo_one-cut_hb_0_one)))/b_hb_lo_one; b_hb_hi_one = 2*a_hb_one*exp(-a_hb_one*(cut_hb_hi_one-cut_hb_0_one))* 2*a_hb_one*exp(-a_hb_one*(cut_hb_hi_one-cut_hb_0_one))* (1-exp(-a_hb_one*(cut_hb_hi_one-cut_hb_0_one)))* (1-exp(-a_hb_one*(cut_hb_hi_one-cut_hb_0_one)))/ (4*((1-exp(-a_hb_one*(cut_hb_hi_one -cut_hb_0_one)))* (1-exp(-a_hb_one*(cut_hb_hi_one-cut_hb_0_one)))- (1-exp(-a_hb_one*(cut_hb_c_one -cut_hb_0_one)))* (1-exp(-a_hb_one*(cut_hb_c_one-cut_hb_0_one))))); cut_hb_hc_one = cut_hb_hi_one - a_hb_one*exp(-a_hb_one*(cut_hb_hi_one-cut_hb_0_one))* (1-exp(-a_hb_one*(cut_hb_hi_one-cut_hb_0_one)))/b_hb_hi_one; tmp = 1 - exp(-(cut_hb_c_one-cut_hb_0_one) * a_hb_one); shift_hb_one = epsilon_hb_one * tmp * tmp; b_hb1_one = a_hb1_one*a_hb1_one*dtheta_hb1_ast_one*dtheta_hb1_ast_one/(1-a_hb1_one*dtheta_hb1_ast_one*dtheta_hb1_ast_one); dtheta_hb1_c_one = 1/(a_hb1_one*dtheta_hb1_ast_one); b_hb2_one = a_hb2_one*a_hb2_one*dtheta_hb2_ast_one*dtheta_hb2_ast_one/(1-a_hb2_one*dtheta_hb2_ast_one*dtheta_hb2_ast_one); dtheta_hb2_c_one = 1/(a_hb2_one*dtheta_hb2_ast_one); b_hb3_one = a_hb3_one*a_hb3_one*dtheta_hb3_ast_one*dtheta_hb3_ast_one/(1-a_hb3_one*dtheta_hb3_ast_one*dtheta_hb3_ast_one); dtheta_hb3_c_one = 1/(a_hb3_one*dtheta_hb3_ast_one); b_hb4_one = a_hb4_one*a_hb4_one*dtheta_hb4_ast_one*dtheta_hb4_ast_one/(1-a_hb4_one*dtheta_hb4_ast_one*dtheta_hb4_ast_one); dtheta_hb4_c_one = 1/(a_hb4_one*dtheta_hb4_ast_one); b_hb7_one = a_hb7_one*a_hb7_one*dtheta_hb7_ast_one*dtheta_hb7_ast_one/(1-a_hb7_one*dtheta_hb7_ast_one*dtheta_hb7_ast_one); dtheta_hb7_c_one = 1/(a_hb7_one*dtheta_hb7_ast_one); b_hb8_one = a_hb8_one*a_hb8_one*dtheta_hb8_ast_one*dtheta_hb8_ast_one/(1-a_hb8_one*dtheta_hb8_ast_one*dtheta_hb8_ast_one); dtheta_hb8_c_one = 1/(a_hb8_one*dtheta_hb8_ast_one); for (int i = ilo; i <= ihi; i++) { for (int j = MAX(jlo,i); j <= jhi; j++) { epsilon_hb[i][j] = epsilon_hb_one; if (seqdepflag) epsilon_hb[i][j] *= alpha_hb[i-1][j-1]; a_hb[i][j] = a_hb_one; cut_hb_0[i][j] = cut_hb_0_one; cut_hb_c[i][j] = cut_hb_c_one; cut_hb_lo[i][j] = cut_hb_lo_one; cut_hb_hi[i][j] = cut_hb_hi_one; cut_hb_lc[i][j] = cut_hb_lc_one; cut_hb_hc[i][j] = cut_hb_hc_one; b_hb_lo[i][j] = b_hb_lo_one; b_hb_hi[i][j] = b_hb_hi_one; shift_hb[i][j] = shift_hb_one; if (seqdepflag) shift_hb[i][j] *= alpha_hb[i-1][j-1]; a_hb1[i][j] = a_hb1_one; theta_hb1_0[i][j] = theta_hb1_0_one; dtheta_hb1_ast[i][j] = dtheta_hb1_ast_one; b_hb1[i][j] = b_hb1_one; dtheta_hb1_c[i][j] = dtheta_hb1_c_one; a_hb2[i][j] = a_hb2_one; theta_hb2_0[i][j] = theta_hb2_0_one; dtheta_hb2_ast[i][j] = dtheta_hb2_ast_one; b_hb2[i][j] = b_hb2_one; dtheta_hb2_c[i][j] = dtheta_hb2_c_one; a_hb3[i][j] = a_hb3_one; theta_hb3_0[i][j] = theta_hb3_0_one; dtheta_hb3_ast[i][j] = dtheta_hb3_ast_one; b_hb3[i][j] = b_hb3_one; dtheta_hb3_c[i][j] = dtheta_hb3_c_one; a_hb4[i][j] = a_hb4_one; theta_hb4_0[i][j] = theta_hb4_0_one; dtheta_hb4_ast[i][j] = dtheta_hb4_ast_one; b_hb4[i][j] = b_hb4_one; dtheta_hb4_c[i][j] = dtheta_hb4_c_one; a_hb7[i][j] = a_hb7_one; theta_hb7_0[i][j] = theta_hb7_0_one; dtheta_hb7_ast[i][j] = dtheta_hb7_ast_one; b_hb7[i][j] = b_hb7_one; dtheta_hb7_c[i][j] = dtheta_hb7_c_one; a_hb8[i][j] = a_hb8_one; theta_hb8_0[i][j] = theta_hb8_0_one; dtheta_hb8_ast[i][j] = dtheta_hb8_ast_one; b_hb8[i][j] = b_hb8_one; dtheta_hb8_c[i][j] = dtheta_hb8_c_one; setflag[i][j] = 1; count++; } } if (count == 0) error->all(FLERR,""Incorrect args for pair coefficients in oxdna/hbond""); } /* ---------------------------------------------------------------------- init specific to this pair style ------------------------------------------------------------------------- */ void PairOxdnaHbond::init_style() { int irequest; // request regular neighbor lists irequest = neighbor->request(this,instance_me); } /* ---------------------------------------------------------------------- neighbor callback to inform pair style of neighbor list to use regular ------------------------------------------------------------------------- */ void PairOxdnaHbond::init_list(int id, NeighList *ptr) { if (id == 0) list = ptr; if (id > 0) error->all(FLERR,""Respa not supported""); } /* ---------------------------------------------------------------------- init for one type pair i,j and corresponding j,i ------------------------------------------------------------------------- */ double PairOxdnaHbond::init_one(int i, int j) { if (setflag[i][j] == 0) { error->all(FLERR,""Coefficient mixing not defined in oxDNA""); } if (offset_flag) { error->all(FLERR,""Offset not supported in oxDNA""); } if (seqdepflag) { epsilon_hb[j][i] = epsilon_hb[i][j] / alpha_hb[i-1][j-1] * alpha_hb[j-1][i-1]; } else { epsilon_hb[j][i] = epsilon_hb[i][j]; } a_hb[j][i] = a_hb[i][j]; cut_hb_0[j][i] = cut_hb_0[i][j]; cut_hb_c[j][i] = cut_hb_c[i][j]; cut_hb_lo[j][i] = cut_hb_lo[i][j]; cut_hb_hi[j][i] = cut_hb_hi[i][j]; b_hb_lo[j][i] = b_hb_lo[i][j]; b_hb_hi[j][i] = b_hb_hi[i][j]; cut_hb_lc[j][i] = cut_hb_lc[i][j]; cut_hb_hc[j][i] = cut_hb_hc[i][j]; if (seqdepflag) { shift_hb[j][i] = shift_hb[i][j] / alpha_hb[i-1][j-1] * alpha_hb[j-1][i-1]; } else { shift_hb[j][i] = shift_hb[i][j]; } a_hb1[j][i] = a_hb1[i][j]; theta_hb1_0[j][i] = theta_hb1_0[i][j]; dtheta_hb1_ast[j][i] = dtheta_hb1_ast[i][j]; b_hb1[j][i] = b_hb1[i][j]; dtheta_hb1_c[j][i] = dtheta_hb1_c[i][j]; a_hb2[j][i] = a_hb2[i][j]; theta_hb2_0[j][i] = theta_hb2_0[i][j]; dtheta_hb2_ast[j][i] = dtheta_hb2_ast[i][j]; b_hb2[j][i] = b_hb2[i][j]; dtheta_hb2_c[j][i] = dtheta_hb2_c[i][j]; a_hb3[j][i] = a_hb3[i][j]; theta_hb3_0[j][i] = theta_hb3_0[i][j]; dtheta_hb3_ast[j][i] = dtheta_hb3_ast[i][j]; b_hb3[j][i] = b_hb3[i][j]; dtheta_hb3_c[j][i] = dtheta_hb3_c[i][j]; a_hb4[j][i] = a_hb4[i][j]; theta_hb4_0[j][i] = theta_hb4_0[i][j]; dtheta_hb4_ast[j][i] = dtheta_hb4_ast[i][j]; b_hb4[j][i] = b_hb4[i][j]; dtheta_hb4_c[j][i] = dtheta_hb4_c[i][j]; a_hb7[j][i] = a_hb7[i][j]; theta_hb7_0[j][i] = theta_hb7_0[i][j]; dtheta_hb7_ast[j][i] = dtheta_hb7_ast[i][j]; b_hb7[j][i] = b_hb7[i][j]; dtheta_hb7_c[j][i] = dtheta_hb7_c[i][j]; a_hb8[j][i] = a_hb8[i][j]; theta_hb8_0[j][i] = theta_hb8_0[i][j]; dtheta_hb8_ast[j][i] = dtheta_hb8_ast[i][j]; b_hb8[j][i] = b_hb8[i][j]; dtheta_hb8_c[j][i] = dtheta_hb8_c[i][j]; cutsq_hb_hc[i][j] = cut_hb_hc[i][j]*cut_hb_hc[i][j]; cutsq_hb_hc[j][i] = cutsq_hb_hc[i][j]; // set the master list distance cutoff return cut_hb_hc[i][j]; } /* ---------------------------------------------------------------------- proc 0 writes to restart file ------------------------------------------------------------------------- */ void PairOxdnaHbond::write_restart(FILE *fp) { write_restart_settings(fp); int i,j; for (i = 1; i <= atom->ntypes; i++) for (j = i; j <= atom->ntypes; j++) { fwrite(&setflag[i][j],sizeof(int),1,fp); if (setflag[i][j]) { fwrite(&epsilon_hb[i][j],sizeof(double),1,fp); fwrite(&a_hb[i][j],sizeof(double),1,fp); fwrite(&cut_hb_0[i][j],sizeof(double),1,fp); fwrite(&cut_hb_c[i][j],sizeof(double),1,fp); fwrite(&cut_hb_lo[i][j],sizeof(double),1,fp); fwrite(&cut_hb_hi[i][j],sizeof(double),1,fp); fwrite(&cut_hb_lc[i][j],sizeof(double),1,fp); fwrite(&cut_hb_hc[i][j],sizeof(double),1,fp); fwrite(&b_hb_lo[i][j],sizeof(double),1,fp); fwrite(&b_hb_hi[i][j],sizeof(double),1,fp); fwrite(&shift_hb[i][j],sizeof(double),1,fp); fwrite(&a_hb1[i][j],sizeof(double),1,fp); fwrite(&theta_hb1_0[i][j],sizeof(double),1,fp); fwrite(&dtheta_hb1_ast[i][j],sizeof(double),1,fp); fwrite(&b_hb1[i][j],sizeof(double),1,fp); fwrite(&dtheta_hb1_c[i][j],sizeof(double),1,fp); fwrite(&a_hb2[i][j],sizeof(double),1,fp); fwrite(&theta_hb2_0[i][j],sizeof(double),1,fp); fwrite(&dtheta_hb2_ast[i][j],sizeof(double),1,fp); fwrite(&b_hb2[i][j],sizeof(double),1,fp); fwrite(&dtheta_hb2_c[i][j],sizeof(double),1,fp); fwrite(&a_hb3[i][j],sizeof(double),1,fp); fwrite(&theta_hb3_0[i][j],sizeof(double),1,fp); fwrite(&dtheta_hb3_ast[i][j],sizeof(double),1,fp); fwrite(&b_hb3[i][j],sizeof(double),1,fp); fwrite(&dtheta_hb3_c[i][j],sizeof(double),1,fp); fwrite(&a_hb4[i][j],sizeof(double),1,fp); fwrite(&theta_hb4_0[i][j],sizeof(double),1,fp); fwrite(&dtheta_hb4_ast[i][j],sizeof(double),1,fp); fwrite(&b_hb4[i][j],sizeof(double),1,fp); fwrite(&dtheta_hb4_c[i][j],sizeof(double),1,fp); fwrite(&a_hb7[i][j],sizeof(double),1,fp); fwrite(&theta_hb7_0[i][j],sizeof(double),1,fp); fwrite(&dtheta_hb7_ast[i][j],sizeof(double),1,fp); fwrite(&b_hb7[i][j],sizeof(double),1,fp); fwrite(&dtheta_hb7_c[i][j],sizeof(double),1,fp); fwrite(&a_hb8[i][j],sizeof(double),1,fp); fwrite(&theta_hb8_0[i][j],sizeof(double),1,fp); fwrite(&dtheta_hb8_ast[i][j],sizeof(double),1,fp); fwrite(&b_hb8[i][j],sizeof(double),1,fp); fwrite(&dtheta_hb8_c[i][j],sizeof(double),1,fp); } } } /* ---------------------------------------------------------------------- proc 0 reads from restart file, bcasts ------------------------------------------------------------------------- */ void PairOxdnaHbond::read_restart(FILE *fp) { read_restart_settings(fp); allocate(); int i,j; int me = comm->me; for (i = 1; i <= atom->ntypes; i++) for (j = i; j <= atom->ntypes; j++) { if (me == 0) fread(&setflag[i][j],sizeof(int),1,fp); MPI_Bcast(&setflag[i][j],1,MPI_INT,0,world); if (setflag[i][j]) { if (me == 0) { fread(&epsilon_hb[i][j],sizeof(double),1,fp); fread(&a_hb[i][j],sizeof(double),1,fp); fread(&cut_hb_0[i][j],sizeof(double),1,fp); fread(&cut_hb_c[i][j],sizeof(double),1,fp); fread(&cut_hb_lo[i][j],sizeof(double),1,fp); fread(&cut_hb_hi[i][j],sizeof(double),1,fp); fread(&cut_hb_lc[i][j],sizeof(double),1,fp); fread(&cut_hb_hc[i][j],sizeof(double),1,fp); fread(&b_hb_lo[i][j],sizeof(double),1,fp); fread(&b_hb_hi[i][j],sizeof(double),1,fp); fread(&shift_hb[i][j],sizeof(double),1,fp); fread(&a_hb1[i][j],sizeof(double),1,fp); fread(&theta_hb1_0[i][j],sizeof(double),1,fp); fread(&dtheta_hb1_ast[i][j],sizeof(double),1,fp); fread(&b_hb1[i][j],sizeof(double),1,fp); fread(&dtheta_hb1_c[i][j],sizeof(double),1,fp); fread(&a_hb2[i][j],sizeof(double),1,fp); fread(&theta_hb2_0[i][j],sizeof(double),1,fp); fread(&dtheta_hb2_ast[i][j],sizeof(double),1,fp); fread(&b_hb2[i][j],sizeof(double),1,fp); fread(&dtheta_hb2_c[i][j],sizeof(double),1,fp); fread(&a_hb3[i][j],sizeof(double),1,fp); fread(&theta_hb3_0[i][j],sizeof(double),1,fp); fread(&dtheta_hb3_ast[i][j],sizeof(double),1,fp); fread(&b_hb3[i][j],sizeof(double),1,fp); fread(&dtheta_hb3_c[i][j],sizeof(double),1,fp); fread(&a_hb4[i][j],sizeof(double),1,fp); fread(&theta_hb4_0[i][j],sizeof(double),1,fp); fread(&dtheta_hb4_ast[i][j],sizeof(double),1,fp); fread(&b_hb4[i][j],sizeof(double),1,fp); fread(&dtheta_hb4_c[i][j],sizeof(double),1,fp); fread(&a_hb7[i][j],sizeof(double),1,fp); fread(&theta_hb7_0[i][j],sizeof(double),1,fp); fread(&dtheta_hb7_ast[i][j],sizeof(double),1,fp); fread(&b_hb7[i][j],sizeof(double),1,fp); fread(&dtheta_hb7_c[i][j],sizeof(double),1,fp); fread(&a_hb8[i][j],sizeof(double),1,fp); fread(&theta_hb8_0[i][j],sizeof(double),1,fp); fread(&dtheta_hb8_ast[i][j],sizeof(double),1,fp); fread(&b_hb8[i][j],sizeof(double),1,fp); fread(&dtheta_hb8_c[i][j],sizeof(double),1,fp); } MPI_Bcast(&epsilon_hb[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&a_hb[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&cut_hb_0[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&cut_hb_c[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&cut_hb_lo[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&cut_hb_hi[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&cut_hb_lc[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&cut_hb_hc[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&b_hb_lo[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&b_hb_hi[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&shift_hb[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&a_hb1[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&theta_hb1_0[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&dtheta_hb1_ast[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&b_hb1[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&dtheta_hb1_c[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&a_hb2[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&theta_hb2_0[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&dtheta_hb2_ast[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&b_hb2[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&dtheta_hb2_c[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&a_hb3[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&theta_hb3_0[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&dtheta_hb3_ast[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&b_hb3[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&dtheta_hb3_c[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&a_hb4[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&theta_hb4_0[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&dtheta_hb4_ast[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&b_hb4[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&dtheta_hb4_c[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&a_hb7[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&theta_hb7_0[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&dtheta_hb7_ast[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&b_hb7[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&dtheta_hb7_c[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&a_hb8[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&theta_hb8_0[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&dtheta_hb8_ast[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&b_hb8[i][j],1,MPI_DOUBLE,0,world); MPI_Bcast(&dtheta_hb8_c[i][j],1,MPI_DOUBLE,0,world); } } } /* ---------------------------------------------------------------------- proc 0 writes to restart file ------------------------------------------------------------------------- */ void PairOxdnaHbond::write_restart_settings(FILE *fp) { fwrite(&offset_flag,sizeof(int),1,fp); fwrite(&mix_flag,sizeof(int),1,fp); fwrite(&tail_flag,sizeof(int),1,fp); } /* ---------------------------------------------------------------------- proc 0 reads from restart file, bcasts ------------------------------------------------------------------------- */ void PairOxdnaHbond::read_restart_settings(FILE *fp) { int me = comm->me; if (me == 0) { fread(&offset_flag,sizeof(int),1,fp); fread(&mix_flag,sizeof(int),1,fp); fread(&tail_flag,sizeof(int),1,fp); } MPI_Bcast(&offset_flag,1,MPI_INT,0,world); MPI_Bcast(&mix_flag,1,MPI_INT,0,world); MPI_Bcast(&tail_flag,1,MPI_INT,0,world); } /* ---------------------------------------------------------------------- proc 0 writes to data file ------------------------------------------------------------------------- */ void PairOxdnaHbond::write_data(FILE *fp) { for (int i = 1; i <= atom->ntypes; i++) fprintf(fp,""%d\\ %g %g %g %g %g %g\\ %g %g %g %g %g\\ %g %g %g %g %g\\ %g %g %g %g %g\\ %g %g %g %g %g\\ %g %g %g %g %g\\ %g %g %g %g %g\\ %g %g %g %g %g\\ \\n"",i, epsilon_hb[i][i],a_hb[i][i],cut_hb_0[i][i],cut_hb_c[i][i],cut_hb_lo[i][i],cut_hb_hi[i][i], cut_hb_lc[i][i],cut_hb_hc[i][i],b_hb_lo[i][i],b_hb_hi[i][i],shift_hb[i][i], a_hb1[i][i],theta_hb1_0[i][i],dtheta_hb1_ast[i][i],b_hb1[i][i],dtheta_hb1_c[i][i], a_hb2[i][i],theta_hb2_0[i][i],dtheta_hb2_ast[i][i],b_hb2[i][i],dtheta_hb2_c[i][i], a_hb3[i][i],theta_hb3_0[i][i],dtheta_hb3_ast[i][i],b_hb3[i][i],dtheta_hb3_c[i][i], a_hb4[i][i],theta_hb4_0[i][i],dtheta_hb4_ast[i][i],b_hb4[i][i],dtheta_hb4_c[i][i], a_hb7[i][i],theta_hb7_0[i][i],dtheta_hb7_ast[i][i],b_hb7[i][i],dtheta_hb7_c[i][i], a_hb8[i][i],theta_hb8_0[i][i],dtheta_hb8_ast[i][i],b_hb8[i][i],dtheta_hb8_c[i][i]); } /* ---------------------------------------------------------------------- proc 0 writes all pairs to data file ------------------------------------------------------------------------- */ void PairOxdnaHbond::write_data_all(FILE *fp) { for (int i = 1; i <= atom->ntypes; i++) for (int j = i; j <= atom->ntypes; j++) fprintf(fp,""%d %d\\ %g %g %g %g %g %g\\ %g %g %g %g %g\\ %g %g %g %g %g\\ %g %g %g %g %g\\ %g %g %g %g %g\\ %g %g %g %g %g\\ %g %g %g %g %g\\ %g %g %g %g %g\\ \\n"",i,j, epsilon_hb[i][j],a_hb[i][j],cut_hb_0[i][j],cut_hb_c[i][j],cut_hb_lo[i][j],cut_hb_hi[i][j], cut_hb_lc[i][j],cut_hb_hc[i][j],b_hb_lo[i][j],b_hb_hi[i][j],shift_hb[i][j], a_hb1[i][j],theta_hb1_0[i][j],dtheta_hb1_ast[i][j],b_hb1[i][j],dtheta_hb1_c[i][j], a_hb2[i][j],theta_hb2_0[i][j],dtheta_hb2_ast[i][j],b_hb2[i][j],dtheta_hb2_c[i][j], a_hb3[i][j],theta_hb3_0[i][j],dtheta_hb3_ast[i][j],b_hb3[i][j],dtheta_hb3_c[i][j], a_hb4[i][j],theta_hb4_0[i][j],dtheta_hb4_ast[i][j],b_hb4[i][j],dtheta_hb4_c[i][j], a_hb7[i][j],theta_hb7_0[i][j],dtheta_hb7_ast[i][j],b_hb7[i][j],dtheta_hb7_c[i][j], a_hb8[i][j],theta_hb8_0[i][j],dtheta_hb8_ast[i][j],b_hb8[i][j],dtheta_hb8_c[i][j]); } /* ---------------------------------------------------------------------- */ void *PairOxdnaHbond::extract(const char *str, int &dim) { dim = 2; if (strcmp(str,""epsilon_hb"") == 0) return (void *) epsilon_hb; if (strcmp(str,""a_hb"") == 0) return (void *) a_hb; if (strcmp(str,""cut_hb_0"") == 0) return (void *) cut_hb_0; if (strcmp(str,""cut_hb_c"") == 0) return (void *) cut_hb_c; if (strcmp(str,""cut_hb_lo"") == 0) return (void *) cut_hb_lo; if (strcmp(str,""cut_hb_hi"") == 0) return (void *) cut_hb_hi; if (strcmp(str,""cut_hb_lc"") == 0) return (void *) cut_hb_lc; if (strcmp(str,""cut_hb_hc"") == 0) return (void *) cut_hb_hc; if (strcmp(str,""b_hb_lo"") == 0) return (void *) b_hb_lo; if (strcmp(str,""b_hb_hi"") == 0) return (void *) b_hb_hi; if (strcmp(str,""shift_hb"") == 0) return (void *) shift_hb; if (strcmp(str,""a_hb1"") == 0) return (void *) a_hb1; if (strcmp(str,""theta_hb1_0"") == 0) return (void *) theta_hb1_0; if (strcmp(str,""dtheta_hb1_ast"") == 0) return (void *) dtheta_hb1_ast; if (strcmp(str,""b_hb1"") == 0) return (void *) b_hb1; if (strcmp(str,""dtheta_hb1_c"") == 0) return (void *) dtheta_hb1_c; if (strcmp(str,""a_hb2"") == 0) return (void *) a_hb2; if (strcmp(str,""theta_hb2_0"") == 0) return (void *) theta_hb2_0; if (strcmp(str,""dtheta_hb2_ast"") == 0) return (void *) dtheta_hb2_ast; if (strcmp(str,""b_hb2"") == 0) return (void *) b_hb2; if (strcmp(str,""dtheta_hb2_c"") == 0) return (void *) dtheta_hb2_c; if (strcmp(str,""a_hb3"") == 0) return (void *) a_hb3; if (strcmp(str,""theta_hb3_0"") == 0) return (void *) theta_hb3_0; if (strcmp(str,""dtheta_hb3_ast"") == 0) return (void *) dtheta_hb3_ast; if (strcmp(str,""b_hb3"") == 0) return (void *) b_hb3; if (strcmp(str,""dtheta_hb3_c"") == 0) return (void *) dtheta_hb3_c; if (strcmp(str,""a_hb4"") == 0) return (void *) a_hb4; if (strcmp(str,""theta_hb4_0"") == 0) return (void *) theta_hb4_0; if (strcmp(str,""dtheta_hb4_ast"") == 0) return (void *) dtheta_hb4_ast; if (strcmp(str,""b_hb4"") == 0) return (void *) b_hb4; if (strcmp(str,""dtheta_hb4_c"") == 0) return (void *) dtheta_hb4_c; if (strcmp(str,""a_hb7"") == 0) return (void *) a_hb7; if (strcmp(str,""theta_hb7_0"") == 0) return (void *) theta_hb7_0; if (strcmp(str,""dtheta_hb7_ast"") == 0) return (void *) dtheta_hb7_ast; if (strcmp(str,""b_hb7"") == 0) return (void *) b_hb7; if (strcmp(str,""dtheta_hb7_c"") == 0) return (void *) dtheta_hb7_c; if (strcmp(str,""a_hb8"") == 0) return (void *) a_hb8; if (strcmp(str,""theta_hb8_0"") == 0) return (void *) theta_hb8_0; if (strcmp(str,""dtheta_hb8_ast"") == 0) return (void *) dtheta_hb8_ast; if (strcmp(str,""b_hb8"") == 0) return (void *) b_hb8; if (strcmp(str,""dtheta_hb8_c"") == 0) return (void *) dtheta_hb8_c; return NULL; } ",16234,True,3215.541365504242,median "#include ""il2cpp-config.h"" #ifndef _MSC_VER # include #else # include #endif #include #include #include #include #include #include #include #include ""il2cpp-class-internals.h"" #include ""codegen/il2cpp-codegen.h"" #include ""il2cpp-object-internals.h"" template struct VirtActionInvoker4 { typedef void (*Action)(void*, T1, T2, T3, T4, const RuntimeMethod*); static inline void Invoke (Il2CppMethodSlot slot, RuntimeObject* obj, T1 p1, T2 p2, T3 p3, T4 p4) { const VirtualInvokeData& invokeData = il2cpp_codegen_get_virtual_invoke_data(slot, obj); ((Action)invokeData.methodPtr)(obj, p1, p2, p3, p4, invokeData.method); } }; struct VirtActionInvoker0 { typedef void (*Action)(void*, const RuntimeMethod*); static inline void Invoke (Il2CppMethodSlot slot, RuntimeObject* obj) { const VirtualInvokeData& invokeData = il2cpp_codegen_get_virtual_invoke_data(slot, obj); ((Action)invokeData.methodPtr)(obj, invokeData.method); } }; template struct GenericVirtActionInvoker4 { typedef void (*Action)(void*, T1, T2, T3, T4, const RuntimeMethod*); static inline void Invoke (const RuntimeMethod* method, RuntimeObject* obj, T1 p1, T2 p2, T3 p3, T4 p4) { VirtualInvokeData invokeData; il2cpp_codegen_get_generic_virtual_invoke_data(method, obj, &invokeData); ((Action)invokeData.methodPtr)(obj, p1, p2, p3, p4, invokeData.method); } }; struct GenericVirtActionInvoker0 { typedef void (*Action)(void*, const RuntimeMethod*); static inline void Invoke (const RuntimeMethod* method, RuntimeObject* obj) { VirtualInvokeData invokeData; il2cpp_codegen_get_generic_virtual_invoke_data(method, obj, &invokeData); ((Action)invokeData.methodPtr)(obj, invokeData.method); } }; template struct InterfaceActionInvoker4 { typedef void (*Action)(void*, T1, T2, T3, T4, const RuntimeMethod*); static inline void Invoke (Il2CppMethodSlot slot, RuntimeClass* declaringInterface, RuntimeObject* obj, T1 p1, T2 p2, T3 p3, T4 p4) { const VirtualInvokeData& invokeData = il2cpp_codegen_get_interface_invoke_data(slot, obj, declaringInterface); ((Action)invokeData.methodPtr)(obj, p1, p2, p3, p4, invokeData.method); } }; struct InterfaceActionInvoker0 { typedef void (*Action)(void*, const RuntimeMethod*); static inline void Invoke (Il2CppMethodSlot slot, RuntimeClass* declaringInterface, RuntimeObject* obj) { const VirtualInvokeData& invokeData = il2cpp_codegen_get_interface_invoke_data(slot, obj, declaringInterface); ((Action)invokeData.methodPtr)(obj, invokeData.method); } }; template struct GenericInterfaceActionInvoker4 { typedef void (*Action)(void*, T1, T2, T3, T4, const RuntimeMethod*); static inline void Invoke (const RuntimeMethod* method, RuntimeObject* obj, T1 p1, T2 p2, T3 p3, T4 p4) { VirtualInvokeData invokeData; il2cpp_codegen_get_generic_interface_invoke_data(method, obj, &invokeData); ((Action)invokeData.methodPtr)(obj, p1, p2, p3, p4, invokeData.method); } }; struct GenericInterfaceActionInvoker0 { typedef void (*Action)(void*, const RuntimeMethod*); static inline void Invoke (const RuntimeMethod* method, RuntimeObject* obj) { VirtualInvokeData invokeData; il2cpp_codegen_get_generic_interface_invoke_data(method, obj, &invokeData); ((Action)invokeData.methodPtr)(obj, invokeData.method); } }; // System.Action struct Action_t1264377477; // System.Action`1 struct Action_1_t269755560; // System.Action`3 struct Action_3_t3050575418; // System.AsyncCallback struct AsyncCallback_t3962456242; // System.Char[] struct CharU5BU5D_t3528271667; // System.DelegateData struct DelegateData_t1677132599; // System.IAsyncResult struct IAsyncResult_t767004451; // System.Reflection.MethodInfo struct MethodInfo_t; // System.String struct String_t; // System.Void struct Void_t1185182177; // UnityEngine.Analytics.AnalyticsSessionInfo/SessionStateChanged struct SessionStateChanged_t3163629820; // UnityEngine.RemoteConfigSettings struct RemoteConfigSettings_t1247263429; // UnityEngine.RemoteSettings/UpdatedEventHandler struct UpdatedEventHandler_t1027848393; extern RuntimeClass* Action_1_t269755560_il2cpp_TypeInfo_var; extern RuntimeClass* AnalyticsSessionInfo_t2322308579_il2cpp_TypeInfo_var; extern RuntimeClass* AnalyticsSessionState_t681173134_il2cpp_TypeInfo_var; extern RuntimeClass* Boolean_t97287965_il2cpp_TypeInfo_var; extern RuntimeClass* Int64_t3736567304_il2cpp_TypeInfo_var; extern RuntimeClass* IntPtr_t_il2cpp_TypeInfo_var; extern RuntimeClass* RemoteSettings_t1718627291_il2cpp_TypeInfo_var; extern const RuntimeMethod* Action_1_Invoke_m1933767679_RuntimeMethod_var; extern const RuntimeMethod* Action_3_Invoke_m1011371804_RuntimeMethod_var; extern const uint32_t AnalyticsSessionInfo_CallSessionStateChanged_m1270932408_MetadataUsageId; extern const uint32_t RemoteConfigSettings_Destroy_m1854335118_MetadataUsageId; extern const uint32_t RemoteConfigSettings_RemoteConfigSettingsUpdated_m2409101234_MetadataUsageId; extern const uint32_t RemoteConfigSettings_t1247263429_com_FromNativeMethodDefinition_MetadataUsageId; extern const uint32_t RemoteConfigSettings_t1247263429_pinvoke_FromNativeMethodDefinition_MetadataUsageId; extern const uint32_t RemoteSettings_RemoteSettingsBeforeFetchFromServer_m4228537265_MetadataUsageId; extern const uint32_t RemoteSettings_RemoteSettingsUpdateCompleted_m2956290507_MetadataUsageId; extern const uint32_t RemoteSettings_RemoteSettingsUpdated_m1182006011_MetadataUsageId; extern const uint32_t SessionStateChanged_BeginInvoke_m1132835327_MetadataUsageId; #ifndef U3CMODULEU3E_T692745541_H #define U3CMODULEU3E_T692745541_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // struct U3CModuleU3E_t692745541 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // U3CMODULEU3E_T692745541_H #ifndef RUNTIMEOBJECT_H #define RUNTIMEOBJECT_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // System.Object #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEOBJECT_H struct Il2CppArrayBounds; #ifndef RUNTIMEARRAY_H #define RUNTIMEARRAY_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // System.Array #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEARRAY_H #ifndef VALUETYPE_T3640485471_H #define VALUETYPE_T3640485471_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // System.ValueType struct ValueType_t3640485471 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_t3640485471_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_t3640485471_marshaled_com { }; #endif // VALUETYPE_T3640485471_H #ifndef ANALYTICSSESSIONINFO_T2322308579_H #define ANALYTICSSESSIONINFO_T2322308579_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // UnityEngine.Analytics.AnalyticsSessionInfo struct AnalyticsSessionInfo_t2322308579 : public RuntimeObject { public: public: }; struct AnalyticsSessionInfo_t2322308579_StaticFields { public: // UnityEngine.Analytics.AnalyticsSessionInfo/SessionStateChanged UnityEngine.Analytics.AnalyticsSessionInfo::sessionStateChanged SessionStateChanged_t3163629820 * ___sessionStateChanged_0; public: inline static int32_t get_offset_of_sessionStateChanged_0() { return static_cast(offsetof(AnalyticsSessionInfo_t2322308579_StaticFields, ___sessionStateChanged_0)); } inline SessionStateChanged_t3163629820 * get_sessionStateChanged_0() const { return ___sessionStateChanged_0; } inline SessionStateChanged_t3163629820 ** get_address_of_sessionStateChanged_0() { return &___sessionStateChanged_0; } inline void set_sessionStateChanged_0(SessionStateChanged_t3163629820 * value) { ___sessionStateChanged_0 = value; Il2CppCodeGenWriteBarrier((&___sessionStateChanged_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ANALYTICSSESSIONINFO_T2322308579_H #ifndef REMOTESETTINGS_T1718627291_H #define REMOTESETTINGS_T1718627291_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // UnityEngine.RemoteSettings struct RemoteSettings_t1718627291 : public RuntimeObject { public: public: }; struct RemoteSettings_t1718627291_StaticFields { public: // UnityEngine.RemoteSettings/UpdatedEventHandler UnityEngine.RemoteSettings::Updated UpdatedEventHandler_t1027848393 * ___Updated_0; // System.Action UnityEngine.RemoteSettings::BeforeFetchFromServer Action_t1264377477 * ___BeforeFetchFromServer_1; // System.Action`3 UnityEngine.RemoteSettings::Completed Action_3_t3050575418 * ___Completed_2; public: inline static int32_t get_offset_of_Updated_0() { return static_cast(offsetof(RemoteSettings_t1718627291_StaticFields, ___Updated_0)); } inline UpdatedEventHandler_t1027848393 * get_Updated_0() const { return ___Updated_0; } inline UpdatedEventHandler_t1027848393 ** get_address_of_Updated_0() { return &___Updated_0; } inline void set_Updated_0(UpdatedEventHandler_t1027848393 * value) { ___Updated_0 = value; Il2CppCodeGenWriteBarrier((&___Updated_0), value); } inline static int32_t get_offset_of_BeforeFetchFromServer_1() { return static_cast(offsetof(RemoteSettings_t1718627291_StaticFields, ___BeforeFetchFromServer_1)); } inline Action_t1264377477 * get_BeforeFetchFromServer_1() const { return ___BeforeFetchFromServer_1; } inline Action_t1264377477 ** get_address_of_BeforeFetchFromServer_1() { return &___BeforeFetchFromServer_1; } inline void set_BeforeFetchFromServer_1(Action_t1264377477 * value) { ___BeforeFetchFromServer_1 = value; Il2CppCodeGenWriteBarrier((&___BeforeFetchFromServer_1), value); } inline static int32_t get_offset_of_Completed_2() { return static_cast(offsetof(RemoteSettings_t1718627291_StaticFields, ___Completed_2)); } inline Action_3_t3050575418 * get_Completed_2() const { return ___Completed_2; } inline Action_3_t3050575418 ** get_address_of_Completed_2() { return &___Completed_2; } inline void set_Completed_2(Action_3_t3050575418 * value) { ___Completed_2 = value; Il2CppCodeGenWriteBarrier((&___Completed_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REMOTESETTINGS_T1718627291_H #ifndef BOOLEAN_T97287965_H #define BOOLEAN_T97287965_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // System.Boolean struct Boolean_t97287965 { public: // System.Boolean System.Boolean::m_value bool ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast(offsetof(Boolean_t97287965, ___m_value_2)); } inline bool get_m_value_2() const { return ___m_value_2; } inline bool* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(bool value) { ___m_value_2 = value; } }; struct Boolean_t97287965_StaticFields { public: // System.String System.Boolean::FalseString String_t* ___FalseString_0; // System.String System.Boolean::TrueString String_t* ___TrueString_1; public: inline static int32_t get_offset_of_FalseString_0() { return static_cast(offsetof(Boolean_t97287965_StaticFields, ___FalseString_0)); } inline String_t* get_FalseString_0() const { return ___FalseString_0; } inline String_t** get_address_of_FalseString_0() { return &___FalseString_0; } inline void set_FalseString_0(String_t* value) { ___FalseString_0 = value; Il2CppCodeGenWriteBarrier((&___FalseString_0), value); } inline static int32_t get_offset_of_TrueString_1() { return static_cast(offsetof(Boolean_t97287965_StaticFields, ___TrueString_1)); } inline String_t* get_TrueString_1() const { return ___TrueString_1; } inline String_t** get_address_of_TrueString_1() { return &___TrueString_1; } inline void set_TrueString_1(String_t* value) { ___TrueString_1 = value; Il2CppCodeGenWriteBarrier((&___TrueString_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BOOLEAN_T97287965_H #ifndef ENUM_T4135868527_H #define ENUM_T4135868527_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // System.Enum struct Enum_t4135868527 : public ValueType_t3640485471 { public: public: }; struct Enum_t4135868527_StaticFields { public: // System.Char[] System.Enum::split_char CharU5BU5D_t3528271667* ___split_char_0; public: inline static int32_t get_offset_of_split_char_0() { return static_cast(offsetof(Enum_t4135868527_StaticFields, ___split_char_0)); } inline CharU5BU5D_t3528271667* get_split_char_0() const { return ___split_char_0; } inline CharU5BU5D_t3528271667** get_address_of_split_char_0() { return &___split_char_0; } inline void set_split_char_0(CharU5BU5D_t3528271667* value) { ___split_char_0 = value; Il2CppCodeGenWriteBarrier((&___split_char_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Enum struct Enum_t4135868527_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t4135868527_marshaled_com { }; #endif // ENUM_T4135868527_H #ifndef INT32_T2950945753_H #define INT32_T2950945753_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // System.Int32 struct Int32_t2950945753 { public: // System.Int32 System.Int32::m_value int32_t ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast(offsetof(Int32_t2950945753, ___m_value_2)); } inline int32_t get_m_value_2() const { return ___m_value_2; } inline int32_t* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(int32_t value) { ___m_value_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT32_T2950945753_H #ifndef INT64_T3736567304_H #define INT64_T3736567304_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // System.Int64 struct Int64_t3736567304 { public: // System.Int64 System.Int64::m_value int64_t ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast(offsetof(Int64_t3736567304, ___m_value_2)); } inline int64_t get_m_value_2() const { return ___m_value_2; } inline int64_t* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(int64_t value) { ___m_value_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT64_T3736567304_H #ifndef INTPTR_T_H #define INTPTR_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // System.IntPtr struct IntPtr_t { public: // System.Void* System.IntPtr::m_value void* ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast(offsetof(IntPtr_t, ___m_value_0)); } inline void* get_m_value_0() const { return ___m_value_0; } inline void** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(void* value) { ___m_value_0 = value; } }; struct IntPtr_t_StaticFields { public: // System.IntPtr System.IntPtr::Zero intptr_t ___Zero_1; public: inline static int32_t get_offset_of_Zero_1() { return static_cast(offsetof(IntPtr_t_StaticFields, ___Zero_1)); } inline intptr_t get_Zero_1() const { return ___Zero_1; } inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; } inline void set_Zero_1(intptr_t value) { ___Zero_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTPTR_T_H #ifndef VOID_T1185182177_H #define VOID_T1185182177_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // System.Void struct Void_t1185182177 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VOID_T1185182177_H #ifndef DELEGATE_T1188392813_H #define DELEGATE_T1188392813_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // System.Delegate struct Delegate_t1188392813 : public RuntimeObject { public: // System.IntPtr System.Delegate::method_ptr Il2CppMethodPointer ___method_ptr_0; // System.IntPtr System.Delegate::invoke_impl intptr_t ___invoke_impl_1; // System.Object System.Delegate::m_target RuntimeObject * ___m_target_2; // System.IntPtr System.Delegate::method intptr_t ___method_3; // System.IntPtr System.Delegate::delegate_trampoline intptr_t ___delegate_trampoline_4; // System.IntPtr System.Delegate::method_code intptr_t ___method_code_5; // System.Reflection.MethodInfo System.Delegate::method_info MethodInfo_t * ___method_info_6; // System.Reflection.MethodInfo System.Delegate::original_method_info MethodInfo_t * ___original_method_info_7; // System.DelegateData System.Delegate::data DelegateData_t1677132599 * ___data_8; public: inline static int32_t get_offset_of_method_ptr_0() { return static_cast(offsetof(Delegate_t1188392813, ___method_ptr_0)); } inline Il2CppMethodPointer get_method_ptr_0() const { return ___method_ptr_0; } inline Il2CppMethodPointer* get_address_of_method_ptr_0() { return &___method_ptr_0; } inline void set_method_ptr_0(Il2CppMethodPointer value) { ___method_ptr_0 = value; } inline static int32_t get_offset_of_invoke_impl_1() { return static_cast(offsetof(Delegate_t1188392813, ___invoke_impl_1)); } inline intptr_t get_invoke_impl_1() const { return ___invoke_impl_1; } inline intptr_t* get_address_of_invoke_impl_1() { return &___invoke_impl_1; } inline void set_invoke_impl_1(intptr_t value) { ___invoke_impl_1 = value; } inline static int32_t get_offset_of_m_target_2() { return static_cast(offsetof(Delegate_t1188392813, ___m_target_2)); } inline RuntimeObject * get_m_target_2() const { return ___m_target_2; } inline RuntimeObject ** get_address_of_m_target_2() { return &___m_target_2; } inline void set_m_target_2(RuntimeObject * value) { ___m_target_2 = value; Il2CppCodeGenWriteBarrier((&___m_target_2), value); } inline static int32_t get_offset_of_method_3() { return static_cast(offsetof(Delegate_t1188392813, ___method_3)); } inline intptr_t get_method_3() const { return ___method_3; } inline intptr_t* get_address_of_method_3() { return &___method_3; } inline void set_method_3(intptr_t value) { ___method_3 = value; } inline static int32_t get_offset_of_delegate_trampoline_4() { return static_cast(offsetof(Delegate_t1188392813, ___delegate_trampoline_4)); } inline intptr_t get_delegate_trampoline_4() const { return ___delegate_trampoline_4; } inline intptr_t* get_address_of_delegate_trampoline_4() { return &___delegate_trampoline_4; } inline void set_delegate_trampoline_4(intptr_t value) { ___delegate_trampoline_4 = value; } inline static int32_t get_offset_of_method_code_5() { return static_cast(offsetof(Delegate_t1188392813, ___method_code_5)); } inline intptr_t get_method_code_5() const { return ___method_code_5; } inline intptr_t* get_address_of_method_code_5() { return &___method_code_5; } inline void set_method_code_5(intptr_t value) { ___method_code_5 = value; } inline static int32_t get_offset_of_method_info_6() { return static_cast(offsetof(Delegate_t1188392813, ___method_info_6)); } inline MethodInfo_t * get_method_info_6() const { return ___method_info_6; } inline MethodInfo_t ** get_address_of_method_info_6() { return &___method_info_6; } inline void set_method_info_6(MethodInfo_t * value) { ___method_info_6 = value; Il2CppCodeGenWriteBarrier((&___method_info_6), value); } inline static int32_t get_offset_of_original_method_info_7() { return static_cast(offsetof(Delegate_t1188392813, ___original_method_info_7)); } inline MethodInfo_t * get_original_method_info_7() const { return ___original_method_info_7; } inline MethodInfo_t ** get_address_of_original_method_info_7() { return &___original_method_info_7; } inline void set_original_method_info_7(MethodInfo_t * value) { ___original_method_info_7 = value; Il2CppCodeGenWriteBarrier((&___original_method_info_7), value); } inline static int32_t get_offset_of_data_8() { return static_cast(offsetof(Delegate_t1188392813, ___data_8)); } inline DelegateData_t1677132599 * get_data_8() const { return ___data_8; } inline DelegateData_t1677132599 ** get_address_of_data_8() { return &___data_8; } inline void set_data_8(DelegateData_t1677132599 * value) { ___data_8 = value; Il2CppCodeGenWriteBarrier((&___data_8), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DELEGATE_T1188392813_H #ifndef ANALYTICSSESSIONSTATE_T681173134_H #define ANALYTICSSESSIONSTATE_T681173134_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // UnityEngine.Analytics.AnalyticsSessionState struct AnalyticsSessionState_t681173134 { public: // System.Int32 UnityEngine.Analytics.AnalyticsSessionState::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast(offsetof(AnalyticsSessionState_t681173134, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ANALYTICSSESSIONSTATE_T681173134_H #ifndef REMOTECONFIGSETTINGS_T1247263429_H #define REMOTECONFIGSETTINGS_T1247263429_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // UnityEngine.RemoteConfigSettings struct RemoteConfigSettings_t1247263429 : public RuntimeObject { public: // System.IntPtr UnityEngine.RemoteConfigSettings::m_Ptr intptr_t ___m_Ptr_0; // System.Action`1 UnityEngine.RemoteConfigSettings::Updated Action_1_t269755560 * ___Updated_1; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast(offsetof(RemoteConfigSettings_t1247263429, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } inline static int32_t get_offset_of_Updated_1() { return static_cast(offsetof(RemoteConfigSettings_t1247263429, ___Updated_1)); } inline Action_1_t269755560 * get_Updated_1() const { return ___Updated_1; } inline Action_1_t269755560 ** get_address_of_Updated_1() { return &___Updated_1; } inline void set_Updated_1(Action_1_t269755560 * value) { ___Updated_1 = value; Il2CppCodeGenWriteBarrier((&___Updated_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.RemoteConfigSettings struct RemoteConfigSettings_t1247263429_marshaled_pinvoke { intptr_t ___m_Ptr_0; Il2CppMethodPointer ___Updated_1; }; // Native definition for COM marshalling of UnityEngine.RemoteConfigSettings struct RemoteConfigSettings_t1247263429_marshaled_com { intptr_t ___m_Ptr_0; Il2CppMethodPointer ___Updated_1; }; #endif // REMOTECONFIGSETTINGS_T1247263429_H #ifndef MULTICASTDELEGATE_T_H #define MULTICASTDELEGATE_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // System.MulticastDelegate struct MulticastDelegate_t : public Delegate_t1188392813 { public: // System.MulticastDelegate System.MulticastDelegate::prev MulticastDelegate_t * ___prev_9; // System.MulticastDelegate System.MulticastDelegate::kpm_next MulticastDelegate_t * ___kpm_next_10; public: inline static int32_t get_offset_of_prev_9() { return static_cast(offsetof(MulticastDelegate_t, ___prev_9)); } inline MulticastDelegate_t * get_prev_9() const { return ___prev_9; } inline MulticastDelegate_t ** get_address_of_prev_9() { return &___prev_9; } inline void set_prev_9(MulticastDelegate_t * value) { ___prev_9 = value; Il2CppCodeGenWriteBarrier((&___prev_9), value); } inline static int32_t get_offset_of_kpm_next_10() { return static_cast(offsetof(MulticastDelegate_t, ___kpm_next_10)); } inline MulticastDelegate_t * get_kpm_next_10() const { return ___kpm_next_10; } inline MulticastDelegate_t ** get_address_of_kpm_next_10() { return &___kpm_next_10; } inline void set_kpm_next_10(MulticastDelegate_t * value) { ___kpm_next_10 = value; Il2CppCodeGenWriteBarrier((&___kpm_next_10), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MULTICASTDELEGATE_T_H #ifndef ACTION_T1264377477_H #define ACTION_T1264377477_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // System.Action struct Action_t1264377477 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ACTION_T1264377477_H #ifndef ACTION_1_T269755560_H #define ACTION_1_T269755560_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // System.Action`1 struct Action_1_t269755560 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ACTION_1_T269755560_H #ifndef ACTION_3_T3050575418_H #define ACTION_3_T3050575418_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // System.Action`3 struct Action_3_t3050575418 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ACTION_3_T3050575418_H #ifndef ASYNCCALLBACK_T3962456242_H #define ASYNCCALLBACK_T3962456242_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // System.AsyncCallback struct AsyncCallback_t3962456242 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ASYNCCALLBACK_T3962456242_H #ifndef SESSIONSTATECHANGED_T3163629820_H #define SESSIONSTATECHANGED_T3163629820_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // UnityEngine.Analytics.AnalyticsSessionInfo/SessionStateChanged struct SessionStateChanged_t3163629820 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SESSIONSTATECHANGED_T3163629820_H #ifndef UPDATEDEVENTHANDLER_T1027848393_H #define UPDATEDEVENTHANDLER_T1027848393_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // UnityEngine.RemoteSettings/UpdatedEventHandler struct UpdatedEventHandler_t1027848393 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UPDATEDEVENTHANDLER_T1027848393_H // System.Void System.Action`1::Invoke(!0) extern ""C"" IL2CPP_METHOD_ATTR void Action_1_Invoke_m1933767679_gshared (Action_1_t269755560 * __this, bool p0, const RuntimeMethod* method); // System.Void System.Action`3::Invoke(!0,!1,!2) extern ""C"" IL2CPP_METHOD_ATTR void Action_3_Invoke_m1011371804_gshared (Action_3_t3050575418 * __this, bool p0, bool p1, int32_t p2, const RuntimeMethod* method); // System.Void UnityEngine.Analytics.AnalyticsSessionInfo/SessionStateChanged::Invoke(UnityEngine.Analytics.AnalyticsSessionState,System.Int64,System.Int64,System.Boolean) extern ""C"" IL2CPP_METHOD_ATTR void SessionStateChanged_Invoke_m4203746932 (SessionStateChanged_t3163629820 * __this, int32_t ___sessionState0, int64_t ___sessionId1, int64_t ___sessionElapsedTime2, bool ___sessionChanged3, const RuntimeMethod* method); // System.Void UnityEngine.RemoteConfigSettings::Destroy() extern ""C"" IL2CPP_METHOD_ATTR void RemoteConfigSettings_Destroy_m1854335118 (RemoteConfigSettings_t1247263429 * __this, const RuntimeMethod* method); // System.Void System.Object::Finalize() extern ""C"" IL2CPP_METHOD_ATTR void Object_Finalize_m3076187857 (RuntimeObject * __this, const RuntimeMethod* method); // System.Boolean System.IntPtr::op_Inequality(System.IntPtr,System.IntPtr) extern ""C"" IL2CPP_METHOD_ATTR bool IntPtr_op_Inequality_m3063970704 (RuntimeObject * __this /* static, unused */, intptr_t p0, intptr_t p1, const RuntimeMethod* method); // System.Void UnityEngine.RemoteConfigSettings::Internal_Destroy(System.IntPtr) extern ""C"" IL2CPP_METHOD_ATTR void RemoteConfigSettings_Internal_Destroy_m1072151938 (RuntimeObject * __this /* static, unused */, intptr_t ___ptr0, const RuntimeMethod* method); // System.Void System.GC::SuppressFinalize(System.Object) extern ""C"" IL2CPP_METHOD_ATTR void GC_SuppressFinalize_m1177400158 (RuntimeObject * __this /* static, unused */, RuntimeObject * p0, const RuntimeMethod* method); // System.Void System.Action`1::Invoke(!0) inline void Action_1_Invoke_m1933767679 (Action_1_t269755560 * __this, bool p0, const RuntimeMethod* method) { (( void (*) (Action_1_t269755560 *, bool, const RuntimeMethod*))Action_1_Invoke_m1933767679_gshared)(__this, p0, method); } // System.Void UnityEngine.RemoteSettings/UpdatedEventHandler::Invoke() extern ""C"" IL2CPP_METHOD_ATTR void UpdatedEventHandler_Invoke_m3026613363 (UpdatedEventHandler_t1027848393 * __this, const RuntimeMethod* method); // System.Void System.Action::Invoke() extern ""C"" IL2CPP_METHOD_ATTR void Action_Invoke_m937035532 (Action_t1264377477 * __this, const RuntimeMethod* method); // System.Void System.Action`3::Invoke(!0,!1,!2) inline void Action_3_Invoke_m1011371804 (Action_3_t3050575418 * __this, bool p0, bool p1, int32_t p2, const RuntimeMethod* method) { (( void (*) (Action_3_t3050575418 *, bool, bool, int32_t, const RuntimeMethod*))Action_3_Invoke_m1011371804_gshared)(__this, p0, p1, p2, method); } #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // System.Void UnityEngine.Analytics.AnalyticsSessionInfo::CallSessionStateChanged(UnityEngine.Analytics.AnalyticsSessionState,System.Int64,System.Int64,System.Boolean) extern ""C"" IL2CPP_METHOD_ATTR void AnalyticsSessionInfo_CallSessionStateChanged_m1270932408 (RuntimeObject * __this /* static, unused */, int32_t ___sessionState0, int64_t ___sessionId1, int64_t ___sessionElapsedTime2, bool ___sessionChanged3, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (AnalyticsSessionInfo_CallSessionStateChanged_m1270932408_MetadataUsageId); s_Il2CppMethodInitialized = true; } SessionStateChanged_t3163629820 * V_0 = NULL; { SessionStateChanged_t3163629820 * L_0 = ((AnalyticsSessionInfo_t2322308579_StaticFields*)il2cpp_codegen_static_fields_for(AnalyticsSessionInfo_t2322308579_il2cpp_TypeInfo_var))->get_sessionStateChanged_0(); V_0 = L_0; SessionStateChanged_t3163629820 * L_1 = V_0; if (!L_1) { goto IL_0017; } } { SessionStateChanged_t3163629820 * L_2 = V_0; int32_t L_3 = ___sessionState0; int64_t L_4 = ___sessionId1; int64_t L_5 = ___sessionElapsedTime2; bool L_6 = ___sessionChanged3; NullCheck(L_2); SessionStateChanged_Invoke_m4203746932(L_2, L_3, L_4, L_5, L_6, /*hidden argument*/NULL); } IL_0017: { return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif extern ""C"" void DelegatePInvokeWrapper_SessionStateChanged_t3163629820 (SessionStateChanged_t3163629820 * __this, int32_t ___sessionState0, int64_t ___sessionId1, int64_t ___sessionElapsedTime2, bool ___sessionChanged3, const RuntimeMethod* method) { typedef void (DEFAULT_CALL *PInvokeFunc)(int32_t, int64_t, int64_t, int32_t); PInvokeFunc il2cppPInvokeFunc = reinterpret_cast(il2cpp_codegen_get_method_pointer(((RuntimeDelegate*)__this)->method)); // Native function invocation il2cppPInvokeFunc(___sessionState0, ___sessionId1, ___sessionElapsedTime2, static_cast(___sessionChanged3)); } // System.Void UnityEngine.Analytics.AnalyticsSessionInfo/SessionStateChanged::.ctor(System.Object,System.IntPtr) extern ""C"" IL2CPP_METHOD_ATTR void SessionStateChanged__ctor_m2637910444 (SessionStateChanged_t3163629820 * __this, RuntimeObject * ___object0, intptr_t ___method1, const RuntimeMethod* method) { __this->set_method_ptr_0(il2cpp_codegen_get_method_pointer((RuntimeMethod*)___method1)); __this->set_method_3(___method1); __this->set_m_target_2(___object0); } // System.Void UnityEngine.Analytics.AnalyticsSessionInfo/SessionStateChanged::Invoke(UnityEngine.Analytics.AnalyticsSessionState,System.Int64,System.Int64,System.Boolean) extern ""C"" IL2CPP_METHOD_ATTR void SessionStateChanged_Invoke_m4203746932 (SessionStateChanged_t3163629820 * __this, int32_t ___sessionState0, int64_t ___sessionId1, int64_t ___sessionElapsedTime2, bool ___sessionChanged3, const RuntimeMethod* method) { if(__this->get_prev_9() != NULL) { SessionStateChanged_Invoke_m4203746932((SessionStateChanged_t3163629820 *)__this->get_prev_9(), ___sessionState0, ___sessionId1, ___sessionElapsedTime2, ___sessionChanged3, method); } Il2CppMethodPointer targetMethodPointer = __this->get_method_ptr_0(); RuntimeMethod* targetMethod = (RuntimeMethod*)(__this->get_method_3()); RuntimeObject* targetThis = __this->get_m_target_2(); il2cpp_codegen_raise_execution_engine_exception_if_method_is_not_found(targetMethod); bool ___methodIsStatic = MethodIsStatic(targetMethod); if (___methodIsStatic) { if (il2cpp_codegen_method_parameter_count(targetMethod) == 4) { // open { typedef void (*FunctionPointerType) (RuntimeObject *, int32_t, int64_t, int64_t, bool, const RuntimeMethod*); ((FunctionPointerType)targetMethodPointer)(NULL, ___sessionState0, ___sessionId1, ___sessionElapsedTime2, ___sessionChanged3, targetMethod); } } else { // closed { typedef void (*FunctionPointerType) (RuntimeObject *, void*, int32_t, int64_t, int64_t, bool, const RuntimeMethod*); ((FunctionPointerType)targetMethodPointer)(NULL, targetThis, ___sessionState0, ___sessionId1, ___sessionElapsedTime2, ___sessionChanged3, targetMethod); } } } else { { // closed if (il2cpp_codegen_method_is_virtual(targetMethod) && !il2cpp_codegen_object_is_of_sealed_type(targetThis) && il2cpp_codegen_delegate_has_invoker((Il2CppDelegate*)__this)) { if (il2cpp_codegen_method_is_generic_instance(targetMethod)) { if (il2cpp_codegen_method_is_interface_method(targetMethod)) GenericInterfaceActionInvoker4< int32_t, int64_t, int64_t, bool >::Invoke(targetMethod, targetThis, ___sessionState0, ___sessionId1, ___sessionElapsedTime2, ___sessionChanged3); else GenericVirtActionInvoker4< int32_t, int64_t, int64_t, bool >::Invoke(targetMethod, targetThis, ___sessionState0, ___sessionId1, ___sessionElapsedTime2, ___sessionChanged3); } else { if (il2cpp_codegen_method_is_interface_method(targetMethod)) InterfaceActionInvoker4< int32_t, int64_t, int64_t, bool >::Invoke(il2cpp_codegen_method_get_slot(targetMethod), il2cpp_codegen_method_get_declaring_type(targetMethod), targetThis, ___sessionState0, ___sessionId1, ___sessionElapsedTime2, ___sessionChanged3); else VirtActionInvoker4< int32_t, int64_t, int64_t, bool >::Invoke(il2cpp_codegen_method_get_slot(targetMethod), targetThis, ___sessionState0, ___sessionId1, ___sessionElapsedTime2, ___sessionChanged3); } } else { typedef void (*FunctionPointerType) (void*, int32_t, int64_t, int64_t, bool, const RuntimeMethod*); ((FunctionPointerType)targetMethodPointer)(targetThis, ___sessionState0, ___sessionId1, ___sessionElapsedTime2, ___sessionChanged3, targetMethod); } } } } // System.IAsyncResult UnityEngine.Analytics.AnalyticsSessionInfo/SessionStateChanged::BeginInvoke(UnityEngine.Analytics.AnalyticsSessionState,System.Int64,System.Int64,System.Boolean,System.AsyncCallback,System.Object) extern ""C"" IL2CPP_METHOD_ATTR RuntimeObject* SessionStateChanged_BeginInvoke_m1132835327 (SessionStateChanged_t3163629820 * __this, int32_t ___sessionState0, int64_t ___sessionId1, int64_t ___sessionElapsedTime2, bool ___sessionChanged3, AsyncCallback_t3962456242 * ___callback4, RuntimeObject * ___object5, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (SessionStateChanged_BeginInvoke_m1132835327_MetadataUsageId); s_Il2CppMethodInitialized = true; } void *__d_args[5] = {0}; __d_args[0] = Box(AnalyticsSessionState_t681173134_il2cpp_TypeInfo_var, &___sessionState0); __d_args[1] = Box(Int64_t3736567304_il2cpp_TypeInfo_var, &___sessionId1); __d_args[2] = Box(Int64_t3736567304_il2cpp_TypeInfo_var, &___sessionElapsedTime2); __d_args[3] = Box(Boolean_t97287965_il2cpp_TypeInfo_var, &___sessionChanged3); return (RuntimeObject*)il2cpp_codegen_delegate_begin_invoke((RuntimeDelegate*)__this, __d_args, (RuntimeDelegate*)___callback4, (RuntimeObject*)___object5); } // System.Void UnityEngine.Analytics.AnalyticsSessionInfo/SessionStateChanged::EndInvoke(System.IAsyncResult) extern ""C"" IL2CPP_METHOD_ATTR void SessionStateChanged_EndInvoke_m3581055289 (SessionStateChanged_t3163629820 * __this, RuntimeObject* ___result0, const RuntimeMethod* method) { il2cpp_codegen_delegate_end_invoke((Il2CppAsyncResult*) ___result0, 0); } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // Conversion methods for marshalling of: UnityEngine.RemoteConfigSettings extern ""C"" void RemoteConfigSettings_t1247263429_marshal_pinvoke(const RemoteConfigSettings_t1247263429& unmarshaled, RemoteConfigSettings_t1247263429_marshaled_pinvoke& marshaled) { marshaled.___m_Ptr_0 = unmarshaled.get_m_Ptr_0(); marshaled.___Updated_1 = il2cpp_codegen_marshal_delegate(reinterpret_cast(unmarshaled.get_Updated_1())); } extern ""C"" void RemoteConfigSettings_t1247263429_marshal_pinvoke_back(const RemoteConfigSettings_t1247263429_marshaled_pinvoke& marshaled, RemoteConfigSettings_t1247263429& unmarshaled) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RemoteConfigSettings_t1247263429_pinvoke_FromNativeMethodDefinition_MetadataUsageId); s_Il2CppMethodInitialized = true; } intptr_t unmarshaled_m_Ptr_temp_0; memset(&unmarshaled_m_Ptr_temp_0, 0, sizeof(unmarshaled_m_Ptr_temp_0)); unmarshaled_m_Ptr_temp_0 = marshaled.___m_Ptr_0; unmarshaled.set_m_Ptr_0(unmarshaled_m_Ptr_temp_0); unmarshaled.set_Updated_1(il2cpp_codegen_marshal_function_ptr_to_delegate(marshaled.___Updated_1, Action_1_t269755560_il2cpp_TypeInfo_var)); } // Conversion method for clean up from marshalling of: UnityEngine.RemoteConfigSettings extern ""C"" void RemoteConfigSettings_t1247263429_marshal_pinvoke_cleanup(RemoteConfigSettings_t1247263429_marshaled_pinvoke& marshaled) { } // Conversion methods for marshalling of: UnityEngine.RemoteConfigSettings extern ""C"" void RemoteConfigSettings_t1247263429_marshal_com(const RemoteConfigSettings_t1247263429& unmarshaled, RemoteConfigSettings_t1247263429_marshaled_com& marshaled) { marshaled.___m_Ptr_0 = unmarshaled.get_m_Ptr_0(); marshaled.___Updated_1 = il2cpp_codegen_marshal_delegate(reinterpret_cast(unmarshaled.get_Updated_1())); } extern ""C"" void RemoteConfigSettings_t1247263429_marshal_com_back(const RemoteConfigSettings_t1247263429_marshaled_com& marshaled, RemoteConfigSettings_t1247263429& unmarshaled) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RemoteConfigSettings_t1247263429_com_FromNativeMethodDefinition_MetadataUsageId); s_Il2CppMethodInitialized = true; } intptr_t unmarshaled_m_Ptr_temp_0; memset(&unmarshaled_m_Ptr_temp_0, 0, sizeof(unmarshaled_m_Ptr_temp_0)); unmarshaled_m_Ptr_temp_0 = marshaled.___m_Ptr_0; unmarshaled.set_m_Ptr_0(unmarshaled_m_Ptr_temp_0); unmarshaled.set_Updated_1(il2cpp_codegen_marshal_function_ptr_to_delegate(marshaled.___Updated_1, Action_1_t269755560_il2cpp_TypeInfo_var)); } // Conversion method for clean up from marshalling of: UnityEngine.RemoteConfigSettings extern ""C"" void RemoteConfigSettings_t1247263429_marshal_com_cleanup(RemoteConfigSettings_t1247263429_marshaled_com& marshaled) { } // System.Void UnityEngine.RemoteConfigSettings::Finalize() extern ""C"" IL2CPP_METHOD_ATTR void RemoteConfigSettings_Finalize_m2805990196 (RemoteConfigSettings_t1247263429 * __this, const RuntimeMethod* method) { Exception_t * __last_unhandled_exception = 0; NO_UNUSED_WARNING (__last_unhandled_exception); Exception_t * __exception_local = 0; NO_UNUSED_WARNING (__exception_local); int32_t __leave_target = -1; NO_UNUSED_WARNING (__leave_target); { } IL_0001: try { // begin try (depth: 1) RemoteConfigSettings_Destroy_m1854335118(__this, /*hidden argument*/NULL); IL2CPP_LEAVE(0x13, FINALLY_000c); } // end try (depth: 1) catch(Il2CppExceptionWrapper& e) { __last_unhandled_exception = (Exception_t *)e.ex; goto FINALLY_000c; } FINALLY_000c: { // begin finally (depth: 1) Object_Finalize_m3076187857(__this, /*hidden argument*/NULL); IL2CPP_END_FINALLY(12) } // end finally (depth: 1) IL2CPP_CLEANUP(12) { IL2CPP_JUMP_TBL(0x13, IL_0013) IL2CPP_RETHROW_IF_UNHANDLED(Exception_t *) } IL_0013: { return; } } // System.Void UnityEngine.RemoteConfigSettings::Destroy() extern ""C"" IL2CPP_METHOD_ATTR void RemoteConfigSettings_Destroy_m1854335118 (RemoteConfigSettings_t1247263429 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RemoteConfigSettings_Destroy_m1854335118_MetadataUsageId); s_Il2CppMethodInitialized = true; } { intptr_t L_0 = __this->get_m_Ptr_0(); bool L_1 = IntPtr_op_Inequality_m3063970704(NULL /*static, unused*/, L_0, (intptr_t)(0), /*hidden argument*/NULL); if (!L_1) { goto IL_002e; } } { intptr_t L_2 = __this->get_m_Ptr_0(); RemoteConfigSettings_Internal_Destroy_m1072151938(NULL /*static, unused*/, L_2, /*hidden argument*/NULL); __this->set_m_Ptr_0((intptr_t)(0)); } IL_002e: { return; } } // System.Void UnityEngine.RemoteConfigSettings::Dispose() extern ""C"" IL2CPP_METHOD_ATTR void RemoteConfigSettings_Dispose_m2083915538 (RemoteConfigSettings_t1247263429 * __this, const RuntimeMethod* method) { { RemoteConfigSettings_Destroy_m1854335118(__this, /*hidden argument*/NULL); GC_SuppressFinalize_m1177400158(NULL /*static, unused*/, __this, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.RemoteConfigSettings::Internal_Destroy(System.IntPtr) extern ""C"" IL2CPP_METHOD_ATTR void RemoteConfigSettings_Internal_Destroy_m1072151938 (RuntimeObject * __this /* static, unused */, intptr_t ___ptr0, const RuntimeMethod* method) { typedef void (*RemoteConfigSettings_Internal_Destroy_m1072151938_ftn) (intptr_t); static RemoteConfigSettings_Internal_Destroy_m1072151938_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (RemoteConfigSettings_Internal_Destroy_m1072151938_ftn)il2cpp_codegen_resolve_icall (""UnityEngine.RemoteConfigSettings::Internal_Destroy(System.IntPtr)""); _il2cpp_icall_func(___ptr0); } // System.Void UnityEngine.RemoteConfigSettings::RemoteConfigSettingsUpdated(UnityEngine.RemoteConfigSettings,System.Boolean) extern ""C"" IL2CPP_METHOD_ATTR void RemoteConfigSettings_RemoteConfigSettingsUpdated_m2409101234 (RuntimeObject * __this /* static, unused */, RemoteConfigSettings_t1247263429 * ___rcs0, bool ___wasLastUpdatedFromServer1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RemoteConfigSettings_RemoteConfigSettingsUpdated_m2409101234_MetadataUsageId); s_Il2CppMethodInitialized = true; } Action_1_t269755560 * V_0 = NULL; { RemoteConfigSettings_t1247263429 * L_0 = ___rcs0; NullCheck(L_0); Action_1_t269755560 * L_1 = L_0->get_Updated_1(); V_0 = L_1; Action_1_t269755560 * L_2 = V_0; if (!L_2) { goto IL_0015; } } { Action_1_t269755560 * L_3 = V_0; bool L_4 = ___wasLastUpdatedFromServer1; NullCheck(L_3); Action_1_Invoke_m1933767679(L_3, L_4, /*hidden argument*/Action_1_Invoke_m1933767679_RuntimeMethod_var); } IL_0015: { return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif // System.Void UnityEngine.RemoteSettings::RemoteSettingsUpdated(System.Boolean) extern ""C"" IL2CPP_METHOD_ATTR void RemoteSettings_RemoteSettingsUpdated_m1182006011 (RuntimeObject * __this /* static, unused */, bool ___wasLastUpdatedFromServer0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RemoteSettings_RemoteSettingsUpdated_m1182006011_MetadataUsageId); s_Il2CppMethodInitialized = true; } UpdatedEventHandler_t1027848393 * V_0 = NULL; { UpdatedEventHandler_t1027848393 * L_0 = ((RemoteSettings_t1718627291_StaticFields*)il2cpp_codegen_static_fields_for(RemoteSettings_t1718627291_il2cpp_TypeInfo_var))->get_Updated_0(); V_0 = L_0; UpdatedEventHandler_t1027848393 * L_1 = V_0; if (!L_1) { goto IL_0013; } } { UpdatedEventHandler_t1027848393 * L_2 = V_0; NullCheck(L_2); UpdatedEventHandler_Invoke_m3026613363(L_2, /*hidden argument*/NULL); } IL_0013: { return; } } // System.Void UnityEngine.RemoteSettings::RemoteSettingsBeforeFetchFromServer() extern ""C"" IL2CPP_METHOD_ATTR void RemoteSettings_RemoteSettingsBeforeFetchFromServer_m4228537265 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RemoteSettings_RemoteSettingsBeforeFetchFromServer_m4228537265_MetadataUsageId); s_Il2CppMethodInitialized = true; } Action_t1264377477 * V_0 = NULL; { Action_t1264377477 * L_0 = ((RemoteSettings_t1718627291_StaticFields*)il2cpp_codegen_static_fields_for(RemoteSettings_t1718627291_il2cpp_TypeInfo_var))->get_BeforeFetchFromServer_1(); V_0 = L_0; Action_t1264377477 * L_1 = V_0; if (!L_1) { goto IL_0013; } } { Action_t1264377477 * L_2 = V_0; NullCheck(L_2); Action_Invoke_m937035532(L_2, /*hidden argument*/NULL); } IL_0013: { return; } } // System.Void UnityEngine.RemoteSettings::RemoteSettingsUpdateCompleted(System.Boolean,System.Boolean,System.Int32) extern ""C"" IL2CPP_METHOD_ATTR void RemoteSettings_RemoteSettingsUpdateCompleted_m2956290507 (RuntimeObject * __this /* static, unused */, bool ___wasLastUpdatedFromServer0, bool ___settingsChanged1, int32_t ___response2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (RemoteSettings_RemoteSettingsUpdateCompleted_m2956290507_MetadataUsageId); s_Il2CppMethodInitialized = true; } Action_3_t3050575418 * V_0 = NULL; { Action_3_t3050575418 * L_0 = ((RemoteSettings_t1718627291_StaticFields*)il2cpp_codegen_static_fields_for(RemoteSettings_t1718627291_il2cpp_TypeInfo_var))->get_Completed_2(); V_0 = L_0; Action_3_t3050575418 * L_1 = V_0; if (!L_1) { goto IL_0016; } } { Action_3_t3050575418 * L_2 = V_0; bool L_3 = ___wasLastUpdatedFromServer0; bool L_4 = ___settingsChanged1; int32_t L_5 = ___response2; NullCheck(L_2); Action_3_Invoke_m1011371804(L_2, L_3, L_4, L_5, /*hidden argument*/Action_3_Invoke_m1011371804_RuntimeMethod_var); } IL_0016: { return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Winvalid-offsetof"" #pragma clang diagnostic ignored ""-Wunused-variable"" #endif extern ""C"" void DelegatePInvokeWrapper_UpdatedEventHandler_t1027848393 (UpdatedEventHandler_t1027848393 * __this, const RuntimeMethod* method) { typedef void (DEFAULT_CALL *PInvokeFunc)(); PInvokeFunc il2cppPInvokeFunc = reinterpret_cast(il2cpp_codegen_get_method_pointer(((RuntimeDelegate*)__this)->method)); // Native function invocation il2cppPInvokeFunc(); } // System.Void UnityEngine.RemoteSettings/UpdatedEventHandler::.ctor(System.Object,System.IntPtr) extern ""C"" IL2CPP_METHOD_ATTR void UpdatedEventHandler__ctor_m3406570235 (UpdatedEventHandler_t1027848393 * __this, RuntimeObject * ___object0, intptr_t ___method1, const RuntimeMethod* method) { __this->set_method_ptr_0(il2cpp_codegen_get_method_pointer((RuntimeMethod*)___method1)); __this->set_method_3(___method1); __this->set_m_target_2(___object0); } // System.Void UnityEngine.RemoteSettings/UpdatedEventHandler::Invoke() extern ""C"" IL2CPP_METHOD_ATTR void UpdatedEventHandler_Invoke_m3026613363 (UpdatedEventHandler_t1027848393 * __this, const RuntimeMethod* method) { if(__this->get_prev_9() != NULL) { UpdatedEventHandler_Invoke_m3026613363((UpdatedEventHandler_t1027848393 *)__this->get_prev_9(), method); } Il2CppMethodPointer targetMethodPointer = __this->get_method_ptr_0(); RuntimeMethod* targetMethod = (RuntimeMethod*)(__this->get_method_3()); RuntimeObject* targetThis = __this->get_m_target_2(); il2cpp_codegen_raise_execution_engine_exception_if_method_is_not_found(targetMethod); bool ___methodIsStatic = MethodIsStatic(targetMethod); if (___methodIsStatic) { if (il2cpp_codegen_method_parameter_count(targetMethod) == 0) { // open { typedef void (*FunctionPointerType) (RuntimeObject *, const RuntimeMethod*); ((FunctionPointerType)targetMethodPointer)(NULL, targetMethod); } } else { // closed { typedef void (*FunctionPointerType) (RuntimeObject *, void*, const RuntimeMethod*); ((FunctionPointerType)targetMethodPointer)(NULL, targetThis, targetMethod); } } } else { { // closed if (il2cpp_codegen_method_is_virtual(targetMethod) && !il2cpp_codegen_object_is_of_sealed_type(targetThis) && il2cpp_codegen_delegate_has_invoker((Il2CppDelegate*)__this)) { if (il2cpp_codegen_method_is_generic_instance(targetMethod)) { if (il2cpp_codegen_method_is_interface_method(targetMethod)) GenericInterfaceActionInvoker0::Invoke(targetMethod, targetThis); else GenericVirtActionInvoker0::Invoke(targetMethod, targetThis); } else { if (il2cpp_codegen_method_is_interface_method(targetMethod)) InterfaceActionInvoker0::Invoke(il2cpp_codegen_method_get_slot(targetMethod), il2cpp_codegen_method_get_declaring_type(targetMethod), targetThis); else VirtActionInvoker0::Invoke(il2cpp_codegen_method_get_slot(targetMethod), targetThis); } } else { typedef void (*FunctionPointerType) (void*, const RuntimeMethod*); ((FunctionPointerType)targetMethodPointer)(targetThis, targetMethod); } } } } // System.IAsyncResult UnityEngine.RemoteSettings/UpdatedEventHandler::BeginInvoke(System.AsyncCallback,System.Object) extern ""C"" IL2CPP_METHOD_ATTR RuntimeObject* UpdatedEventHandler_BeginInvoke_m424999959 (UpdatedEventHandler_t1027848393 * __this, AsyncCallback_t3962456242 * ___callback0, RuntimeObject * ___object1, const RuntimeMethod* method) { void *__d_args[1] = {0}; return (RuntimeObject*)il2cpp_codegen_delegate_begin_invoke((RuntimeDelegate*)__this, __d_args, (RuntimeDelegate*)___callback0, (RuntimeObject*)___object1); } // System.Void UnityEngine.RemoteSettings/UpdatedEventHandler::EndInvoke(System.IAsyncResult) extern ""C"" IL2CPP_METHOD_ATTR void UpdatedEventHandler_EndInvoke_m3714202114 (UpdatedEventHandler_t1027848393 * __this, RuntimeObject* ___result0, const RuntimeMethod* method) { il2cpp_codegen_delegate_end_invoke((Il2CppAsyncResult*) ___result0, 0); } #ifdef __clang__ #pragma clang diagnostic pop #endif ",16172,True,3324.7083324786836,median "[[features.testing]] == Testing Spring Boot provides a number of utilities and annotations to help when testing your application. Test support is provided by two modules: `spring-boot-test` contains core items, and `spring-boot-test-autoconfigure` supports auto-configuration for tests. Most developers use the `spring-boot-starter-test` ""`Starter`"", which imports both Spring Boot test modules as well as JUnit Jupiter, AssertJ, Hamcrest, and a number of other useful libraries. [TIP] ==== If you have tests that use JUnit 4, JUnit 5's vintage engine can be used to run them. To use the vintage engine, add a dependency on `junit-vintage-engine`, as shown in the following example: [source,xml,indent=0,subs=""verbatim""] ---- org.junit.vintage junit-vintage-engine test org.hamcrest hamcrest-core ---- ==== `hamcrest-core` is excluded in favor of `org.hamcrest:hamcrest` that is part of `spring-boot-starter-test`. [[features.testing.test-scope-dependencies]] === Test Scope Dependencies The `spring-boot-starter-test` ""`Starter`"" (in the `test` `scope`) contains the following provided libraries: * https://junit.org/junit5/[JUnit 5]: The de-facto standard for unit testing Java applications. * {spring-framework-docs}/testing.html#integration-testing[Spring Test] & Spring Boot Test: Utilities and integration test support for Spring Boot applications. * https://assertj.github.io/doc/[AssertJ]: A fluent assertion library. * https://github.com/hamcrest/JavaHamcrest[Hamcrest]: A library of matcher objects (also known as constraints or predicates). * https://site.mockito.org/[Mockito]: A Java mocking framework. * https://github.com/skyscreamer/JSONassert[JSONassert]: An assertion library for JSON. * https://github.com/jayway/JsonPath[JsonPath]: XPath for JSON. We generally find these common libraries to be useful when writing tests. If these libraries do not suit your needs, you can add additional test dependencies of your own. [[features.testing.spring-applications]] === Testing Spring Applications One of the major advantages of dependency injection is that it should make your code easier to unit test. You can instantiate objects by using the `new` operator without even involving Spring. You can also use _mock objects_ instead of real dependencies. Often, you need to move beyond unit testing and start integration testing (with a Spring `ApplicationContext`). It is useful to be able to perform integration testing without requiring deployment of your application or needing to connect to other infrastructure. The Spring Framework includes a dedicated test module for such integration testing. You can declare a dependency directly to `org.springframework:spring-test` or use the `spring-boot-starter-test` ""`Starter`"" to pull it in transitively. If you have not used the `spring-test` module before, you should start by reading the {spring-framework-docs}/testing.html#testing[relevant section] of the Spring Framework reference documentation. [[features.testing.spring-boot-applications]] === Testing Spring Boot Applications A Spring Boot application is a Spring `ApplicationContext`, so nothing very special has to be done to test it beyond what you would normally do with a vanilla Spring context. NOTE: External properties, logging, and other features of Spring Boot are installed in the context by default only if you use `SpringApplication` to create it. Spring Boot provides a `@SpringBootTest` annotation, which can be used as an alternative to the standard `spring-test` `@ContextConfiguration` annotation when you need Spring Boot features. The annotation works by <>. In addition to `@SpringBootTest` a number of other annotations are also provided for <> of an application. TIP: If you are using JUnit 4, don't forget to also add `@RunWith(SpringRunner.class)` to your test, otherwise the annotations will be ignored. If you are using JUnit 5, there's no need to add the equivalent `@ExtendWith(SpringExtension.class)` as `@SpringBootTest` and the other `@...Test` annotations are already annotated with it. By default, `@SpringBootTest` will not start a server. You can use the `webEnvironment` attribute of `@SpringBootTest` to further refine how your tests run: * `MOCK`(Default) : Loads a web `ApplicationContext` and provides a mock web environment. Embedded servers are not started when using this annotation. If a web environment is not available on your classpath, this mode transparently falls back to creating a regular non-web `ApplicationContext`. It can be used in conjunction with <> for mock-based testing of your web application. * `RANDOM_PORT`: Loads a `WebServerApplicationContext` and provides a real web environment. Embedded servers are started and listen on a random port. * `DEFINED_PORT`: Loads a `WebServerApplicationContext` and provides a real web environment. Embedded servers are started and listen on a defined port (from your `application.properties`) or on the default port of `8080`. * `NONE`: Loads an `ApplicationContext` by using `SpringApplication` but does not provide _any_ web environment (mock or otherwise). NOTE: If your test is `@Transactional`, it rolls back the transaction at the end of each test method by default. However, as using this arrangement with either `RANDOM_PORT` or `DEFINED_PORT` implicitly provides a real servlet environment, the HTTP client and server run in separate threads and, thus, in separate transactions. Any transaction initiated on the server does not roll back in this case. NOTE: `@SpringBootTest` with `webEnvironment = WebEnvironment.RANDOM_PORT` will also start the management server on a separate random port if your application uses a different port for the management server. [[features.testing.spring-boot-applications.detecting-web-app-type]] ==== Detecting Web Application Type If Spring MVC is available, a regular MVC-based application context is configured. If you have only Spring WebFlux, we'll detect that and configure a WebFlux-based application context instead. If both are present, Spring MVC takes precedence. If you want to test a reactive web application in this scenario, you must set the configprop:spring.main.web-application-type[] property: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/detectingwebapptype/MyWebFluxTests.java[] ---- [[features.testing.spring-boot-applications.detecting-configuration]] ==== Detecting Test Configuration If you are familiar with the Spring Test Framework, you may be used to using `@ContextConfiguration(classes=...)` in order to specify which Spring `@Configuration` to load. Alternatively, you might have often used nested `@Configuration` classes within your test. When testing Spring Boot applications, this is often not required. Spring Boot's `@*Test` annotations search for your primary configuration automatically whenever you do not explicitly define one. The search algorithm works up from the package that contains the test until it finds a class annotated with `@SpringBootApplication` or `@SpringBootConfiguration`. As long as you <> in a sensible way, your main configuration is usually found. [NOTE] ==== If you use a <>, you should avoid adding configuration settings that are specific to a particular area on the <>. The underlying component scan configuration of `@SpringBootApplication` defines exclude filters that are used to make sure slicing works as expected. If you are using an explicit `@ComponentScan` directive on your `@SpringBootApplication`-annotated class, be aware that those filters will be disabled. If you are using slicing, you should define them again. ==== If you want to customize the primary configuration, you can use a nested `@TestConfiguration` class. Unlike a nested `@Configuration` class, which would be used instead of your application's primary configuration, a nested `@TestConfiguration` class is used in addition to your application's primary configuration. NOTE: Spring's test framework caches application contexts between tests. Therefore, as long as your tests share the same configuration (no matter how it is discovered), the potentially time-consuming process of loading the context happens only once. [[features.testing.spring-boot-applications.excluding-configuration]] ==== Excluding Test Configuration If your application uses component scanning (for example, if you use `@SpringBootApplication` or `@ComponentScan`), you may find top-level configuration classes that you created only for specific tests accidentally get picked up everywhere. As we <>, `@TestConfiguration` can be used on an inner class of a test to customize the primary configuration. When placed on a top-level class, `@TestConfiguration` indicates that classes in `src/test/java` should not be picked up by scanning. You can then import that class explicitly where it is required, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/excludingconfiguration/MyTests.java[] ---- NOTE: If you directly use `@ComponentScan` (that is, not through `@SpringBootApplication`) you need to register the `TypeExcludeFilter` with it. See {spring-boot-module-api}/context/TypeExcludeFilter.html[the Javadoc] for details. [[features.testing.spring-boot-applications.using-application-arguments]] ==== Using Application Arguments If your application expects <>, you can have `@SpringBootTest` inject them using the `args` attribute. [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/usingapplicationarguments/MyApplicationArgumentTests.java[] ---- [[features.testing.spring-boot-applications.with-mock-environment]] ==== Testing with a mock environment By default, `@SpringBootTest` does not start the server. If you have web endpoints that you want to test against this mock environment, you can additionally configure {spring-framework-docs}/testing.html#spring-mvc-test-framework[`MockMvc`] as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/withmockenvironment/MyMockMvcTests.java[] ---- TIP: If you want to focus only on the web layer and not start a complete `ApplicationContext`, consider <>. Alternatively, you can configure a {spring-framework-docs}/testing.html#webtestclient-tests[`WebTestClient`] as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/withmockenvironment/MyMockWebTestClientTests.java[] ---- [TIP] ==== Testing within a mocked environment is usually faster than running with a full Servlet container. However, since mocking occurs at the Spring MVC layer, code that relies on lower-level Servlet container behavior cannot be directly tested with MockMvc. For example, Spring Boot's error handling is based on the ""`error page`"" support provided by the Servlet container. This means that, whilst you can test your MVC layer throws and handles exceptions as expected, you cannot directly test that a specific <> is rendered. If you need to test these lower-level concerns, you can start a fully running server as described in the next section. ==== [[features.testing.spring-boot-applications.with-running-server]] ==== Testing with a running server If you need to start a full running server, we recommend that you use random ports. If you use `@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)`, an available port is picked at random each time your test runs. The `@LocalServerPort` annotation can be used to <> into your test. For convenience, tests that need to make REST calls to the started server can additionally `@Autowire` a {spring-framework-docs}/testing.html#webtestclient-tests[`WebTestClient`], which resolves relative links to the running server and comes with a dedicated API for verifying responses, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/withrunningserver/MyRandomPortWebTestClientTests.java[] ---- This setup requires `spring-webflux` on the classpath. If you can't or won't add webflux, Spring Boot also provides a `TestRestTemplate` facility: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/withrunningserver/MyRandomPortTestRestTemplateTests.java[] ---- [[features.testing.spring-boot-applications.customizing-web-test-client]] ==== Customizing WebTestClient To customize the `WebTestClient` bean, configure a `WebTestClientBuilderCustomizer` bean. Any such beans are called with the `WebTestClient.Builder` that is used to create the `WebTestClient`. [[features.testing.spring-boot-applications.jmx]] ==== Using JMX As the test context framework caches context, JMX is disabled by default to prevent identical components to register on the same domain. If such test needs access to an `MBeanServer`, consider marking it dirty as well: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/jmx/MyJmxTests.java[] ---- [[features.testing.spring-boot-applications.metrics]] ==== Using Metrics Regardless of your classpath, meter registries, except the in-memory backed, are not auto-configured when using `@SpringBootTest`. If you need to export metrics to a different backend as part of an integration test, annotate it with `@AutoConfigureMetrics`. [[features.testing.spring-boot-applications.mocking-beans]] ==== Mocking and Spying Beans When running tests, it is sometimes necessary to mock certain components within your application context. For example, you may have a facade over some remote service that is unavailable during development. Mocking can also be useful when you want to simulate failures that might be hard to trigger in a real environment. Spring Boot includes a `@MockBean` annotation that can be used to define a Mockito mock for a bean inside your `ApplicationContext`. You can use the annotation to add new beans or replace a single existing bean definition. The annotation can be used directly on test classes, on fields within your test, or on `@Configuration` classes and fields. When used on a field, the instance of the created mock is also injected. Mock beans are automatically reset after each test method. [NOTE] ==== If your test uses one of Spring Boot's test annotations (such as `@SpringBootTest`), this feature is automatically enabled. To use this feature with a different arrangement, listeners must be explicitly added, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/mockingbeans/listener/MyTests.java[] ---- ==== The following example replaces an existing `RemoteService` bean with a mock implementation: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/mockingbeans/bean/MyTests.java[] ---- NOTE: `@MockBean` cannot be used to mock the behavior of a bean that's exercised during application context refresh. By the time the test is executed, the application context refresh has completed and it is too late to configure the mocked behavior. We recommend using a `@Bean` method to create and configure the mock in this situation. Additionally, you can use `@SpyBean` to wrap any existing bean with a Mockito `spy`. See the {spring-boot-test-module-api}/mock/mockito/SpyBean.html[Javadoc] for full details. NOTE: CGLib proxies, such as those created for scoped beans, declare the proxied methods as `final`. This stops Mockito from functioning correctly as it cannot mock or spy on `final` methods in its default configuration. If you want to mock or spy on such a bean, configure Mockito to use its inline mock maker by adding `org.mockito:mockito-inline` to your application's test dependencies. This allows Mockito to mock and spy on `final` methods. NOTE: While Spring's test framework caches application contexts between tests and reuses a context for tests sharing the same configuration, the use of `@MockBean` or `@SpyBean` influences the cache key, which will most likely increase the number of contexts. TIP: If you are using `@SpyBean` to spy on a bean with `@Cacheable` methods that refer to parameters by name, your application must be compiled with `-parameters`. This ensures that the parameter names are available to the caching infrastructure once the bean has been spied upon. TIP: When you are using `@SpyBean` to spy on a bean that is proxied by Spring, you may need to remove Spring's proxy in some situations, for example when setting expectations using `given` or `when`. Use `AopTestUtils.getTargetObject(yourProxiedSpy)` to do so. [[features.testing.spring-boot-applications.autoconfigured-tests]] ==== Auto-configured Tests Spring Boot's auto-configuration system works well for applications but can sometimes be a little too much for tests. It often helps to load only the parts of the configuration that are required to test a ""`slice`"" of your application. For example, you might want to test that Spring MVC controllers are mapping URLs correctly, and you do not want to involve database calls in those tests, or you might want to test JPA entities, and you are not interested in the web layer when those tests run. The `spring-boot-test-autoconfigure` module includes a number of annotations that can be used to automatically configure such ""`slices`"". Each of them works in a similar way, providing a `@...Test` annotation that loads the `ApplicationContext` and one or more `@AutoConfigure...` annotations that can be used to customize auto-configuration settings. NOTE: Each slice restricts component scan to appropriate components and loads a very restricted set of auto-configuration classes. If you need to exclude one of them, most `@...Test` annotations provide an `excludeAutoConfiguration` attribute. Alternatively, you can use `@ImportAutoConfiguration#exclude`. NOTE: Including multiple ""`slices`"" by using several `@...Test` annotations in one test is not supported. If you need multiple ""`slices`"", pick one of the `@...Test` annotations and include the `@AutoConfigure...` annotations of the other ""`slices`"" by hand. TIP: It is also possible to use the `@AutoConfigure...` annotations with the standard `@SpringBootTest` annotation. You can use this combination if you are not interested in ""`slicing`"" your application but you want some of the auto-configured test beans. [[features.testing.spring-boot-applications.json-tests]] ==== Auto-configured JSON Tests To test that object JSON serialization and deserialization is working as expected, you can use the `@JsonTest` annotation. `@JsonTest` auto-configures the available supported JSON mapper, which can be one of the following libraries: * Jackson `ObjectMapper`, any `@JsonComponent` beans and any Jackson ``Module``s * `Gson` * `Jsonb` TIP: A list of the auto-configurations that are enabled by `@JsonTest` can be <>. If you need to configure elements of the auto-configuration, you can use the `@AutoConfigureJsonTesters` annotation. Spring Boot includes AssertJ-based helpers that work with the JSONAssert and JsonPath libraries to check that JSON appears as expected. The `JacksonTester`, `GsonTester`, `JsonbTester`, and `BasicJsonTester` classes can be used for Jackson, Gson, Jsonb, and Strings respectively. Any helper fields on the test class can be `@Autowired` when using `@JsonTest`. The following example shows a test class for Jackson: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/jsontests/MyJsonTests.java[] ---- NOTE: JSON helper classes can also be used directly in standard unit tests. To do so, call the `initFields` method of the helper in your `@Before` method if you do not use `@JsonTest`. If you're using Spring Boot's AssertJ-based helpers to assert on a number value at a given JSON path, you might not be able to use `isEqualTo` depending on the type. Instead, you can use AssertJ's `satisfies` to assert that the value matches the given condition. For instance, the following example asserts that the actual number is a float value close to `0.15` within an offset of `0.01`. [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/jsontests/MyJsonAssertJTests.java[tag=*] ---- [[features.testing.spring-boot-applications.spring-mvc-tests]] ==== Auto-configured Spring MVC Tests To test whether Spring MVC controllers are working as expected, use the `@WebMvcTest` annotation. `@WebMvcTest` auto-configures the Spring MVC infrastructure and limits scanned beans to `@Controller`, `@ControllerAdvice`, `@JsonComponent`, `Converter`, `GenericConverter`, `Filter`, `HandlerInterceptor`, `WebMvcConfigurer`, and `HandlerMethodArgumentResolver`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@WebMvcTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configuration settings that are enabled by `@WebMvcTest` can be <>. TIP: If you need to register extra components, such as the Jackson `Module`, you can import additional configuration classes by using `@Import` on your test. Often, `@WebMvcTest` is limited to a single controller and is used in combination with `@MockBean` to provide mock implementations for required collaborators. `@WebMvcTest` also auto-configures `MockMvc`. Mock MVC offers a powerful way to quickly test MVC controllers without needing to start a full HTTP server. TIP: You can also auto-configure `MockMvc` in a non-`@WebMvcTest` (such as `@SpringBootTest`) by annotating it with `@AutoConfigureMockMvc`. The following example uses `MockMvc`: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/springmvctests/MyControllerTests.java[] ---- TIP: If you need to configure elements of the auto-configuration (for example, when servlet filters should be applied) you can use attributes in the `@AutoConfigureMockMvc` annotation. If you use HtmlUnit or Selenium, auto-configuration also provides an HtmlUnit `WebClient` bean and/or a Selenium `WebDriver` bean. The following example uses HtmlUnit: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/springmvctests/MyHtmlUnitTests.java[] ---- NOTE: By default, Spring Boot puts `WebDriver` beans in a special ""`scope`"" to ensure that the driver exits after each test and that a new instance is injected. If you do not want this behavior, you can add `@Scope(""singleton"")` to your `WebDriver` `@Bean` definition. WARNING: The `webDriver` scope created by Spring Boot will replace any user defined scope of the same name. If you define your own `webDriver` scope you may find it stops working when you use `@WebMvcTest`. If you have Spring Security on the classpath, `@WebMvcTest` will also scan `WebSecurityConfigurer` beans. Instead of disabling security completely for such tests, you can use Spring Security's test support. More details on how to use Spring Security's `MockMvc` support can be found in this _<>_ how-to section. TIP: Sometimes writing Spring MVC tests is not enough; Spring Boot can help you run <>. [[features.testing.spring-boot-applications.spring-webflux-tests]] ==== Auto-configured Spring WebFlux Tests To test that {spring-framework-docs}/web-reactive.html[Spring WebFlux] controllers are working as expected, you can use the `@WebFluxTest` annotation. `@WebFluxTest` auto-configures the Spring WebFlux infrastructure and limits scanned beans to `@Controller`, `@ControllerAdvice`, `@JsonComponent`, `Converter`, `GenericConverter`, `WebFilter`, and `WebFluxConfigurer`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@WebFluxTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configurations that are enabled by `@WebFluxTest` can be <>. TIP: If you need to register extra components, such as Jackson `Module`, you can import additional configuration classes using `@Import` on your test. Often, `@WebFluxTest` is limited to a single controller and used in combination with the `@MockBean` annotation to provide mock implementations for required collaborators. `@WebFluxTest` also auto-configures {spring-framework-docs}/testing.html#webtestclient[`WebTestClient`], which offers a powerful way to quickly test WebFlux controllers without needing to start a full HTTP server. TIP: You can also auto-configure `WebTestClient` in a non-`@WebFluxTest` (such as `@SpringBootTest`) by annotating it with `@AutoConfigureWebTestClient`. The following example shows a class that uses both `@WebFluxTest` and a `WebTestClient`: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/springwebfluxtests/MyControllerTests.java[] ---- TIP: This setup is only supported by WebFlux applications as using `WebTestClient` in a mocked web application only works with WebFlux at the moment. NOTE: `@WebFluxTest` cannot detect routes registered via the functional web framework. For testing `RouterFunction` beans in the context, consider importing your `RouterFunction` yourself via `@Import` or using `@SpringBootTest`. NOTE: `@WebFluxTest` cannot detect custom security configuration registered via a `@Bean` of type `SecurityWebFilterChain`. To include that in your test, you will need to import the configuration that registers the bean via `@Import` or use `@SpringBootTest`. TIP: Sometimes writing Spring WebFlux tests is not enough; Spring Boot can help you run <>. [[features.testing.spring-boot-applications.autoconfigured-spring-data-cassandra]] ==== Auto-configured Data Cassandra Tests You can use `@DataCassandraTest` to test Cassandra applications. By default, it configures a `CassandraTemplate`, scans for `@Table` classes, and configures Spring Data Cassandra repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataCassandraTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. (For more about using Cassandra with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataCassandraTest` can be <>. The following example shows a typical setup for using Cassandra tests in Spring Boot: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatacassandra/MyDataCassandraTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-data-jpa]] ==== Auto-configured Data JPA Tests You can use the `@DataJpaTest` annotation to test JPA applications. By default, it scans for `@Entity` classes and configures Spring Data JPA repositories. If an embedded database is available on the classpath, it configures one as well. SQL queries are logged by default by setting the `spring.jpa.show-sql` property to `true`. This can be disabled using the `showSql()` attribute of the annotation. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataJpaTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configuration settings that are enabled by `@DataJpaTest` can be <>. By default, data JPA tests are transactional and roll back at the end of each test. See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole class as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatajpa/MyNonTransactionalTests.java[] ---- Data JPA tests may also inject a {spring-boot-test-autoconfigure-module-code}/orm/jpa/TestEntityManager.java[`TestEntityManager`] bean, which provides an alternative to the standard JPA `EntityManager` that is specifically designed for tests. If you want to use `TestEntityManager` outside of `@DataJpaTest` instances, you can also use the `@AutoConfigureTestEntityManager` annotation. A `JdbcTemplate` is also available if you need that. The following example shows the `@DataJpaTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatajpa/withoutdb/MyRepositoryTests.java[] ---- In-memory embedded databases generally work well for tests, since they are fast and do not require any installation. If, however, you prefer to run tests against a real database you can use the `@AutoConfigureTestDatabase` annotation, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatajpa/withdb/MyRepositoryTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-jdbc]] ==== Auto-configured JDBC Tests `@JdbcTest` is similar to `@DataJpaTest` but is for tests that only require a `DataSource` and do not use Spring Data JDBC. By default, it configures an in-memory embedded database and a `JdbcTemplate`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@JdbcTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configurations that are enabled by `@JdbcTest` can be <>. By default, JDBC tests are transactional and roll back at the end of each test. See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole class, as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredjdbc/MyTransactionalTests.java[] ---- If you prefer your test to run against a real database, you can use the `@AutoConfigureTestDatabase` annotation in the same way as for `DataJpaTest`. (See ""<>"".) [[features.testing.spring-boot-applications.autoconfigured-spring-data-jdbc]] ==== Auto-configured Data JDBC Tests `@DataJdbcTest` is similar to `@JdbcTest` but is for tests that use Spring Data JDBC repositories. By default, it configures an in-memory embedded database, a `JdbcTemplate`, and Spring Data JDBC repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataJdbcTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configurations that are enabled by `@DataJdbcTest` can be <>. By default, Data JDBC tests are transactional and roll back at the end of each test. See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole test class as <>. If you prefer your test to run against a real database, you can use the `@AutoConfigureTestDatabase` annotation in the same way as for `DataJpaTest`. (See ""<>"".) [[features.testing.spring-boot-applications.autoconfigured-jooq]] ==== Auto-configured jOOQ Tests You can use `@JooqTest` in a similar fashion as `@JdbcTest` but for jOOQ-related tests. As jOOQ relies heavily on a Java-based schema that corresponds with the database schema, the existing `DataSource` is used. If you want to replace it with an in-memory database, you can use `@AutoConfigureTestDatabase` to override those settings. (For more about using jOOQ with Spring Boot, see ""<>"", earlier in this chapter.) Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@JooqTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configurations that are enabled by `@JooqTest` can be <>. `@JooqTest` configures a `DSLContext`. The following example shows the `@JooqTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredjooq/MyJooqTests.java[] ---- JOOQ tests are transactional and roll back at the end of each test by default. If that is not what you want, you can disable transaction management for a test or for the whole test class as <>. [[features.testing.spring-boot-applications.autoconfigured-spring-data-mongodb]] ==== Auto-configured Data MongoDB Tests You can use `@DataMongoTest` to test MongoDB applications. By default, it configures an in-memory embedded MongoDB (if available), configures a `MongoTemplate`, scans for `@Document` classes, and configures Spring Data MongoDB repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataMongoTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. (For more about using MongoDB with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataMongoTest` can be <>. The following class shows the `@DataMongoTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatamongodb/withoutdb/MyDataMongoDbTests.java[] ---- In-memory embedded MongoDB generally works well for tests, since it is fast and does not require any developer installation. If, however, you prefer to run tests against a real MongoDB server, you should exclude the embedded MongoDB auto-configuration, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdatamongodb/withdb/MyDataMongoDbTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-data-neo4j]] ==== Auto-configured Data Neo4j Tests You can use `@DataNeo4jTest` to test Neo4j applications. By default, it scans for `@Node` classes, and configures Spring Data Neo4j repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataNeo4jTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. (For more about using Neo4J with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataNeo4jTest` can be <>. The following example shows a typical setup for using Neo4J tests in Spring Boot: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataneo4j/propagation/MyDataNeo4jTests.java[] ---- By default, Data Neo4j tests are transactional and roll back at the end of each test. See the {spring-framework-docs}/testing.html#testcontext-tx-enabling-transactions[relevant section] in the Spring Framework Reference Documentation for more details. If that is not what you want, you can disable transaction management for a test or for the whole class, as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataneo4j/nopropagation/MyDataNeo4jTests.java[] ---- NOTE: Transactional tests are not supported with reactive access. If you are using this style, you must configure `@DataNeo4jTest` tests as described above. [[features.testing.spring-boot-applications.autoconfigured-spring-data-redis]] ==== Auto-configured Data Redis Tests You can use `@DataRedisTest` to test Redis applications. By default, it scans for `@RedisHash` classes and configures Spring Data Redis repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataRedisTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. (For more about using Redis with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataRedisTest` can be <>. The following example shows the `@DataRedisTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataredis/MyDataRedisTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-data-ldap]] ==== Auto-configured Data LDAP Tests You can use `@DataLdapTest` to test LDAP applications. By default, it configures an in-memory embedded LDAP (if available), configures an `LdapTemplate`, scans for `@Entry` classes, and configures Spring Data LDAP repositories. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@DataLdapTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. (For more about using LDAP with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@DataLdapTest` can be <>. The following example shows the `@DataLdapTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataldap/inmemory/MyDataLdapTests.java[] ---- In-memory embedded LDAP generally works well for tests, since it is fast and does not require any developer installation. If, however, you prefer to run tests against a real LDAP server, you should exclude the embedded LDAP auto-configuration, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringdataldap/server/MyDataLdapTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-rest-client]] ==== Auto-configured REST Clients You can use the `@RestClientTest` annotation to test REST clients. By default, it auto-configures Jackson, GSON, and Jsonb support, configures a `RestTemplateBuilder`, and adds support for `MockRestServiceServer`. Regular `@Component` and `@ConfigurationProperties` beans are not scanned when the `@RestClientTest` annotation is used. `@EnableConfigurationProperties` can be used to include `@ConfigurationProperties` beans. TIP: A list of the auto-configuration settings that are enabled by `@RestClientTest` can be <>. The specific beans that you want to test should be specified by using the `value` or `components` attribute of `@RestClientTest`, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredrestclient/MyRestClientTests.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-restdocs]] ==== Auto-configured Spring REST Docs Tests You can use the `@AutoConfigureRestDocs` annotation to use {spring-restdocs}[Spring REST Docs] in your tests with Mock MVC, REST Assured, or WebTestClient. It removes the need for the JUnit extension in Spring REST Docs. `@AutoConfigureRestDocs` can be used to override the default output directory (`target/generated-snippets` if you are using Maven or `build/generated-snippets` if you are using Gradle). It can also be used to configure the host, scheme, and port that appears in any documented URIs. [[features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-mock-mvc]] ===== Auto-configured Spring REST Docs Tests with Mock MVC `@AutoConfigureRestDocs` customizes the `MockMvc` bean to use Spring REST Docs when testing Servlet-based web applications. You can inject it by using `@Autowired` and use it in your tests as you normally would when using Mock MVC and Spring REST Docs, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withmockmvc/MyUserDocumentationTests.java[] ---- If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, you can use a `RestDocsMockMvcConfigurationCustomizer` bean, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withmockmvc/MyRestDocsConfiguration.java[] ---- If you want to make use of Spring REST Docs support for a parameterized output directory, you can create a `RestDocumentationResultHandler` bean. The auto-configuration calls `alwaysDo` with this result handler, thereby causing each `MockMvc` call to automatically generate the default snippets. The following example shows a `RestDocumentationResultHandler` being defined: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withmockmvc/MyResultHandlerConfiguration.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-web-test-client]] ===== Auto-configured Spring REST Docs Tests with WebTestClient `@AutoConfigureRestDocs` can also be used with `WebTestClient` when testing reactive web applications. You can inject it by using `@Autowired` and use it in your tests as you normally would when using `@WebFluxTest` and Spring REST Docs, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withwebtestclient/MyUsersDocumentationTests.java[] ---- If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, you can use a `RestDocsWebTestClientConfigurationCustomizer` bean, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withwebtestclient/MyRestDocsConfiguration.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-spring-restdocs.with-rest-assured]] ===== Auto-configured Spring REST Docs Tests with REST Assured `@AutoConfigureRestDocs` makes a `RequestSpecification` bean, preconfigured to use Spring REST Docs, available to your tests. You can inject it by using `@Autowired` and use it in your tests as you normally would when using REST Assured and Spring REST Docs, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withrestassured/MyUserDocumentationTests.java[] ---- If you require more control over Spring REST Docs configuration than offered by the attributes of `@AutoConfigureRestDocs`, a `RestDocsRestAssuredConfigurationCustomizer` bean can be used, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredspringrestdocs/withrestassured/MyRestDocsConfiguration.java[] ---- [[features.testing.spring-boot-applications.autoconfigured-webservices]] ==== Auto-configured Spring Web Services Tests You can use `@WebServiceClientTest` to test applications that use call web services using the Spring Web Services project. By default, it configures a mock `WebServiceServer` bean and automatically customizes your `WebServiceTemplateBuilder`. (For more about using Web Services with Spring Boot, see ""<>"", earlier in this chapter.) TIP: A list of the auto-configuration settings that are enabled by `@WebServiceClientTest` can be <>. The following example shows the `@WebServiceClientTest` annotation in use: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/autoconfiguredwebservices/MyWebServiceClientTests.java[] ---- [[features.testing.spring-boot-applications.additional-autoconfiguration-and-slicing]] ==== Additional Auto-configuration and Slicing Each slice provides one or more `@AutoConfigure...` annotations that namely defines the auto-configurations that should be included as part of a slice. Additional auto-configurations can be added on a test-by-test basis by creating a custom `@AutoConfigure...` annotation or by adding `@ImportAutoConfiguration` to the test as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/additionalautoconfigurationandslicing/MyJdbcTests.java[] ---- NOTE: Make sure to not use the regular `@Import` annotation to import auto-configurations as they are handled in a specific way by Spring Boot. Alternatively, additional auto-configurations can be added for any use of a slice annotation by registering them in `META-INF/spring.factories` as shown in the following example: [indent=0] ---- org.springframework.boot.test.autoconfigure.jdbc.JdbcTest=com.example.IntegrationAutoConfiguration ---- TIP: A slice or `@AutoConfigure...` annotation can be customized this way as long as it is meta-annotated with `@ImportAutoConfiguration`. [[features.testing.spring-boot-applications.user-configuration-and-slicing]] ==== User Configuration and Slicing If you <> in a sensible way, your `@SpringBootApplication` class is <> as the configuration of your tests. It then becomes important not to litter the application's main class with configuration settings that are specific to a particular area of its functionality. Assume that you are using Spring Batch and you rely on the auto-configuration for it. You could define your `@SpringBootApplication` as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/MyApplication.java[] ---- Because this class is the source configuration for the test, any slice test actually tries to start Spring Batch, which is definitely not what you want to do. A recommended approach is to move that area-specific configuration to a separate `@Configuration` class at the same level as your application, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/MyBatchConfiguration.java[] ---- NOTE: Depending on the complexity of your application, you may either have a single `@Configuration` class for your customizations or one class per domain area. The latter approach lets you enable it in one of your tests, if necessary, with the `@Import` annotation. Test slices exclude `@Configuration` classes from scanning. For example, for a `@WebMvcTest`, the following configuration will not include the given `WebMvcConfigurer` bean in the application context loaded by the test slice: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/MyWebConfiguration.java[] ---- The configuration below will, however, cause the custom `WebMvcConfigurer` to be loaded by the test slice. [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/MyWebMvcConfigurer.java[] ---- Another source of confusion is classpath scanning. Assume that, while you structured your code in a sensible way, you need to scan an additional package. Your application may resemble the following code: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/springbootapplications/userconfigurationandslicing/scan/MyApplication.java[] ---- Doing so effectively overrides the default component scan directive with the side effect of scanning those two packages regardless of the slice that you chose. For instance, a `@DataJpaTest` seems to suddenly scan components and user configurations of your application. Again, moving the custom directive to a separate class is a good way to fix this issue. TIP: If this is not an option for you, you can create a `@SpringBootConfiguration` somewhere in the hierarchy of your test so that it is used instead. Alternatively, you can specify a source for your test, which disables the behavior of finding a default one. [[features.testing.spring-boot-applications.spock]] ==== Using Spock to Test Spring Boot Applications Spock 2.x can be used to test a Spring Boot application. To do so, add a dependency on Spock's `spock-spring` module to your application's build. `spock-spring` integrates Spring's test framework into Spock. See https://spockframework.org/spock/docs/2.0/modules.html#_spring_module[the documentation for Spock's Spring module] for further details. [[features.testing.utilities]] === Test Utilities A few test utility classes that are generally useful when testing your application are packaged as part of `spring-boot`. [[features.testing.utilities.config-data-application-context-initializer]] ==== ConfigDataApplicationContextInitializer `ConfigDataApplicationContextInitializer` is an `ApplicationContextInitializer` that you can apply to your tests to load Spring Boot `application.properties` files. You can use it when you do not need the full set of features provided by `@SpringBootTest`, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/utilities/configdataapplicationcontextinitializer/MyConfigFileTests.java[] ---- NOTE: Using `ConfigDataApplicationContextInitializer` alone does not provide support for `@Value(""${...}"")` injection. Its only job is to ensure that `application.properties` files are loaded into Spring's `Environment`. For `@Value` support, you need to either additionally configure a `PropertySourcesPlaceholderConfigurer` or use `@SpringBootTest`, which auto-configures one for you. [[features.testing.utilities.test-property-values]] ==== TestPropertyValues `TestPropertyValues` lets you quickly add properties to a `ConfigurableEnvironment` or `ConfigurableApplicationContext`. You can call it with `key=value` strings, as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/utilities/testpropertyvalues/MyEnvironmentTests.java[] ---- [[features.testing.utilities.output-capture]] ==== OutputCapture `OutputCapture` is a JUnit `Extension` that you can use to capture `System.out` and `System.err` output. To use add `@ExtendWith(OutputCaptureExtension.class)` and inject `CapturedOutput` as an argument to your test class constructor or test method as follows: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/utilities/outputcapture/MyOutputCaptureTests.java[] ---- [[features.testing.utilities.test-rest-template]] ==== TestRestTemplate `TestRestTemplate` is a convenience alternative to Spring's `RestTemplate` that is useful in integration tests. You can get a vanilla template or one that sends Basic HTTP authentication (with a username and password). In either case, the template is fault tolerant. This means that it behaves in a test-friendly way by not throwing exceptions on 4xx and 5xx errors. Instead, such errors can be detected via the returned `ResponseEntity` and its status code. TIP: Spring Framework 5.0 provides a new `WebTestClient` that works for <> and both <>. It provides a fluent API for assertions, unlike `TestRestTemplate`. It is recommended, but not mandatory, to use the Apache HTTP Client (version 4.3.2 or better). If you have that on your classpath, the `TestRestTemplate` responds by configuring the client appropriately. If you do use Apache's HTTP client, some additional test-friendly features are enabled: * Redirects are not followed (so you can assert the response location). * Cookies are ignored (so the template is stateless). `TestRestTemplate` can be instantiated directly in your integration tests, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/utilities/testresttemplate/MyTests.java[] ---- Alternatively, if you use the `@SpringBootTest` annotation with `WebEnvironment.RANDOM_PORT` or `WebEnvironment.DEFINED_PORT`, you can inject a fully configured `TestRestTemplate` and start using it. If necessary, additional customizations can be applied through the `RestTemplateBuilder` bean. Any URLs that do not specify a host and port automatically connect to the embedded server, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/testing/utilities/testresttemplate/MySpringBootTests.java[] ---- ",12345,True,2619.4643198948056,median "// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include ""stdafx.h"" #include ""test_utils.h"" #include ""test_websocket_client.h"" #include ""connection_impl.h"" #include ""signalrclient/trace_level.h"" #include ""memory_log_writer.h"" #include ""signalr_default_scheduler.h"" #include ""signalrclient/signalr_exception.h"" #include ""signalrclient/web_exception.h"" #include ""test_http_client.h"" using namespace signalr; static std::shared_ptr create_connection(std::shared_ptr websocket_client = create_test_websocket_client(), std::shared_ptr log_writer = std::make_shared(), trace_level trace_level = trace_level::verbose) { return connection_impl::create(create_uri(), trace_level, log_writer, create_test_http_client(), [websocket_client](const signalr_client_config& config) { websocket_client->set_config(config); return websocket_client; }); } TEST(connection_impl_connection_state, initial_connection_state_is_disconnected) { auto connection = create_connection(); ASSERT_EQ(connection_state::disconnected, connection->get_connection_state()); } TEST(connection_impl_start, cannot_start_non_disconnected_exception) { auto connection = create_connection(); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); try { connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_TRUE(false); // exception not thrown } catch (const signalr_exception & e) { ASSERT_STREQ(""cannot start a connection that is not in the disconnected state"", e.what()); } } TEST(connection_impl_start, connection_state_is_connecting_when_connection_is_being_started) { std::shared_ptr writer(std::make_shared()); auto state_mre = manual_reset_event(); auto websocket_client = create_test_websocket_client( /* send function */ [](const std::string&, std::function callback) { callback(std::make_exception_ptr(std::runtime_error(""should not be invoked""))); }, /* connect function */[&state_mre](const std::string&, std::function callback) { state_mre.get(); callback(std::make_exception_ptr(std::runtime_error(""connecting failed""))); }); auto connection = create_connection(websocket_client, writer, trace_level::error); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); ASSERT_EQ(connection->get_connection_state(), connection_state::connecting); state_mre.set(); try { mre.get(); ASSERT_TRUE(false); } catch (const std::runtime_error & ex) { ASSERT_STREQ(""connecting failed"", ex.what()); } } TEST(connection_impl_start, connection_state_is_connected_when_connection_established_succesfully) { auto connection = create_connection(); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_EQ(connection->get_connection_state(), connection_state::connected); } TEST(connection_impl_start, connection_state_is_disconnected_when_connection_cannot_be_established) { auto http_client = std::shared_ptr(new test_http_client([](const std::string&, http_request) { return http_response{ 404, """" }; })); auto connection = connection_impl::create(create_uri(), trace_level::none, std::make_shared(), [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, nullptr); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); } catch (...) {} ASSERT_EQ(connection->get_connection_state(), connection_state::disconnected); } TEST(connection_impl_start, throws_for_invalid_uri) { std::shared_ptr writer(std::make_shared()); auto websocket_client = create_test_websocket_client(); auto connection = connection_impl::create("":1\\t ä bad_uri&a=b"", trace_level::error, writer, create_test_http_client(), [websocket_client](const signalr_client_config&) { return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); } catch (const std::exception&) { // We shouldn't check the exact exception as it would be specific to the http library being used } ASSERT_EQ(connection->get_connection_state(), connection_state::disconnected); } TEST(connection_impl_start, start_sets_id_query_string) { std::shared_ptr writer(std::make_shared()); std::string query_string; auto websocket_client = create_test_websocket_client( /* send function */ [](const std::string&, std::function callback) { callback(std::make_exception_ptr(std::runtime_error(""should not be invoked""))); }, /* connect function */[&query_string](const std::string& url, std::function callback) { query_string = url.substr(url.find('?') + 1); callback(std::make_exception_ptr(std::runtime_error(""connecting failed""))); }); auto connection = connection_impl::create(create_uri(""""), trace_level::error, writer, create_test_http_client(), [websocket_client](const signalr_client_config& config) { websocket_client->set_config(config); return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); } catch (const std::runtime_error & ex) { ASSERT_STREQ(""connecting failed"", ex.what()); } ASSERT_EQ(""id=f7707523-307d-4cba-9abf-3eef701241e8"", query_string); } TEST(connection_impl_start, start_appends_id_query_string) { std::shared_ptr writer(std::make_shared()); std::string query_string; auto websocket_client = create_test_websocket_client( /* send function */ [](const std::string&, std::function callback) { callback(std::make_exception_ptr(std::runtime_error(""should not be invoked""))); }, /* connect function */[&query_string](const std::string& url, std::function callback) { query_string = url.substr(url.find('?') + 1); callback(std::make_exception_ptr(std::runtime_error(""connecting failed""))); }); auto connection = connection_impl::create(create_uri(""a=b&c=d""), trace_level::error, writer, create_test_http_client(), [websocket_client](const signalr_client_config& config) { websocket_client->set_config(config); return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); } catch (const std::runtime_error & ex) { ASSERT_STREQ(""connecting failed"", ex.what()); } ASSERT_EQ(""a=b&c=d&id=f7707523-307d-4cba-9abf-3eef701241e8"", query_string); } TEST(connection_impl_start, start_logs_exceptions) { std::shared_ptr writer(std::make_shared()); auto http_client = std::shared_ptr(new test_http_client([](const std::string&, http_request) { return http_response{ 404, """" }; })); auto connection = connection_impl::create(create_uri(), trace_level::error, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, nullptr); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); } catch (...) {} auto log_entries = std::dynamic_pointer_cast(writer)->get_log_entries(); ASSERT_FALSE(log_entries.empty()); ASSERT_TRUE(has_log_entry(""[error ] connection could not be started due to: negotiate failed with status code 404\\n"", log_entries)) << dump_vector(log_entries); } TEST(connection_impl_start, start_propagates_exceptions_from_negotiate) { auto http_client = std::shared_ptr(new test_http_client([](const std::string&, http_request) -> http_response { throw custom_exception(); })); auto websocket_client = std::make_shared(); auto connection = connection_impl::create(create_uri(), trace_level::none, std::make_shared(), [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config&) { return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); // exception not thrown } catch (const custom_exception& e) { ASSERT_STREQ(""custom exception"", e.what()); } } TEST(connection_impl_start, start_fails_if_transport_connect_throws) { std::shared_ptr writer(std::make_shared()); auto websocket_client = create_test_websocket_client( /* send function */ [](const std::string&, std::function callback) { callback(std::make_exception_ptr(std::runtime_error(""should not be invoked""))); }, /* connect function */[](const std::string&, std::function callback) { callback(std::make_exception_ptr(std::runtime_error(""connecting failed""))); }); auto connection = create_connection(websocket_client, writer, trace_level::error); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); // exception not thrown } catch (const std::exception & e) { ASSERT_STREQ(""connecting failed"", e.what()); } auto log_entries = std::dynamic_pointer_cast(writer)->get_log_entries(); ASSERT_TRUE(log_entries.size() > 1) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[error ] transport could not connect due to: connecting failed\\n"", log_entries)) << dump_vector(log_entries); } TEST(connection_impl_send, send_fails_if_transport_fails_when_receiving_messages) { std::shared_ptr writer(std::make_shared()); auto websocket_client = create_test_websocket_client( /* send function */ [](const std::string&, std::function callback) { callback(std::make_exception_ptr(std::runtime_error(""send error""))); }); auto connection = create_connection(websocket_client, writer, trace_level::error); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); connection->send(""message"", transfer_format::text, [&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); // exception not thrown } catch (const std::exception & e) { ASSERT_STREQ(""send error"", e.what()); } auto log_entries = std::dynamic_pointer_cast(writer)->get_log_entries(); ASSERT_TRUE(has_log_entry(""[error ] error sending data: send error\\n"", log_entries)) << dump_vector(log_entries); } TEST(connection_impl_start, start_fails_if_negotiate_request_fails) { std::shared_ptr writer(std::make_shared()); auto http_client = std::shared_ptr(new test_http_client([](const std::string&, http_request) { return http_response{ 400, """" }; })); auto websocket_client = std::make_shared(); auto connection = connection_impl::create(create_uri(), trace_level::info, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config&) { return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); // exception not thrown } catch (const std::exception & e) { ASSERT_STREQ(""negotiate failed with status code 400"", e.what()); } } TEST(connection_impl_start, start_fails_if_negotiate_response_has_error) { std::shared_ptr writer(std::make_shared()); auto http_client = std::shared_ptr(new test_http_client([](const std::string& url, http_request) { auto response_body = url.find(""/negotiate"") != std::string::npos ? ""{ \\""error\\"": \\""bad negotiate\\"" }"" : """"; return http_response{ 200, response_body }; })); auto connect_mre = manual_reset_event(); auto websocket_client = std::make_shared(); websocket_client->set_connect_function([&connect_mre](const std::string&, std::function callback) { connect_mre.get(); callback(nullptr); }); auto connection = connection_impl::create(create_uri(), trace_level::info, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config&) { return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); // exception not thrown } catch (const signalr_exception & e) { ASSERT_STREQ(""bad negotiate"", e.what()); } connect_mre.set(); } TEST(connection_impl_start, start_fails_if_negotiate_response_does_not_have_websockets) { std::shared_ptr writer(std::make_shared()); auto http_client = std::shared_ptr(new test_http_client([](const std::string& url, http_request) { auto response_body = url.find(""/negotiate"") != std::string::npos ? ""{ \\""availableTransports\\"": [ { \\""transport\\"": \\""ServerSentEvents\\"", \\""transferFormats\\"": [ \\""Text\\"" ] } ] }"" : """"; return http_response{ 200, response_body }; })); auto websocket_client = std::make_shared(); auto connection = connection_impl::create(create_uri(), trace_level::info, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config&) { return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); // exception not thrown } catch (const signalr_exception & e) { ASSERT_STREQ(""The server does not support WebSockets which is currently the only transport supported by this client."", e.what()); } } TEST(connection_impl_start, start_fails_if_negotiate_response_does_not_have_transports) { std::shared_ptr writer(std::make_shared()); auto http_client = std::shared_ptr(new test_http_client([](const std::string& url, http_request) { auto response_body = url.find(""/negotiate"") != std::string::npos ? ""{ \\""availableTransports\\"": [ ] }"" : """"; return http_response{ 200, response_body }; })); auto websocket_client = std::make_shared(); auto connection = connection_impl::create(create_uri(), trace_level::info, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config&) { return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); // exception not thrown } catch (const signalr_exception & e) { ASSERT_STREQ(""The server does not support WebSockets which is currently the only transport supported by this client."", e.what()); } } TEST(connection_impl_start, start_fails_if_negotiate_response_is_invalid) { std::shared_ptr writer(std::make_shared()); auto http_client = std::shared_ptr(new test_http_client([](const std::string& url, http_request) { auto response_body = url.find(""/negotiate"") != std::string::npos ? ""{ \\""availableTransports\\"": [ "" : """"; return http_response{ 200, response_body }; })); auto websocket_client = std::make_shared(); auto connection = connection_impl::create(create_uri(), trace_level::info, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config&) { return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); // exception not thrown } catch (const std::runtime_error&) { } } TEST(connection_impl_start, negotiate_follows_redirect) { std::shared_ptr writer(std::make_shared()); auto http_client = std::shared_ptr(new test_http_client([](const std::string& url, http_request) { std::string response_body = """"; if (url.find(""/negotiate"") != std::string::npos) { if (url.find(""redirected"") != std::string::npos) { response_body = ""{\\""connectionId\\"" : \\""f7707523-307d-4cba-9abf-3eef701241e8\\"", "" ""\\""availableTransports\\"" : [ { \\""transport\\"": \\""WebSockets\\"", \\""transferFormats\\"": [ \\""Text\\"", \\""Binary\\"" ] } ] }""; } else { response_body = ""{ \\""url\\"": \\""http://redirected\\"" }""; } } return http_response{ 200, response_body }; })); auto websocket_client = std::make_shared(); std::string connectUrl; websocket_client->set_connect_function([&connectUrl](const std::string& url, std::function callback) { connectUrl = url; callback(nullptr); }); auto connection = connection_impl::create(create_uri(), trace_level::info, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config& config) { websocket_client->set_config(config); return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_EQ(""ws://redirected/?id=f7707523-307d-4cba-9abf-3eef701241e8"", connectUrl); } TEST(connection_impl_start, negotiate_redirect_uses_accessToken) { std::shared_ptr writer(std::make_shared()); std::string accessToken; auto http_client = std::shared_ptr(new test_http_client([&accessToken](const std::string& url, http_request request) { std::string response_body = """"; if (url.find(""/negotiate"") != std::string::npos) { if (url.find(""redirected"") != std::string::npos) { response_body = ""{\\""connectionId\\"" : \\""f7707523-307d-4cba-9abf-3eef701241e8\\"", "" ""\\""availableTransports\\"" : [ { \\""transport\\"": \\""WebSockets\\"", \\""transferFormats\\"": [ \\""Text\\"", \\""Binary\\"" ] } ] }""; } else { response_body = ""{ \\""url\\"": \\""http://redirected\\"", \\""accessToken\\"": \\""secret\\"" }""; } } accessToken = request.headers[""Authorization""]; return http_response{ 200, response_body }; })); auto websocket_client = std::make_shared(); std::string connectUrl; websocket_client->set_connect_function([&connectUrl](const std::string& url, std::function callback) { connectUrl = url; callback(nullptr); }); auto connection = connection_impl::create(create_uri(), trace_level::info, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config& config) { websocket_client->set_config(config); return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_EQ(""ws://redirected/?id=f7707523-307d-4cba-9abf-3eef701241e8"", connectUrl); ASSERT_EQ(""Bearer secret"", accessToken); } TEST(connection_impl_start, negotiate_fails_after_too_many_redirects) { std::shared_ptr writer(std::make_shared()); auto http_client = std::shared_ptr(new test_http_client([](const std::string& url, http_request) { std::string response_body = """"; if (url.find(""/negotiate"") != std::string::npos) { // infinite redirect response_body = ""{ \\""url\\"": \\""http://redirected\\"" }""; } return http_response{ 200, response_body }; })); auto websocket_client = std::make_shared(); auto connection = connection_impl::create(create_uri(), trace_level::info, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config&) { return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); } catch (signalr_exception e) { ASSERT_STREQ(""Negotiate redirection limit exceeded."", e.what()); } } TEST(connection_impl_start, negotiate_fails_if_ProtocolVersion_in_response) { std::shared_ptr writer(std::make_shared()); auto http_client = std::shared_ptr(new test_http_client([](const std::string& url, http_request) { std::string response_body = """"; if (url.find(""/negotiate"") != std::string::npos) { response_body = ""{\\""ProtocolVersion\\"" : \\""\\"" }""; } return http_response{ 200, response_body }; })); auto websocket_client = std::make_shared(); auto connection = connection_impl::create(create_uri(), trace_level::info, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config&) { return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); } catch (signalr_exception e) { ASSERT_STREQ(""Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details."", e.what()); } } TEST(connection_impl_start, negotiate_redirect_does_not_overwrite_url) { std::shared_ptr writer(std::make_shared()); int redirectCount = 0; auto http_client = std::shared_ptr(new test_http_client([&redirectCount](const std::string& url, http_request) { std::string response_body = """"; if (url.find(""/negotiate"") != std::string::npos) { if (url.find(""redirected"") != std::string::npos) { response_body = ""{\\""connectionId\\"" : \\""f7707523-307d-4cba-9abf-3eef701241e8\\"", "" ""\\""availableTransports\\"" : [ { \\""transport\\"": \\""WebSockets\\"", \\""transferFormats\\"": [ \\""Text\\"", \\""Binary\\"" ] } ] }""; } else { response_body = ""{ \\""url\\"": \\""http://redirected\\"" }""; redirectCount++; } } return http_response{ 200, response_body }; })); auto websocket_client = std::make_shared(); auto connection = connection_impl::create(create_uri(), trace_level::info, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config& config) { websocket_client->set_config(config); return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_EQ(1, redirectCount); connection->stop([&mre](std::exception_ptr) { mre.set(); }, nullptr); mre.get(); connection->start([&mre](std::exception_ptr) { mre.set(); }); mre.get(); ASSERT_EQ(2, redirectCount); } TEST(connection_impl_start, negotiate_redirect_uses_own_query_string) { std::shared_ptr writer(std::make_shared()); std::string query_string; auto websocket_client = create_test_websocket_client( /* send function */ [](const std::string&, std::function callback) { callback(std::make_exception_ptr(std::runtime_error(""should not be invoked""))); }, /* connect function */[&query_string](const std::string& url, std::function callback) { query_string = url.substr(url.find('?') + 1); callback(std::make_exception_ptr(std::runtime_error(""connecting failed""))); }); auto http_client = std::shared_ptr(new test_http_client([](const std::string& url, http_request) { std::string response_body = """"; if (url.find(""/negotiate"") != std::string::npos) { if (url.find(""redirected"") != std::string::npos) { response_body = ""{\\""connectionId\\"" : \\""f7707523-307d-4cba-9abf-3eef701241e8\\"", "" ""\\""availableTransports\\"" : [ { \\""transport\\"": \\""WebSockets\\"", \\""transferFormats\\"": [ \\""Text\\"", \\""Binary\\"" ] } ] }""; } else { response_body = ""{ \\""url\\"": \\""http://redirected?customQuery=1\\"" }""; } } return http_response{ 200, response_body }; })); auto connection = connection_impl::create(create_uri(""a=b&c=d""), trace_level::error, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config& config) { websocket_client->set_config(config); return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); } catch (const std::runtime_error & ex) { ASSERT_STREQ(""connecting failed"", ex.what()); } ASSERT_EQ(""customQuery=1&id=f7707523-307d-4cba-9abf-3eef701241e8"", query_string); } TEST(connection_impl_start, negotiate_with_negotiateVersion_uses_connectionToken) { std::shared_ptr writer(std::make_shared()); std::string query_string; auto websocket_client = create_test_websocket_client( /* send function */ [](const std::string&, std::function callback) { callback(std::make_exception_ptr(std::runtime_error(""should not be invoked""))); }, /* connect function */[&query_string](const std::string& url, std::function callback) { query_string = url.substr(url.find('?') + 1); callback(std::make_exception_ptr(std::runtime_error(""connecting failed""))); }); auto http_client = std::shared_ptr(new test_http_client([](const std::string& url, http_request) { std::string response_body = """"; if (url.find(""/negotiate"") != std::string::npos) { response_body = ""{\\""connectionId\\"" : \\""f7707523-307d-4cba-9abf-3eef701241e8\\"", "" ""\\""connectionToken\\"":\\""1122334455\\"", \\""negotiateVersion\\"": 1, "" ""\\""availableTransports\\"" : [ { \\""transport\\"": \\""WebSockets\\"", \\""transferFormats\\"": [ \\""Text\\"", \\""Binary\\"" ] } ] }""; } return http_response{ 200, response_body }; })); auto connection = connection_impl::create(create_uri(), trace_level::error, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config& config) { websocket_client->set_config(config); return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); } catch (const std::runtime_error & ex) { ASSERT_STREQ(""connecting failed"", ex.what()); } ASSERT_EQ(""id=1122334455"", query_string); } TEST(connection_impl_start, correct_connection_id_returned_with_negotiateVersion_one) { std::shared_ptr writer(std::make_shared()); auto websocket_client = create_test_websocket_client( /* send function */ [](const std::string&, std::function callback) { callback(std::make_exception_ptr(std::runtime_error(""should not be invoked""))); }, /* connect function */[](const std::string&, std::function callback) { callback(nullptr); }); auto http_client = std::shared_ptr(new test_http_client([](const std::string& url, http_request) { std::string response_body = """"; if (url.find(""/negotiate"") != std::string::npos) { response_body = ""{\\""connectionId\\"" : \\""f7707523-307d-4cba-9abf-3eef701241e8\\"", "" ""\\""connectionToken\\"":\\""1122334455\\"", \\""negotiateVersion\\"": 1, "" ""\\""availableTransports\\"" : [ { \\""transport\\"": \\""WebSockets\\"", \\""transferFormats\\"": [ \\""Text\\"", \\""Binary\\"" ] } ] }""; } return http_response{ 200, response_body }; })); auto connection = connection_impl::create(create_uri(), trace_level::error, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config& config) { websocket_client->set_config(config); return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_EQ(""f7707523-307d-4cba-9abf-3eef701241e8"", connection->get_connection_id()); } TEST(connection_impl_start, start_fails_if_connect_request_times_out) { std::shared_ptr writer(std::make_shared()); auto http_client = create_test_http_client(); auto connect_mre = manual_reset_event(); auto wait_connect_mre = manual_reset_event(); auto websocket_client = std::make_shared(); websocket_client->set_connect_function([&connect_mre, &wait_connect_mre](const std::string&, std::function callback) { connect_mre.get(); callback(nullptr); wait_connect_mre.set(); }); auto connection = connection_impl::create(create_uri(), trace_level::info, writer, std::move(http_client), [websocket_client](const signalr_client_config& config) { websocket_client->set_config(config); return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); // exception not thrown } catch (const signalr_exception & e) { ASSERT_STREQ(""transport timed out when trying to connect"", e.what()); } connect_mre.set(); wait_connect_mre.get(); } TEST(connection_impl_start, negotiate_can_be_skipped) { std::shared_ptr writer(std::make_shared()); bool negotiate_called = false; auto http_client = std::shared_ptr(new test_http_client([&negotiate_called](const std::string& url, http_request request) { negotiate_called = true; auto response_body = url.find_first_of(""/negotiate"") != 0 ? ""{\\""connectionId\\"" : \\""f7707523-307d-4cba-9abf-3eef701241e8\\"", "" ""\\""availableTransports\\"" : [ { \\""transport\\"": \\""WebSockets\\"", \\""transferFormats\\"": [ \\""Text\\"", \\""Binary\\"" ] } ] }"" : """"; return http_response{ 200, response_body }; })); auto websocket_client = std::make_shared(); auto connection = connection_impl::create(create_uri(), trace_level::info, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config& config) { websocket_client->set_config(config); return websocket_client; }, true); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_TRUE(connection->get_connection_state() == connection_state::connected); ASSERT_TRUE(connection->get_connection_id().empty()); ASSERT_FALSE(negotiate_called); } TEST(connection_impl_process_response, process_response_logs_messages) { std::shared_ptr writer(std::make_shared()); auto wait_receive = std::make_shared(); auto websocket_client = create_test_websocket_client(); auto connection = create_connection(websocket_client, writer, trace_level::debug); auto message_mre = manual_reset_event(); connection->set_message_received([&message_mre](std::string&& message) { message_mre.set(message); }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_FALSE(websocket_client->receive_loop_started.wait(1000)); websocket_client->receive_message(""{ }""); ASSERT_STREQ(""{ }"", message_mre.get().c_str()); auto log_entries = std::dynamic_pointer_cast(writer)->get_log_entries(); ASSERT_FALSE(log_entries.empty()); ASSERT_TRUE(has_log_entry(""[debug ] processing message: { }\\n"", log_entries)) << dump_vector(log_entries); } TEST(connection_impl_send, message_sent) { std::string actual_message; auto websocket_client = create_test_websocket_client( /* send function */ [&actual_message](const std::string& message, std::function callback) { actual_message = message; callback(nullptr); }); auto connection = create_connection(websocket_client); const std::string message{ ""Test message"" }; auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); connection->send(message, transfer_format::text, [&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_EQ(message, actual_message); } TEST(connection_impl_send, send_throws_if_connection_not_connected) { auto connection = connection_impl::create(create_uri(), trace_level::none, std::make_shared()); auto mre = manual_reset_event(); connection->send(""whatever"", transfer_format::text, [&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); // exception expected but not thrown } catch (const signalr_exception & e) { ASSERT_STREQ(""cannot send data when the connection is not in the connected state. current connection state: disconnected"", e.what()); } } TEST(connection_impl_send, exceptions_from_send_logged_and_propagated) { std::shared_ptr writer(std::make_shared()); auto websocket_client = create_test_websocket_client( /* send function */ [](const std::string&, std::function callback) { callback(std::make_exception_ptr(std::runtime_error(""error""))); }); auto connection = create_connection(websocket_client, writer, trace_level::error); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); connection->send(""Test message"", transfer_format::text, [&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); // exception expected but not thrown } catch (const std::runtime_error & e) { ASSERT_STREQ(""error"", e.what()); } auto log_entries = std::dynamic_pointer_cast(writer)->get_log_entries(); ASSERT_FALSE(log_entries.empty()); ASSERT_TRUE(has_log_entry(""[error ] error sending data: error\\n"", log_entries)) << dump_vector(log_entries); } TEST(connection_impl_set_message_received, callback_invoked_when_message_received) { auto websocket_client = create_test_websocket_client(); auto connection = create_connection(websocket_client); auto message = std::make_shared(); auto message_received_event = std::make_shared(); connection->set_message_received([message, message_received_event](const std::string& m) { if (m == ""Test"") { *message = m; } if (m == ""release"") { message_received_event->cancel(); } }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); websocket_client->receive_message(""Test""); websocket_client->receive_message(""release""); ASSERT_FALSE(message_received_event->wait(5000)); ASSERT_EQ(""Test"", *message); } TEST(connection_impl_set_message_received, exception_from_callback_caught_and_logged) { auto websocket_client = create_test_websocket_client(); std::shared_ptr writer(std::make_shared()); auto connection = create_connection(websocket_client, writer, trace_level::error); auto message_received_event = std::make_shared(); connection->set_message_received([message_received_event](const std::string& m) { if (m == ""throw"") { throw std::runtime_error(""oops""); } if (m == ""release"") { message_received_event->cancel(); } }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); websocket_client->receive_message(""throw""); websocket_client->receive_message(""release""); ASSERT_FALSE(message_received_event->wait(5000)); auto log_entries = std::dynamic_pointer_cast(writer)->get_log_entries(); ASSERT_FALSE(log_entries.empty()); ASSERT_TRUE(has_log_entry(""[error ] message_received callback threw an exception: oops\\n"", log_entries)) << dump_vector(log_entries); } TEST(connection_impl_set_message_received, non_std_exception_from_callback_caught_and_logged) { auto websocket_client = create_test_websocket_client(); std::shared_ptr writer(std::make_shared()); auto connection = create_connection(websocket_client, writer, trace_level::error); auto message_received_event = std::make_shared(); connection->set_message_received([message_received_event](const std::string& m) { if (m == ""throw"") { throw 42; } if (m == ""release"") { message_received_event->cancel(); } }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); websocket_client->receive_message(""throw""); websocket_client->receive_message(""release""); ASSERT_FALSE(message_received_event->wait(5000)); auto log_entries = std::dynamic_pointer_cast(writer)->get_log_entries(); ASSERT_FALSE(log_entries.empty()); ASSERT_TRUE(has_log_entry(""[error ] message_received callback threw an unknown exception\\n"", log_entries)) << dump_vector(log_entries); } void can_be_set_only_in_disconnected_state(std::function callback, const char* expected_exception_message) { auto websocket_client = create_test_websocket_client(); auto connection = create_connection(websocket_client); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); try { callback(connection.get()); ASSERT_TRUE(false); // exception expected but not thrown } catch (const signalr_exception & e) { ASSERT_STREQ(expected_exception_message, e.what()); } } TEST(connection_impl_set_configuration, set_message_received_callback_can_be_set_only_in_disconnected_state) { can_be_set_only_in_disconnected_state( [](connection_impl* connection) { connection->set_message_received([](const std::string&) {}); }, ""cannot set the callback when the connection is not in the disconnected state. current connection state: connected""); } TEST(connection_impl_set_configuration, set_disconnected_callback_can_be_set_only_in_disconnected_state) { can_be_set_only_in_disconnected_state( [](connection_impl* connection) { connection->set_disconnected([](std::exception_ptr) {}); }, ""cannot set the disconnected callback when the connection is not in the disconnected state. current connection state: connected""); } TEST(connection_impl_stop, stopping_disconnected_connection_is_no_op) { std::shared_ptr writer{ std::make_shared() }; auto connection = connection_impl::create(create_uri(), trace_level::verbose, writer); auto mre = manual_reset_event(); connection->stop([&mre](std::exception_ptr exception) { mre.set(exception); }, nullptr); mre.get(); ASSERT_EQ(connection_state::disconnected, connection->get_connection_state()); auto log_entries = std::dynamic_pointer_cast(writer)->get_log_entries(); ASSERT_EQ(2U, log_entries.size()) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[info ] stopping connection\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[info ] acquired lock in shutdown()\\n"", log_entries)) << dump_vector(log_entries); } TEST(connection_impl_stop, stopping_disconnecting_connection_returns_canceled_task) { cancellation_token close_event; auto writer = std::shared_ptr{ std::make_shared() }; auto websocket_client = create_test_websocket_client( /* send function */ [](const std::string, std::function callback) { callback(std::make_exception_ptr(std::runtime_error(""should not be invoked""))); }, /* connect function */ [&close_event](const std::string&, std::function callback) { callback(nullptr); }, /* close function */ [&close_event](std::function callback) { close_event.wait(); callback(nullptr); }); auto connection = create_connection(websocket_client, writer, trace_level::verbose); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); connection->stop([&mre](std::exception_ptr exception) { mre.set(exception); }, nullptr); try { auto mre_stop = manual_reset_event(); connection->stop([&mre_stop](std::exception_ptr exception) { mre_stop.set(exception); }, nullptr); mre_stop.get(); ASSERT_FALSE(true); // exception expected but not thrown } catch (const signalr::canceled_exception&) { } close_event.cancel(); mre.get(); ASSERT_EQ(connection_state::disconnected, connection->get_connection_state()); auto log_entries = std::dynamic_pointer_cast(writer)->get_log_entries(); ASSERT_TRUE(has_log_entry(""[verbose ] disconnected -> connecting\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[verbose ] connecting -> connected\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[verbose ] connected -> disconnecting\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[verbose ] disconnecting -> disconnected\\n"", log_entries)) << dump_vector(log_entries); } TEST(connection_impl_stop, can_start_and_stop_connection) { auto writer = std::shared_ptr{ std::make_shared() }; auto websocket_client = create_test_websocket_client(); auto connection = create_connection(websocket_client, writer, trace_level::verbose); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); connection->stop([&mre](std::exception_ptr exception) { mre.set(exception); }, nullptr); mre.get(); auto log_entries = std::dynamic_pointer_cast(writer)->get_log_entries(); ASSERT_TRUE(has_log_entry(""[verbose ] disconnected -> connecting\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[verbose ] connecting -> connected\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[verbose ] connected -> disconnecting\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[verbose ] disconnecting -> disconnected\\n"", log_entries)) << dump_vector(log_entries); } TEST(connection_impl_stop, can_start_and_stop_connection_multiple_times) { auto writer = std::shared_ptr{ std::make_shared() }; { auto websocket_client = create_test_websocket_client(); auto connection = create_connection(websocket_client, writer, trace_level::verbose); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); connection->stop([&mre](std::exception_ptr exception) { mre.set(exception); }, nullptr); mre.get(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); } auto memory_writer = std::dynamic_pointer_cast(writer); // The connection_impl will be destroyed when the last reference to shared_ptr holding is released. This can happen // on a different thread in which case the dtor will be invoked on a different thread so we need to wait for this // to happen and if it does not the test will fail for (int wait_time_ms = 5; wait_time_ms < 100 && memory_writer->get_log_entries().size() < 16; wait_time_ms <<= 1) { std::this_thread::sleep_for(std::chrono::milliseconds(wait_time_ms)); } auto log_entries = memory_writer->get_log_entries(); ASSERT_EQ(16U, log_entries.size()) << dump_vector(log_entries); auto second_half = std::vector(log_entries.begin() + 8, log_entries.end()); log_entries = std::vector(log_entries.begin(), log_entries.begin() + 8); ASSERT_TRUE(has_log_entry(""[verbose ] disconnected -> connecting\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[verbose ] connecting -> connected\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[verbose ] connected -> disconnecting\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[verbose ] disconnecting -> disconnected\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[verbose ] disconnected -> connecting\\n"", second_half)) << dump_vector(second_half); ASSERT_TRUE(has_log_entry(""[verbose ] connecting -> connected\\n"", second_half)) << dump_vector(second_half); ASSERT_TRUE(has_log_entry(""[verbose ] connected -> disconnecting\\n"", second_half)) << dump_vector(second_half); ASSERT_TRUE(has_log_entry(""[verbose ] disconnecting -> disconnected\\n"", second_half)) << dump_vector(second_half); } TEST(connection_impl_stop, dtor_stops_the_connection) { auto writer = std::shared_ptr{ std::make_shared() }; { auto websocket_client = create_test_websocket_client(); auto connection = create_connection(websocket_client, writer, trace_level::verbose); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); } auto memory_writer = std::dynamic_pointer_cast(writer); // The connection_impl will be destroyed when the last reference to shared_ptr holding is released. This can happen // on a different thread in which case the dtor will be invoked on a different thread so we need to wait for this // to happen and if it does not the test will fail for (int wait_time_ms = 5; wait_time_ms < 6000 && memory_writer->get_log_entries().size() < 7; wait_time_ms <<= 1) { std::this_thread::sleep_for(std::chrono::milliseconds(wait_time_ms)); } auto log_entries = memory_writer->get_log_entries(); ASSERT_TRUE(has_log_entry(""[verbose ] disconnected -> connecting\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[verbose ] connecting -> connected\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[verbose ] connected -> disconnecting\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[verbose ] disconnecting -> disconnected\\n"", log_entries)) << dump_vector(log_entries); } TEST(connection_impl_stop, stop_cancels_ongoing_start_request) { auto disconnect_completed_event = std::make_shared(); auto http_client = std::shared_ptr(new test_http_client([](const std::string& url, http_request) { auto response_body = url.find(""/negotiate"") != std::string::npos ? ""{ \\""connectionId\\"" : \\""f7707523-307d-4cba-9abf-3eef701241e8\\"", "" ""\\""availableTransports\\"" : [ { \\""transport\\"": \\""WebSockets\\"", \\""transferFormats\\"": [ \\""Text\\"", \\""Binary\\"" ] } ] }"" : """"; return http_response{ 200, response_body }; })); auto wait_for_start_mre = manual_reset_event(); auto websocket_client = create_test_websocket_client( [](const std::string&, std::function callback) { callback(std::make_exception_ptr(std::exception())); }, [disconnect_completed_event, &wait_for_start_mre](const std::string&, std::function callback) { wait_for_start_mre.set(); disconnect_completed_event->wait(); callback(nullptr); }); auto writer = std::shared_ptr{ std::make_shared() }; auto connection = connection_impl::create(create_uri(), trace_level::verbose, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config& config) { websocket_client->set_config(config); return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); wait_for_start_mre.get(); connection->stop([disconnect_completed_event](std::exception_ptr) { disconnect_completed_event->cancel(); }, nullptr); try { mre.get(); ASSERT_TRUE(false); // exception expected but not thrown } catch (const canceled_exception&) { } ASSERT_EQ(connection_state::disconnected, connection->get_connection_state()); auto log_entries = std::dynamic_pointer_cast(writer)->get_log_entries(); ASSERT_TRUE(has_log_entry(""[verbose ] disconnected -> connecting\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[info ] [websocket transport] connecting to: ws://stop_cancels_ongoing_start_request/?id=f7707523-307d-4cba-9abf-3eef701241e8\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[info ] stopping connection\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[info ] acquired lock in shutdown()\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[info ] starting the connection has been canceled.\\n"", log_entries)) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[verbose ] connecting -> disconnected\\n"", log_entries)) << dump_vector(log_entries); } // Test races with start and stop TEST(connection_impl_stop, DISABLED_ongoing_start_request_canceled_if_connection_stopped_before_init_message_received) { auto stop_mre = manual_reset_event(); auto http_client = std::shared_ptr(new test_http_client([&stop_mre](const std::string& url, http_request) { stop_mre.get(); auto response_body = url.find(""/negotiate"") != std::string::npos ? ""{ \\""connectionId\\"" : \\""f7707523-307d-4cba-9abf-3eef701241e8\\"", "" ""\\""availableTransports\\"" : [ { \\""transport\\"": \\""WebSockets\\"", \\""transferFormats\\"": [ \\""Text\\"", \\""Binary\\"" ] } ] }"" : """"; return http_response{ 200, response_body }; })); auto websocket_client = create_test_websocket_client(); auto writer = std::shared_ptr{ std::make_shared() }; auto connection = connection_impl::create(create_uri(), trace_level::verbose, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config& config) { websocket_client->set_config(config); return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); connection->stop([&stop_mre](std::exception_ptr exception) { stop_mre.set(exception); }, nullptr); try { mre.get(); ASSERT_TRUE(false); // exception expected but not thrown } catch (const std::exception&) { } auto log_entries = std::dynamic_pointer_cast(writer)->get_log_entries(); ASSERT_EQ(5U, log_entries.size()) << dump_vector(log_entries); ASSERT_EQ(""[state change] disconnected -> connecting\\n"", remove_date_from_log_entry(log_entries[0])); ASSERT_EQ(""[info ] stopping connection\\n"", remove_date_from_log_entry(log_entries[1])); ASSERT_EQ(""[info ] acquired lock in shutdown()\\n"", remove_date_from_log_entry(log_entries[2])); ASSERT_EQ(""[info ] starting the connection has been canceled.\\n"", remove_date_from_log_entry(log_entries[3])); ASSERT_EQ(""[state change] connecting -> disconnected\\n"", remove_date_from_log_entry(log_entries[4])); } TEST(connection_impl_stop, stop_invokes_disconnected_callback) { auto websocket_client = create_test_websocket_client(); auto connection = create_connection(websocket_client); auto disconnected_invoked = false; connection->set_disconnected([&disconnected_invoked](std::exception_ptr) { disconnected_invoked = true; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); connection->stop([&mre](std::exception_ptr exception) { mre.set(exception); }, nullptr); mre.get(); ASSERT_TRUE(disconnected_invoked); } TEST(connection_impl_stop, std_exception_from_disconnected_callback_caught_and_logged) { auto writer = std::shared_ptr{ std::make_shared() }; auto websocket_client = create_test_websocket_client(); auto connection = create_connection(websocket_client, writer, trace_level::error); connection->set_disconnected([](std::exception_ptr) { throw std::runtime_error(""exception from disconnected""); }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); connection->stop([&mre](std::exception_ptr exception) { mre.set(exception); }, nullptr); mre.get(); auto log_entries = std::dynamic_pointer_cast(writer)->get_log_entries(); ASSERT_EQ(1U, log_entries.size()) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[error ] disconnected callback threw an exception: exception from disconnected\\n"", log_entries)) << dump_vector(log_entries); } TEST(connection_impl_stop, exception_from_disconnected_callback_caught_and_logged) { auto writer = std::shared_ptr{ std::make_shared() }; auto websocket_client = create_test_websocket_client(); auto connection = create_connection(websocket_client, writer, trace_level::error); connection->set_disconnected([](std::exception_ptr) { throw 42; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); connection->stop([&mre](std::exception_ptr exception) { mre.set(exception); }, nullptr); mre.get(); auto log_entries = std::dynamic_pointer_cast(writer)->get_log_entries(); ASSERT_EQ(1U, log_entries.size()) << dump_vector(log_entries); ASSERT_TRUE(has_log_entry(""[error ] disconnected callback threw an unknown exception\\n"", log_entries)) << dump_vector(log_entries); } TEST(connection_impl_stop, transport_error_invokes_disconnected_callback) { auto websocket_client = create_test_websocket_client(); auto connection = create_connection(websocket_client); auto disconnect_mre = manual_reset_event(); connection->set_disconnected([&disconnect_mre](std::exception_ptr ex) { disconnect_mre.set(ex); }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); ASSERT_FALSE(websocket_client->receive_loop_started.wait(1000)); websocket_client->receive_message(std::make_exception_ptr(custom_exception(""error""))); try { disconnect_mre.get(); ASSERT_TRUE(false); } catch (const custom_exception& ex) { ASSERT_STREQ(""error"", ex.what()); } ASSERT_EQ(connection_state::disconnected, connection->get_connection_state()); } TEST(connection_impl_config, custom_headers_set_in_requests) { auto writer = std::shared_ptr{ std::make_shared() }; auto http_client = std::shared_ptr(new test_http_client([](const std::string& url, http_request) { auto response_body = url.find(""/negotiate"") != std::string::npos ? ""{\\""connectionId\\"" : \\""f7707523-307d-4cba-9abf-3eef701241e8\\"", "" ""\\""availableTransports\\"" : [ { \\""transport\\"": \\""WebSockets\\"", \\""transferFormats\\"": [ \\""Text\\"", \\""Binary\\"" ] } ] }"" : """"; /*auto request = new web_request_stub((unsigned short)200, ""OK"", response_body); request->on_get_response = [](web_request_stub& request) { auto http_headers = request.m_signalr_client_config.get_http_headers(); ASSERT_EQ(1U, http_headers.size()); ASSERT_EQ(_XPLATSTR(""42""), http_headers[_XPLATSTR(""Answer"")]); };*/ return http_response{ 200, response_body }; })); auto websocket_client = create_test_websocket_client(); auto connection = connection_impl::create(create_uri(), trace_level::verbose, writer, [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config& config) { websocket_client->set_config(config); return websocket_client; }); signalr::signalr_client_config signalr_client_config{}; auto http_headers = signalr_client_config.get_http_headers(); http_headers[""Answer""] = ""42""; signalr_client_config.set_http_headers(http_headers); connection->set_client_config(signalr_client_config); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); connection->stop([&mre](std::exception_ptr exception) { mre.set(exception); }, nullptr); mre.get(); ASSERT_EQ(connection_state::disconnected, connection->get_connection_state()); } TEST(connection_impl_set_config, config_can_be_set_only_in_disconnected_state) { can_be_set_only_in_disconnected_state( [](connection_impl* connection) { signalr::signalr_client_config signalr_client_config; connection->set_client_config(signalr_client_config); }, ""cannot set client config when the connection is not in the disconnected state. current connection state: connected""); } TEST(connection_impl_change_state, change_state_logs) { std::shared_ptr writer(std::make_shared()); auto websocket_client = create_test_websocket_client(); auto connection = create_connection(websocket_client, writer, trace_level::verbose); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); auto log_entries = std::dynamic_pointer_cast(writer)->get_log_entries(); ASSERT_FALSE(log_entries.empty()); ASSERT_TRUE(has_log_entry(""[verbose ] disconnected -> connecting\\n"", log_entries)) << dump_vector(log_entries); } TEST(connection_id, connection_id_is_set_if_start_fails_but_negotiate_request_succeeds) { std::shared_ptr writer(std::make_shared()); auto websocket_client = create_test_websocket_client( /* send function */ [](const std::string, std::function callback) { callback(std::make_exception_ptr(std::runtime_error(""should not be invoked""))); }, /* connect function */[](const std::string&, std::function callback) { callback(std::make_exception_ptr(std::runtime_error(""connecting failed""))); }); auto connection = create_connection(websocket_client, writer, trace_level::error); ASSERT_EQ("""", connection->get_connection_id()); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); try { mre.get(); ASSERT_TRUE(false); } catch (const std::runtime_error & ex) { ASSERT_STREQ(""connecting failed"", ex.what()); } ASSERT_EQ(""f7707523-307d-4cba-9abf-3eef701241e8"", connection->get_connection_id()); } TEST(connection_id, can_get_connection_id_when_connection_in_connected_state) { auto writer = std::shared_ptr{ std::make_shared() }; auto websocket_client = create_test_websocket_client(); auto connection = create_connection(websocket_client, writer, trace_level::verbose); std::string connection_id; auto mre = manual_reset_event(); connection->start([&mre, &connection_id, connection](std::exception_ptr exception) { connection_id = connection->get_connection_id(); mre.set(exception); }); mre.get(); connection->stop([&mre](std::exception_ptr exception) { mre.set(exception); }, nullptr); mre.get(); ASSERT_EQ(""f7707523-307d-4cba-9abf-3eef701241e8"", connection_id); } TEST(connection_id, can_get_connection_id_after_connection_has_stopped) { auto writer = std::shared_ptr{ std::make_shared() }; auto websocket_client = create_test_websocket_client(); auto connection = create_connection(websocket_client, writer, trace_level::verbose); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); connection->stop([&mre](std::exception_ptr exception) { mre.set(exception); }, nullptr); mre.get(); ASSERT_EQ(""f7707523-307d-4cba-9abf-3eef701241e8"", connection->get_connection_id()); } TEST(connection_id, connection_id_reset_when_starting_connection) { auto fail_http_requests = false; auto writer = std::shared_ptr{ std::make_shared() }; auto websocket_client = create_test_websocket_client(); auto http_client = std::shared_ptr(new test_http_client([&fail_http_requests](const std::string& url, http_request) { if (!fail_http_requests) { auto response_body = url.find(""/negotiate"") != std::string::npos ? ""{\\""connectionId\\"" : \\""f7707523-307d-4cba-9abf-3eef701241e8\\"", "" ""\\""availableTransports\\"" : [ { \\""transport\\"": \\""WebSockets\\"", \\""transferFormats\\"": [ \\""Text\\"", \\""Binary\\"" ] } ] }"" : """"; return http_response{ 200, response_body }; } return http_response{ 500, """" }; })); auto connection = connection_impl::create(create_uri(), trace_level::none, std::make_shared(), [http_client](const signalr_client_config& config) { http_client->set_scheduler(config.get_scheduler()); return http_client; }, [websocket_client](const signalr_client_config& config) { websocket_client->set_config(config); return websocket_client; }); auto mre = manual_reset_event(); connection->start([&mre](std::exception_ptr exception) { mre.set(exception); }); mre.get(); connection->stop([&mre](std::exception_ptr exception) { mre.set(exception); }, nullptr); mre.get(); ASSERT_EQ(""f7707523-307d-4cba-9abf-3eef701241e8"", connection->get_connection_id()); fail_http_requests = true; connection->start([&mre](std::exception_ptr) { mre.set(); }); mre.get(); ASSERT_EQ("""", connection->get_connection_id()); } ",16179,True,3944.572517148161,median "[[release-notes-7.3.2]] == {es} version 7.3.2 Also see <>. [[bug-7.3.2]] [float] === Bug fixes Data Frame:: * Fix off-by-one error in checkpoint operations_behind {es-pull}46235[#46235] Distributed:: * Update translog checkpoint after marking operations as persisted {es-pull}45634[#45634] (issue: {es-issue}29161[#29161]) Engine:: * Handle delete document level failures {es-pull}46100[#46100] (issue: {es-issue}46083[#46083]) * Handle no-op document level failures {es-pull}46083[#46083] Infra/Scripting:: * Fix bugs in Painless SCatch node {es-pull}45880[#45880] Machine learning:: * Throw an error when a datafeed needs {ccs} but it is not enabled for the node {es-pull}46044[#46044] SQL:: * SQL: Fix issue with IIF function when condition folds {es-pull}46290[#46290] (issue: {es-issue}46268[#46268]) * SQL: Fix issue with DataType for CASE with NULL {es-pull}46173[#46173] (issue: {es-issue}46032[#46032]) Search:: * Multi-get requests should wait for search active {es-pull}46283[#46283] (issue: {es-issue}27500[#27500]) * Ensure top docs optimization is fully disabled for queries with unbounded max scores. {es-pull}46105[#46105] (issue: {es-issue}45933[#45933]) [[release-notes-7.3.1]] == {es} version 7.3.1 Also see <>. [[enhancement-7.3.1]] [float] === Enhancements CCR:: * Include leases in error message when operations are no longer available {es-pull}45681[#45681] Infra/Core:: * Add OCI annotations and adjust existing annotations {es-pull}45167[#45167] (issues: {es-issue}45162[#45162], {es-issue}45166[#45166]) Infra/Settings:: * Normalize environment paths {es-pull}45179[#45179] (issue: {es-issue}45176[#45176]) Machine Learning:: * Outlier detection should only fetch docs that have the analyzed fields {es-pull}44944[#44944] SQL:: * Remove deprecated use of ""interval"" from date_histogram usage {es-pull}45501[#45501] (issue: {es-issue}43922[#43922]) [[bug-7.3.1]] [float] === Bug fixes Aggregations:: * Fix early termination of aggregators that run with breadth-first mode {es-pull}44963[#44963] (issue: {es-issue}44909[#44909]) Analysis:: * Enable reloading of synonym_graph filters {es-pull}45135[#45135] (issue: {es-issue}45127[#45127]) Authentication:: * Do not use scroll when finding duplicate API key {es-pull}45026[#45026] * Fix broken short-circuit in getUnlicensedRealms {es-pull}44399[#44399] CCR:: * Clean up ShardFollowTasks for deleted indices {es-pull}44702[#44702] (issue: {es-issue}34404[#34404]) CRUD:: * Allow _update on write alias {es-pull}45318[#45318] (issue: {es-issue}31520[#31520]) Data Frame:: * Fix starting a batch {dataframe-transform} after stopping at runtime {es-pull}45340[#45340] (issues: {es-issue}44219[#44219], {es-issue}45339[#45339]) * Fix null aggregation handling in indexer {es-pull}45061[#45061] (issue: {es-issue}44906[#44906]) Distributed:: * Ensure AsyncTask#isScheduled remains false after close {es-pull}45687[#45687] (issue: {es-issue}45576[#45576]) * Fix clock used in update requests {es-pull}45262[#45262] (issue: {es-issue}45254[#45254]) * Restore DefaultShardOperationFailedException's reason during deserialization {es-pull}45203[#45203] Features/Watcher:: * Fix watcher HttpClient URL creation {es-pull}45207[#45207] (issue: {es-issue}44970[#44970]) Infra/Packaging:: * Use bundled JDK in Sys V init {es-pull}45593[#45593] (issue: {es-issue}45542[#45542]) Infra/Settings:: * Fix a bug with elasticsearch.common.settings.Settings.processSetting {es-pull}44047[#44047] (issue: {es-issue}43791[#43791]) MULTIPLE AREA LABELS:: * Fix a bug where mappings are dropped from rollover requests. {es-pull}45411[#45411] (issue: {es-issue}45399[#45399]) * Sparse role queries can throw an NPE {es-pull}45053[#45053] Machine Learning:: * Check dest index is empty when starting {dfanalytics} {es-pull}45094[#45094] * Catch any error thrown while closing {dfanalytics} process {es-pull}44958[#44958] * Only trap the case where more rows are supplied to outlier detection than expected. Previously, if rows were excluded from the {dataframe-transform} after supplying the row count in the configuration, we detected the inconsistency and failed outlier detection. However, this situation legitimately happens in cases where the field values are non-numeric or array valued. {ml-pull}569[#569] Mapping:: * Make sure to validate the type before attempting to merge a new mapping. {es-pull}45157[#45157] (issues: {es-issue}29316[#29316], {es-issue}43012[#43012]) SQL:: * Adds format parameter to range queries for constant date comparisons {es-pull}45326[#45326] (issue: {es-issue}45139[#45139]) * Uniquely named inner_hits sections for each nested field condition {es-pull}45039[#45039] (issues: {es-issue}33080[#33080], {es-issue}44544[#44544]) * Fix URI path being lost in case of hosted ES scenario {es-pull}44776[#44776] (issue: {es-issue}44721[#44721]) Search:: * Prevent Leaking Search Tasks on Exceptions in FetchSearchPhase and DfsQueryPhase {es-pull}45500[#45500] * Fix an NPE when requesting inner hits and _source is disabled. {es-pull}44836[#44836] (issue: {es-issue}43517[#43517]) Security:: * Fix .security-* indices auto-create {es-pull}44918[#44918] * Use system context for looking up connected nodes {es-pull}43991[#43991] (issue: {es-issue}43974[#43974]) [[upgrade-7.3.1]] [float] === Upgrades Infra/Packaging:: * Upgrade to JDK 12.0.2 {es-pull}45172[#45172] [[release-notes-7.3.0]] == {es} version 7.3.0 Also see <>. [float] === Known issues * Applying deletes or updates on an index after it has been shrunk may corrupt the index. In order to prevent this issue, it is recommended to stop shrinking read-write indices. For read-only indices, it is recommended to force-merge indices after shrinking, which significantly reduces the likeliness of this corruption in the case that deletes/updates would be applied by mistake. This bug is fixed in {es} 7.7 and later versions. More details can be found on the https://issues.apache.org/jira/browse/LUCENE-9300[corresponding issue]. * Indices created in 6.x with <> and <> fields using formats that are incompatible with java.time patterns will cause parsing errors, incorrect date calculations or wrong search results. https://github.com/elastic/elasticsearch/pull/52555 This is fixed in {es} 7.7 and later versions. [[breaking-7.3.0]] [float] === Breaking changes CCR:: * Do not allow modify aliases on followers {es-pull}43017[#43017] (issue: {es-issue}41396[#41396]) Data Frame:: * Removing format support in date_histogram group_by {es-pull}43659[#43659] [[breaking-java-7.3.0]] [float] === Breaking Java changes Mapping:: * Refactor put mapping request validation for reuse {es-pull}43005[#43005] (issues: {es-issue}37675[#37675], {es-issue}41396[#41396]) Search:: * Refactor IndexSearcherWrapper to disallow the wrapping of IndexSearcher {es-pull}43645[#43645] [[deprecation-7.3.0]] [float] === Deprecations Features/Java High Level REST Client:: * Deprecate native code info in xpack info api {es-pull}43297[#43297] Mapping:: * Deprecate support for chained multi-fields. {es-pull}41926[#41926] (issue: {es-issue}41267[#41267]) Network:: * Deprecate transport profile security type setting {es-pull}43237[#43237] Search:: * Deprecate CommonTermsQuery and cutoff_frequency {es-pull}42619[#42619] (issue: {es-issue}37096[#37096]) [[feature-7.3.0]] [float] === New features Aggregations:: * Adds a minimum interval to `auto_date_histogram`. {es-pull}42814[#42814] (issue: {es-issue}41757[#41757]) * Add RareTerms aggregation {es-pull}35718[#35718] (issue: {es-issue}20586[#20586]) Audit:: * Enable console audit logs for docker {es-pull}42671[#42671] (issue: {es-issue}42666[#42666]) Data Frame:: * Add sync api {es-pull}41800[#41800] Infra/Settings:: * Consistent Secure Settings {es-pull}40416[#40416] Machine Learning:: * Machine learning data frame analytics {es-pull}43544[#43544] Mapping:: * Add support for 'flattened object' fields. {es-pull}42541[#42541] (issues: {es-issue}25312[#25312], {es-issue}33003[#33003]) Ranking:: * Move dense_vector and sparse_vector to module {es-pull}43280[#43280] SQL:: * SQL: Add support for FROZEN indices {es-pull}41558[#41558] (issues: {es-issue}39377[#39377], {es-issue}39390[#39390]) Search:: * Wildcard intervals {es-pull}43691[#43691] (issue: {es-issue}43198[#43198]) * Add prefix intervals source {es-pull}43635[#43635] (issue: {es-issue}43198[#43198]) [[enhancement-7.3.0]] [float] === Enhancements Aggregations:: * Allocate memory lazily in BestBucketsDeferringCollector {es-pull}43339[#43339] (issue: {es-issue}43091[#43091]) * Reduce the number of docvalues iterator created in the global ordinals fielddata {es-pull}43091[#43091] Analysis:: * Return reloaded analyzers in _reload_search_ananlyzer response {es-pull}43813[#43813] (issue: {es-issue}43804[#43804]) * Allow reloading of search time analyzers {es-pull}43313[#43313] (issue: {es-issue}29051[#29051]) * Allow reloading of search time analyzers {es-pull}42888[#42888] (issue: {es-issue}29051[#29051]) * Allow reloading of search time analyzers {es-pull}42669[#42669] (issue: {es-issue}29051[#29051]) Authentication:: * Always attach system user to internal actions {es-pull}43468[#43468] (issue: {es-issue}42215[#42215]) * Add kerberos grant_type to get token in exchange for Kerberos ticket {es-pull}42847[#42847] (issue: {es-issue}41943[#41943]) * Permit API Keys on Basic License {es-pull}42787[#42787] Authorization:: * Add ""manage_api_key"" cluster privilege {es-pull}43728[#43728] (issue: {es-issue}42020[#42020]) * Use separate BitSet cache in Doc Level Security {es-pull}43669[#43669] (issue: {es-issue}30974[#30974]) * Support builtin privileges in get privileges API {es-pull}42134[#42134] (issue: {es-issue}29771[#29771]) CCR:: * Replicate aliases in cross-cluster replication {es-pull}41815[#41815] (issue: {es-issue}41396[#41396]) Cluster Coordination:: * Ignore unknown fields if overriding node metadata {es-pull}44689[#44689] * Add voting-only master node {es-pull}43410[#43410] (issue: {es-issue}14340[#14340]) * Defer reroute when nodes join {es-pull}42855[#42855] * Stop SeedHostsResolver on shutdown {es-pull}42844[#42844] * Log leader and handshake failures by default {es-pull}42342[#42342] (issue: {es-issue}42153[#42153]) Data Frame:: * Add a frequency option to transform config, default 1m {es-pull}44120[#44120] * Add node attr to GET _stats {es-pull}43842[#43842] (issue: {es-issue}43743[#43743]) * Add deduced mappings to _preview response payload {es-pull}43742[#43742] (issue: {es-issue}39250[#39250]) * Add support for allow_no_match for endpoints {es-pull}43490[#43490] (issue: {es-issue}42766[#42766]) * Add version and create_time to transform config {es-pull}43384[#43384] (issue: {es-issue}43037[#43037]) * Have sum map to a double to prevent overflows {es-pull}43213[#43213] * Add new pipeline field to dest config {es-pull}43124[#43124] (issue: {es-issue}43061[#43061]) * Write a warning audit on bulk index failures {es-pull}43106[#43106] * Add support for weighted_avg agg {es-pull}42646[#42646] Distributed:: * Improve Close Index Response {es-pull}39687[#39687] (issue: {es-issue}33888[#33888]) Engine:: * Use reader attributes to control term dict memory useage {es-pull}42838[#42838] (issue: {es-issue}38390[#38390]) * Remove sort by primary term when reading soft-deletes {es-pull}43845[#43845] * Refresh translog stats after translog trimming in NoOpEngine {es-pull}43825[#43825] (issue: {es-issue}43156[#43156]) * Expose translog stats in ReadOnlyEngine {es-pull}43752[#43752] * Do not use soft-deletes to resolve indexing strategy {es-pull}43336[#43336] (issues: {es-issue}35230[#35230], {es-issue}42979[#42979], {es-issue}43202[#43202]) * Rebuild version map when opening internal engine {es-pull}43202[#43202] (issues: {es-issue}40741[#40741], {es-issue}42979[#42979]) * Only load FST off heap if we are actually using mmaps for the term dictionary {es-pull}43158[#43158] (issue: {es-issue}43150[#43150]) * Trim translog for closed indices {es-pull}43156[#43156] (issue: {es-issue}42445[#42445]) * Also mmap terms index (`.tip`) files for hybridfs {es-pull}43150[#43150] (issue: {es-issue}42838[#42838]) * Add a merge policy that prunes ID postings for soft-deleted but retained documents {es-pull}40741[#40741] Features/Indices APIs:: * Remove ""template"" field in IndexTemplateMetadata {es-pull}42099[#42099] (issue: {es-issue}38502[#38502]) Features/Ingest:: * Avoid HashMap construction on Grok non-match {es-pull}42444[#42444] * Improve how internal representation of pipelines are updated {es-pull}42257[#42257] Features/Java High Level REST Client:: * Add _reload_search_analyzers endpoint to HLRC {es-pull}43733[#43733] (issue: {es-issue}43313[#43313]) * Bulk processor concurrent requests {es-pull}41451[#41451] Features/Java Low Level REST Client:: * Adapt low-level REST client to java 8 {es-pull}41537[#41537] (issue: {es-issue}38540[#38540]) Features/Monitoring:: * Expand beats_system role privileges {es-pull}40876[#40876] Features/Watcher:: * Improve CryptoService error message on missing secure file {es-pull}43623[#43623] (issue: {es-issue}43619[#43619]) * Watcher: Allow to execute actions for each element in array {es-pull}41997[#41997] (issue: {es-issue}34546[#34546]) Infra/Core:: * Shortcut simple patterns ending in `*` {es-pull}43904[#43904] * Prevent merging nodes' data paths {es-pull}42665[#42665] (issue: {es-issue}42489[#42489]) * Deprecation info for joda-java migration on 7.x {es-pull}42659[#42659] (issue: {es-issue}42010[#42010]) * Implement XContentParser.genericMap and XContentParser.genericMapOrdered methods {es-pull}42059[#42059] Infra/Packaging:: * Omit JDK sources archive from bundled JDK {es-pull}42821[#42821] Infra/Plugins:: * Enable node roles to be pluggable {es-pull}43175[#43175] Infra/Scripting:: * Add annotations to Painless whitelist {es-pull}43239[#43239] * Add painless method getByPath, get value from nested collections with dotted path {es-pull}43170[#43170] (issue: {es-issue}42769[#42769]) * Add painless method getByPath, get value from nested collections with dotted path {es-pull}43129[#43129] (issue: {es-issue}42769[#42769]) Machine Learning:: * Add version and create_time to data frame analytics config {es-pull}43683[#43683] * Improve message when native controller cannot connect {es-pull}43565[#43565] (issue: {es-issue}42341[#42341]) * Report exponential_avg_bucket_processing_time which gives more weight to recent buckets {es-pull}43189[#43189] (issue: {es-issue}29857[#29857]) * Adding support for geo_shape, geo_centroid, geo_point in datafeeds {es-pull}42969[#42969] (issue: {es-issue}42820[#42820]) * Report timing stats as part of the Job stats response {es-pull}42709[#42709] (issue: {es-issue}29857[#29857]) * Increase maximum forecast interval to 10 years. {es-pull}41082[#41082] (issue: {es-issue}41103[#41103]) * Upgrade to a newer version of the Apache Portable Runtime library. {ml-pull}495[#495] * Improve stability of modelling around change points. {ml-pull}496[#496] * Restrict detection of epoch timestamps in find_file_structure {es-pull}43188[#43188] * Better detection of binary input in find_file_structure {es-pull}42707[#42707] * Add a limit on line merging in find_file_structure {es-pull}42501[#42501] (issue: {es-issue}38086[#38086]) * Improve file structure finder timestamp format determination {es-pull}41948[#41948] (issues: {es-issue}35132[#35132], {es-issue}35137[#35137], {es-issue}38086[#38086]) * Add earliest and latest timestamps to field stats in find_file_structure response {es-pull}42890[#42890] * Change dots in CSV column names to underscores in find_file_structure response {es-pull}42839[#42839] (issue: {es-issue}26800[#26800]) Mapping:: * Add dims parameter to dense_vector mapping {es-pull}43444[#43444] * Added parsing of erroneous field value {es-pull}42321[#42321] (issue: {es-issue}41372[#41372]) Network:: * Do not hang on unsupported HTTP methods {es-pull}43362[#43362] Ranking:: * Fix parameter value for calling data.advanceExact {es-pull}44205[#44205] * Distance measures for dense and sparse vectors {es-pull}37947[#37947] (issue: {es-issue}31615[#31615]) Recovery:: * Make peer recovery send file info step async {es-pull}43792[#43792] (issue: {es-issue}36195[#36195]) * Make peer recovery clean files step async {es-pull}43787[#43787] (issue: {es-issue}36195[#36195]) Reindex:: * Reindex max_docs parameter name {es-pull}41894[#41894] (issue: {es-issue}24344[#24344]) Search:: * Split search in two when made against read-only and write indices {es-pull}42510[#42510] (issue: {es-issue}40900[#40900]) * Rename SearchRequest#crossClusterSearch {es-pull}42363[#42363] * Allow `fields` to be set to `*` {es-pull}42301[#42301] (issue: {es-issue}39577[#39577]) * Search - enable low_level_cancellation by default. {es-pull}42291[#42291] (issue: {es-issue}26258[#26258]) * Cut over ClusterSearchShardsGroup to Writeable {es-pull}41788[#41788] * Disable max score optimization for queries with unbounded max scores {es-pull}41361[#41361] Snapshot/Restore:: * Recursive Delete on BlobContainer {es-pull}43281[#43281] (issue: {es-issue}42189[#42189]) * Add SAS Token Authentication Support to Azure Repo Plugin {es-pull}42982[#42982] (issue: {es-issue}42117[#42117]) * Enable Parallel Deletes in Azure Repository {es-pull}42783[#42783] * Add Ability to List Child Containers to BlobContainer {es-pull}42653[#42653] (issue: {es-issue}42189[#42189]) * Add custom metadata to snapshots {es-pull}41281[#41281] (issue: {es-issue}40638[#40638]) Store:: * Shard CLI tool always check shards {es-pull}41480[#41480] (issue: {es-issue}41298[#41298]) [[bug-7.3.0]] [float] === Bug fixes Aggregations:: * Fix incorrect calculation of how many buckets will result from a merge {es-pull}44461[#44461] (issue: {es-issue}43577[#43577]) * Set document on script when using Bytes.WithScript {es-pull}43390[#43390] * Bug fix to allow access to top level params in reduce script {es-pull}42096[#42096] (issue: {es-issue}42046[#42046]) Allocation:: * Do not copy initial recovery filter during split {es-pull}44053[#44053] (issue: {es-issue}43955[#43955]) * Avoid parallel reroutes in DiskThresholdMonitor {es-pull}43381[#43381] (issue: {es-issue}40174[#40174]) * Reset failed allocation counter before executing routing commands {es-pull}42658[#42658] (issue: {es-issue}39546[#39546]) * Validate routing commands using updated routing state {es-pull}42066[#42066] (issue: {es-issue}41050[#41050]) Analysis:: * Fix AnalyzeAction response serialization {es-pull}44284[#44284] (issue: {es-issue}44078[#44078]) * Actually close IndexAnalyzers contents {es-pull}43914[#43914] * Issue deprecation warnings for preconfigured delimited_payload_filter {es-pull}43684[#43684] (issues: {es-issue}26625[#26625], {es-issue}43568[#43568]) * Use preconfigured filters correctly in Analyze API {es-pull}43568[#43568] (issue: {es-issue}43002[#43002]) * Require [articles] setting in elision filter {es-pull}43083[#43083] (issue: {es-issue}43002[#43002]) Authentication:: * Fix broken short-circuit in getUnlicensedRealms {es-pull}44399[#44399] * Fix Token Service retry mechanism {es-pull}39639[#39639] CCR:: * Skip update if leader and follower settings identical {es-pull}44535[#44535] (issue: {es-issue}44521[#44521]) * Avoid stack overflow in auto-follow coordinator {es-pull}44421[#44421] (issue: {es-issue}43251[#43251]) * Avoid NPE when checking for CCR index privileges {es-pull}44397[#44397] (issue: {es-issue}44172[#44172]) * CCR should not replicate private/internal settings {es-pull}43067[#43067] (issue: {es-issue}41268[#41268]) CRUD:: * Fix NPE when rejecting bulk updates {es-pull}42923[#42923] * Fix ""size"" field in the body of AbstractBulkByScrollRequest {es-pull}35742[#35742] (issue: {es-issue}35636[#35636]) Cluster Coordination:: * Local node is discovered when cluster fails {es-pull}43316[#43316] * Reset state recovery after successful recovery {es-pull}42576[#42576] (issue: {es-issue}39172[#39172]) * Cluster state from API should always have a master {es-pull}42454[#42454] (issues: {es-issue}38331[#38331], {es-issue}38432[#38432]) * Omit non-masters in ClusterFormationFailureHelper {es-pull}41344[#41344] Data Frame:: * Treat bulk index failures as an indexing failure {es-pull}44351[#44351] (issue: {es-issue}44101[#44101]) * Responding with 409 status code when failing _stop {es-pull}44231[#44231] (issue: {es-issue}44103[#44103]) * Adds index validations to _start data frame transform {es-pull}44191[#44191] (issue: {es-issue}44104[#44104]) * Data frame task failure do not make a 500 response {es-pull}44058[#44058] (issue: {es-issue}44011[#44011]) * Audit message missing for autostop {es-pull}43984[#43984] (issue: {es-issue}43977[#43977]) * Add data frame transform cluster privileges to HLRC {es-pull}43879[#43879] * Improve pivot nested field validations {es-pull}43548[#43548] * Adjusting error message {es-pull}43455[#43455] * Size the GET stats search by number of Ids requested {es-pull}43206[#43206] (issue: {es-issue}43203[#43203]) * Rewrite start and stop to answer with acknowledged {es-pull}42589[#42589] (issue: {es-issue}42450[#42450]) * Set data frame transform task state to stopped when stopping {es-pull}42516[#42516] (issue: {es-issue}42441[#42441]) Distributed:: * Fix DefaultShardOperationFailedException subclass xcontent serialization {es-pull}43435[#43435] (issue: {es-issue}43423[#43423]) * Advance checkpoints only after persisting ops {es-pull}43205[#43205] * Avoid loading retention leases while writing them {es-pull}42620[#42620] (issue: {es-issue}41430[#41430]) * Do not use ifSeqNo for update requests on mixed cluster {es-pull}42596[#42596] (issue: {es-issue}42561[#42561]) * Ensure relocation target still tracked when start handoff {es-pull}42201[#42201] Engine:: * AsyncIOProcessor preserve thread context {es-pull}43729[#43729] * Account soft deletes for committed segments {es-pull}43126[#43126] (issue: {es-issue}43103[#43103]) * Prune _id of only docs below local checkpoint of safe commit {es-pull}43051[#43051] (issues: {es-issue}40741[#40741], {es-issue}42979[#42979]) * Improve translog corruption detection {es-pull}42744[#42744] (issue: {es-issue}42661[#42661]) Features/CAT APIs:: * Fix indices shown in _cat/indices {es-pull}43286[#43286] (issues: {es-issue}33888[#33888], {es-issue}38824[#38824], {es-issue}39933[#39933]) Features/ILM:: * Fix swapped variables in error message {es-pull}44300[#44300] * Account for node versions during allocation in ILM Shrink {es-pull}43300[#43300] (issue: {es-issue}41879[#41879]) * Narrow period of Shrink action in which ILM prevents stopping {es-pull}43254[#43254] (issue: {es-issue}43253[#43253]) * Make ILM force merging best effort {es-pull}43246[#43246] (issues: {es-issue}42824[#42824], {es-issue}43245[#43245]) Features/Indices APIs:: * Check shard limit after applying index templates {es-pull}44619[#44619] (issues: {es-issue}34021[#34021], {es-issue}44567[#44567], {es-issue}44619[#44619]) * Validate index settings after applying templates {es-pull}44612[#44612] (issues: {es-issue}34021[#34021], {es-issue}44567[#44567]) * Prevent NullPointerException in TransportRolloverAction {es-pull}43353[#43353] (issue: {es-issue}43296[#43296]) Features/Ingest:: * Read the default pipeline for bulk upsert through an alias {es-pull}41963[#41963] Features/Java High Level REST Client:: * Fix CreateRepository Requeset in HLRC {es-pull}43522[#43522] (issue: {es-issue}43521[#43521]) Features/Stats:: * Return 0 for negative ""free"" and ""total"" memory reported by the OS {es-pull}42725[#42725] (issue: {es-issue}42157[#42157]) Features/Watcher:: * NullPointerException when creating a watch with Jira action (#41922) {es-pull}42081[#42081] * fix unlikely bug that can prevent Watcher from restarting {es-pull}42030[#42030] Infra/Core:: * Add default CLI JVM options {es-pull}44545[#44545] (issues: {es-issue}219[#219], {es-issue}42021[#42021]) * scheduleAtFixedRate would hang {es-pull}42993[#42993] (issue: {es-issue}38441[#38441]) * Only ignore IOException when fsyncing on dirs {es-pull}42972[#42972] (issue: {es-issue}42950[#42950]) * Fix alpha build error message when generate version object from version string {es-pull}40406[#40406] * Bat scripts to work with JAVA_HOME with parantheses {es-pull}39712[#39712] (issues: {es-issue}30606[#30606], {es-issue}33405[#33405], {es-issue}38578[#38578], {es-issue}38624[#38624]) * Change licence expiration date pattern {es-pull}39681[#39681] (issue: {es-issue}39136[#39136]) Infra/Packaging:: * Restore setting up temp dir for windows service {es-pull}44541[#44541] * Fix the bundled jdk flag to be passed through windows startup {es-pull}43502[#43502] Infra/Plugins:: * Do not checksum all bytes at once in plugin install {es-pull}44649[#44649] (issue: {es-issue}44545[#44545]) Infra/REST API:: * Remove deprecated _source_exclude and _source_include from get API spec {es-pull}42188[#42188] Infra/Scripting:: * Allow aggregations using expressions to use _score {es-pull}42652[#42652] Machine Learning:: * Update .ml-config mappings before indexing job, datafeed or df analytics config {es-pull}44216[#44216] (issue: {es-issue}44263[#44263]) * Wait for .ml-config primary before assigning persistent tasks {es-pull}44170[#44170] (issue: {es-issue}44156[#44156]) * Fix ML memory tracker lockup when inner step fails {es-pull}44158[#44158] (issue: {es-issue}44156[#44156]) * Reduce false positives associated with the multi-bucket feature. {ml-pull}491[#491] * Reduce false positives for sum and count functions on sparse data. {ml-pull}492[#492] * Fix an edge case causing spurious anomalies (false positives) if the variance in the count of events changed significantly throughout the period of a seasonal quantity. (See {ml-pull}489[#489].) Mapping:: * Ensure field caps doesn't error on rank feature fields. {es-pull}44370[#44370] (issue: {es-issue}44330[#44330]) * Prevent types deprecation warning for indices.exists requests {es-pull}43963[#43963] (issue: {es-issue}43905[#43905]) * Fix index_prefix sub field name on nested text fields {es-pull}43862[#43862] (issue: {es-issue}43741[#43741]) * Fix possible NPE in put mapping validators {es-pull}43000[#43000] (issue: {es-issue}37675[#37675]) * Allow big integers and decimals to be mapped dynamically. {es-pull}42827[#42827] (issue: {es-issue}37846[#37846]) Network:: * Reconnect remote cluster when seeds are changed {es-pull}43379[#43379] (issue: {es-issue}37799[#37799]) * Don't require TLS for single node clusters {es-pull}42826[#42826] * Fix Class Load Order in Netty4Plugin {es-pull}42591[#42591] (issue: {es-issue}42532[#42532]) Recovery:: * Ensure to access RecoveryState#fileDetails under lock {es-pull}43839[#43839] * Make Recovery API support `detailed` params {es-pull}29076[#29076] (issue: {es-issue}28910[#28910]) Reindex:: * Properly serialize remote query in ReindexRequest {es-pull}43457[#43457] (issues: {es-issue}43406[#43406], {es-issue}43456[#43456]) * Fixing handling of auto slices in bulk scroll requests {es-pull}43050[#43050] * Remote reindex failure parse fix {es-pull}42928[#42928] * Fix concurrent search and index delete {es-pull}42621[#42621] (issue: {es-issue}28053[#28053]) * Propogate version in reindex from remote search {es-pull}42412[#42412] (issue: {es-issue}31908[#31908]) SQL:: * SQL: change the size of the list of concrete indices when resolving multiple indices {es-pull}43878[#43878] (issue: {es-issue}43876[#43876]) * SQL: handle double quotes escaping {es-pull}43829[#43829] (issue: {es-issue}43810[#43810]) * SQL: add pretty printing to JSON format {es-pull}43756[#43756] * SQL: handle SQL not being available in a more graceful way {es-pull}43665[#43665] (issue: {es-issue}41279[#41279]) * SQL: fix NPE in case of subsequent scrolled requests for a CSV/TSV formatted response {es-pull}43365[#43365] (issue: {es-issue}43327[#43327]) * Geo: Add coerce support to libs/geo WKT parser {es-pull}43273[#43273] (issue: {es-issue}43173[#43173]) * SQL: Increase hard limit for sorting on aggregates {es-pull}43220[#43220] (issue: {es-issue}43168[#43168]) * SQL: Fix wrong results when sorting on aggregate {es-pull}43154[#43154] (issue: {es-issue}42851[#42851]) * SQL: cover the Integer type when extracting values from _source {es-pull}42859[#42859] (issue: {es-issue}42858[#42858]) Search:: * Don't use index_phrases on graph queries {es-pull}44340[#44340] (issue: {es-issue}43976[#43976]) * Fix wrong logic in `match_phrase` query with multi-word synonyms {es-pull}43941[#43941] (issue: {es-issue}43308[#43308]) * Fix UOE on search requests that match a sparse role query {es-pull}43668[#43668] (issue: {es-issue}42857[#42857]) * Fix propagation of enablePositionIncrements in QueryStringQueryBuilder {es-pull}43578[#43578] (issue: {es-issue}43574[#43574]) * Fix score mode of the MinimumScoreCollector {es-pull}43527[#43527] (issue: {es-issue}43497[#43497]) * Fix round up of date range without rounding {es-pull}43303[#43303] (issue: {es-issue}43277[#43277]) * SearchRequest#allowPartialSearchResults does not handle successful retries {es-pull}43095[#43095] (issue: {es-issue}40743[#40743]) * Wire query cache into sorting nested-filter computation {es-pull}42906[#42906] (issue: {es-issue}42813[#42813]) * Fix auto fuzziness in query_string query {es-pull}42897[#42897] * Fix IntervalBuilder#analyzeText to never return `null` {es-pull}42750[#42750] (issue: {es-issue}42587[#42587]) * Fix sorting on nested field with unmapped {es-pull}42451[#42451] (issue: {es-issue}33644[#33644]) * Deduplicate alias and concrete fields in query field expansion {es-pull}42328[#42328] Security:: * Do not swallow I/O exception getting authentication {es-pull}44398[#44398] (issues: {es-issue}44172[#44172], {es-issue}44397[#44397]) * Use system context for looking up connected nodes {es-pull}43991[#43991] (issue: {es-issue}43974[#43974]) * SecurityIndexSearcherWrapper doesn't always carry over caches and similarity {es-pull}43436[#43436] * Detect when security index is closed {es-pull}42191[#42191] Snapshot/Restore:: * Check again on-going snapshots/restores of indices before closing {es-pull}43873[#43873] * Fix Azure List by Prefix Bug {es-pull}42713[#42713] Store:: * Remove usage of FileSwitchDirectory {es-pull}42937[#42937] (issue: {es-issue}37111[#37111]) * Fix Infinite Loops in ExceptionsHelper#unwrap {es-pull}42716[#42716] (issue: {es-issue}42340[#42340]) Suggesters:: * Fix suggestions for empty indices {es-pull}42927[#42927] (issue: {es-issue}42473[#42473]) * Skip explain phase when only suggestions are requested {es-pull}41739[#41739] (issue: {es-issue}31260[#31260]) [[regression-7.3.0]] [float] === Regressions Infra/Core:: * Restore date aggregation performance in UTC case {es-pull}38221[#38221] (issue: {es-issue}37826[#37826]) [[upgrade-7.3.0]] [float] === Upgrades Discovery-Plugins:: * Upgrade AWS SDK to Latest Version {es-pull}42708[#42708] Engine:: * Upgrade to Lucene 8.1.0 {es-pull}42214[#42214] Infra/Core:: * Upgrade HPPC to version 0.8.1 {es-pull}43025[#43025] Network:: * Upgrade to Netty 4.1.36 {es-pull}42543[#42543] (issue: {es-issue}42532[#42532]) Snapshot/Restore:: * Upgrade GCS Repository Dependencies {es-pull}43142[#43142] ",12375,True,3131.062147566494,median "[[scoreCalculation]] = Score calculation :doctype: book :sectnums: :icons: font [[scoreTerminology]] == Score terminology [[whatIsAScore]] === What is a score? Every `@PlanningSolution` class has a score. The score is an objective way to compare two solutions. The solution with the higher score is better. The `Solver` aims to find the solution with the highest `Score` of all possible solutions. The _best solution_ is the solution with the highest `Score` that `Solver` has encountered during solving, which might be the __optimal solution__. OptaPlanner cannot automatically know which solution is best for your business, so you need to tell it how to calculate the score of a given `@PlanningSolution` instance according to your business needs. If you forget or are unable to implement an important business constraint, the solution is probably useless: image::score-calculation/optimalWithIncompleteConstraints.png[align=""center""] [[formalizeTheBusinessConstraints]] === Formalize the business constraints To implement a verbal business constraint, it needs to be formalized as a score constraint. Luckily, defining constraints in OptaPlanner is very flexible through the following score techniques: * **Score signum (positive or negative)**: maximize or minimize a constraint type * **Score weight**: put a cost/profit on a constraint type * **Score level (hard, soft, ...)**: prioritize a group of constraint types * *Pareto scoring* (rarely used) Take the time to acquaint yourself with the first three techniques. Once you understand them, formalizing most business constraints becomes straightforward. [NOTE] ==== Do not presume that your business knows all its score constraints in advance. Expect score constraints to be added, changed or removed after the first releases. ==== [[scoreConstraintSignum]] === Score constraint signum (positive or negative) All score techniques are based on constraints. A constraint can be a simple pattern (such as __Maximize the apple harvest in the solution__) or a more complex pattern. A positive constraint is a constraint you want to maximize. A negative constraint is a constraint you want to minimize image::score-calculation/positiveAndNegativeConstraints.png[align=""center""] The image above illustrates that **the optimal solution always has the highest score**, regardless if the constraints are positive or negative. Most planning problems have only negative constraints and therefore have a negative score. In that case, the score is the sum of the weight of the negative constraints being broken, with a perfect score of 0. For example in n queens, the score is the negative of the number of queen pairs which can attack each other. Negative and positive constraints can be combined, even in the same score level. When a constraint activates (because the negative constraint is broken or the positive constraint is fulfilled) on a certain planning entity set, it is called a __constraint match__. [[scoreConstraintWeight]] === Score constraint weight Not all score constraints are equally important. If breaking one constraint is equally bad as breaking another constraint x times, then those two constraints have a different weight (but they are in the same score level). For example in vehicle routing, you can make one _unhappy driver_ constraint match count as much as two _fuel tank usage_ constraint matches: image::score-calculation/scoreWeighting.png[align=""center""] Score weighting is easy in use cases where you can __put a price tag on everything__. In that case, the positive constraints maximize revenue and the negative constraints minimize expenses, so together they maximize profit. Alternatively, score weighting is also often used to create social <>. For example, a nurse, who requests a free day, pays a higher weight on New Years eve than on a normal day. The weight of a constraint match can depend on the planning entities involved. For example in cloud balancing, the weight of the soft constraint match for an active `Computer` is the maintenance `cost` of that `Computer` (which differs per computer). Putting a good weight on a constraint is often a difficult analytical decision, because it is about making choices and trade-offs against other constraints. Different stakeholders have different priorities. *Don't waste time with constraint weight discussions at the start of an implementation, instead add a <> and allow users to change them through a UI.* A non-accurate weight is less damaging than mediocre algorithms: image::score-calculation/scoreTradeoffInPerspective.png[align=""center""] Most use cases use a `Score` with `int` weights, such as <>. [[scoreLevel]] === Score constraint level (hard, soft, ...) Sometimes a score constraint outranks another score constraint, no matter how many times the latter is broken. In that case, those score constraints are in different levels. For example, a nurse cannot do two shifts at the same time (due to the constraints of physical reality), so this outranks all nurse happiness constraints. Most use cases have only two score levels, hard and soft. The levels of two scores are compared lexicographically. The first score level gets compared first. If those differ, the remaining score levels are ignored. For example, a score that breaks `0` hard constraints and `1000000` soft constraints is better than a score that breaks `1` hard constraint and `0` soft constraints. image::score-calculation/scoreLevels.png[align=""center""] If there are two (or more) score levels, for example <>, then a score is _feasible_ if no hard constraints are broken. [NOTE] ==== By default, OptaPlanner will always assign all planning variables a planning value. If there is no feasible solution, this means the best solution will be infeasible. To instead leave some of the planning entities unassigned, apply xref:repeated-planning/repeated-planning.adoc#overconstrainedPlanning[overconstrained planning]. ==== For each constraint, you need to pick a score level, a score weight and a score signum. For example: `-1soft` which has score level of ``soft``, a weight of `1` and a negative signum. Do not use a big constraint weight when your business actually wants different score levels. That hack, known as __score folding__, is broken: image::score-calculation/scoreFoldingIsBroken.png[align=""center""] [NOTE] ==== Your business might tell you that your hard constraints all have the same weight, because they cannot be broken (so the weight does not matter). This is not true because if no feasible solution exists for a specific dataset, the least infeasible solution allows the business to estimate how many business resources they are lacking. For example in cloud balancing, how many new computers to buy. Furthermore, it will likely create a <>. For example in cloud balance if a `Computer` has seven CPU too little for its ``Process``es, then it must be weighted seven times as much as if it had only one CPU too little. ==== Three or more score levels are also supported. For example: a company might decide that profit outranks employee satisfaction (or vice versa), while both are outranked by the constraints of physical reality. [NOTE] ==== To model <>, there is no need to use lots of score levels (even though OptaPlanner can handle many score levels). ==== Most use cases use a `Score` with two or three weights, such as <> and <>. [[paretoScoring]] === Pareto scoring (AKA multi-objective optimization scoring) Far less common is the use case of pareto optimization, which is also known as _multi-objective optimization_. In pareto scoring, score constraints are in the same score level, yet they are not weighted against each other. When two scores are compared, each of the score constraints are compared individually and the score with the most dominating score constraints wins. Pareto scoring can even be combined with score levels and score constraint weighting. Consider this example with positive constraints, where we want to get the most apples and oranges. Since it is impossible to compare apples and oranges, we cannot weigh them against each other. Yet, despite that we cannot compare them, we can state that two apples are better than one apple. Similarly, we can state that two apples and one orange are better than just one orange. So despite our inability to compare some Scores conclusively (at which point we declare them equal), we can find a set of optimal scores. Those are called pareto optimal. image::score-calculation/paretoOptimizationScoring.png[align=""center""] Scores are considered equal far more often. It is left up to a human to choose the better out of a set of best solutions (with equal scores) found by OptaPlanner. In the example above, the user must choose between solution A (three apples and one orange) and solution B (one apple and six oranges). It is guaranteed that OptaPlanner has not found another solution which has more apples or more oranges or even a better combination of both (such as two apples and three oranges). Pareto scoring is currently not supported in OptaPlanner. [NOTE] ==== A pareto ``Score``'s `compareTo` method is not transitive because it does a pareto comparison. For example: having two apples is greater than one apple. One apple is equal to One orange. Yet, two apples are not greater than one orange (but actually equal). Pareto comparison violates the contract of the interface ``java.lang.Comparable``'s `compareTo` method, but Planners systems are __pareto comparison safe__, unless explicitly stated otherwise in this documentation. ==== [[combiningScoreTechniques]] === Combining score techniques All the score techniques mentioned above, can be combined seamlessly: image::score-calculation/scoreComposition.png[align=""center""] [[scoreInterface]] === `Score` interface A score is represented by the `Score` interface, which naturally extends ``Comparable``: [source,java,options=""nowrap""] ---- public interface Score<...> extends Comparable<...> { ... } ---- The `Score` implementation to use depends on your use case. Your score might not efficiently fit in a single `long` value. OptaPlanner has several built-in `Score` implementations, but you can implement a custom `Score` too. Most use cases tend to use the built-in ``HardSoftScore``. image::score-calculation/scoreClassDiagram.png[align=""center""] All Score implementations also have an `initScore` (which is an ``int``).It is mostly intended for internal use in OptaPlanner: it is the negative number of uninitialized planning variables. From a user's perspective this is ``0``, unless a Construction Heuristic is terminated before it could initialize all planning variables (in which case `Score.isSolutionInitialized()` returns ``false``). The `Score` implementation (for example ``HardSoftScore``) must be the same throughout a `Solver` runtime. The `Score` implementation is configured in the solution domain class: [source,java,options=""nowrap""] ---- @PlanningSolution public class CloudBalance { ... @PlanningScore private HardSoftScore score; } ---- [[avoidFloatingPointNumbersInScoreCalculation]] === Avoid floating point numbers in score calculation Avoid the use of `float` or `double` in score calculation. Use `BigDecimal` or scaled `long` instead. Floating point numbers (``float`` and ``double``) cannot represent a decimal number correctly. For example: a `double` cannot hold the value `0.05` correctly. Instead, it holds the nearest representable value. Arithmetic (including addition and subtraction) with floating point numbers, especially for planning problems, leads to incorrect decisions: image::score-calculation/scoreWeightType.png[align=""center""] Additionally, floating point number addition is not associative: [source,java,options=""nowrap""] ---- System.out.println( ((0.01 + 0.02) + 0.03) == (0.01 + (0.02 + 0.03)) ); // returns false ---- This leads to __score corruption__. Decimal numbers (``BigDecimal``) have none of these problems. [NOTE] ==== BigDecimal arithmetic is considerably slower than ``int``, `long` or `double` arithmetic. In experiments we have seen the score calculation take five times longer. Therefore, in many cases, it can be worthwhile to multiply _all_ numbers for a single score weight by a plural of ten, so the score weight fits in a scaled `int` or ``long``. For example, if we multiply all weights by ``1000``, a fuelCost of `0.07` becomes a fuelCostMillis of `70` and no longer uses a decimal score weight. ==== [[scoreType]] == Choose a score type Depending on the number of score levels and type of score weights you need, choose a `Score` type. Most use cases use a ``HardSoftScore``. [NOTE] ==== To properly write a `Score` to a database (with JPA/Hibernate) or to XML/JSON (with XStream/JAXB/Jackson), see xref:integration/integration.adoc#integration[the integration chapter]. ==== [[simpleScore]] === `SimpleScore` A `SimpleScore` has a single `int` value, for example ``-123``. It has a single score level. [source,java,options=""nowrap""] ---- @PlanningScore private SimpleScore score; ---- Variants of this `Score` type: * `SimpleLongScore` uses a `long` value instead of an `int` value. * `SimpleBigDecimalScore` uses a `BigDecimal` value instead of an `int` value. [[hardSoftScore]] === `HardSoftScore` (Recommended) A `HardSoftScore` has a hard `int` value and a soft `int` value, for example ``-123hard/-456soft``. It has two score levels (hard and soft). [source,java,options=""nowrap""] ---- @PlanningScore private HardSoftScore score; ---- Variants of this `Score` type: * `HardSoftLongScore` uses `long` values instead of `int` values. * `HardSoftBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[hardMediumSoftScore]] === `HardMediumSoftScore` A `HardMediumSoftScore` which has a hard `int` value, a medium `int` value and a soft `int` value, for example ``-123hard/-456medium/-789soft``. It has three score levels (hard, medium and soft). The hard level determines if the solution is feasible, and the medium level and soft level score values determine how well the solution meets business goals. Higher medium values take precedence over soft values irrespective of the soft value. [source,java,options=""nowrap""] ---- @PlanningScore private HardMediumSoftScore score; ---- Variants of this `Score` type: * `HardMediumSoftLongScore` uses `long` values instead of `int` values. * `HardMediumSoftBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[bendableScore]] === `BendableScore` A `BendableScore` has a configurable number of score levels. It has an array of hard `int` values and an array of soft `int` values, for example with two hard levels and three soft levels, the score can be ``[-123/-456]hard/[-789/-012/-345]soft``. In that case, it has five score levels. A solution is feasible if all hard levels are at least zero. A BendableScore with one hard level and one soft level is equivalent to a HardSoftScore, while a BendableScore with one hard level and two soft levels is equivalent to a HardMediumSoftScore. [source,java,options=""nowrap""] ---- @PlanningScore(bendableHardLevelsSize = 2, bendableSoftLevelsSize = 3) private BendableScore score; ---- The number of hard and soft score levels need to be set at compilation time. It is not flexible to change during solving. [NOTE] ==== Do not use a `BendableScore` with seven levels just because you have seven constraints. It is extremely rare to use a different score level for each constraint, because that means one constraint match on soft 0 outweighs even a million constraint matches of soft 1. Usually, multiple constraints share the same level and are weighted against each other. Use <> to get the weight of individual constraints in the same level. ==== Variants of this `Score` type: * `BendableLongScore` uses `long` values instead of `int` values. * `BendableBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[calculateTheScore]] == Calculate the `Score` [[scoreCalculationTypes]] === Score calculation types There are several ways to calculate the `Score` of a solution: * **<>**: Implement all constraints together in a single method in Java (or another JVM language). Does not scale. * **xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint streams score calculation]**: Implement each constraint as a separate Constraint Stream in Java (or another JVM language). Fast and scalable. * **<>** (not recommended): Implement multiple low-level methods in Java (or another JVM language). Fast and scalable. Very difficult to implement and maintain. * **xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation]**: Implement each constraint as a separate score rule in DRL. Scalable. Every score calculation type can work with any Score definition (such as ``HardSoftScore`` or ``HardMediumSoftScore``). All score calculation types are Object Oriented and can reuse existing Java code. [IMPORTANT] ==== The score calculation must be read-only. It must not change the planning entities or the problem facts in any way. For example, it must not call a setter method on a planning entity in the score calculation. OptaPlanner does not recalculate the score of a solution if it can predict it (unless an xref:planner-configuration/planner-configuration.adoc#environmentMode[environmentMode assertion] is enabled). For example, after a winning step is done, there is no need to calculate the score because that move was done and undone earlier. As a result, there is no guarantee that changes applied during score calculation actually happen. To update planning entities when the planning variable change, use xref:shadow-variable/shadow-variable.adoc#shadowVariable[shadow variables] instead. ==== [[easyJavaScoreCalculation]] === Easy Java score calculation An easy way to implement your score calculation in Java. * Advantages: ** Plain old Java: no learning curve ** Opportunity to delegate score calculation to an existing code base or legacy system * Disadvantages: ** Slower ** Does not scale because there is no <> Implement the one method of the interface ``EasyScoreCalculator``: [source,java,options=""nowrap""] ---- public interface EasyScoreCalculator> { Score_ calculateScore(Solution_ solution); } ---- For example in n queens: [source,java,options=""nowrap""] ---- public class NQueensEasyScoreCalculator implements EasyScoreCalculator { @Override public SimpleScore calculateScore(NQueens nQueens) { int n = nQueens.getN(); List queenList = nQueens.getQueenList(); int score = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { Queen leftQueen = queenList.get(i); Queen rightQueen = queenList.get(j); if (leftQueen.getRow() != null && rightQueen.getRow() != null) { if (leftQueen.getRowIndex() == rightQueen.getRowIndex()) { score--; } if (leftQueen.getAscendingDiagonalIndex() == rightQueen.getAscendingDiagonalIndex()) { score--; } if (leftQueen.getDescendingDiagonalIndex() == rightQueen.getDescendingDiagonalIndex()) { score--; } } } } return SimpleScore.valueOf(score); } } ---- Configure it in the solver configuration: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.nqueens.optional.score.NQueensEasyScoreCalculator ---- To configure values of an `EasyScoreCalculator` dynamically in the solver configuration (so the xref:benchmarking-and-tweaking/benchmarking-and-tweaking.adoc#benchmarker[Benchmarker] can tweak those parameters), add the `easyScoreCalculatorCustomProperties` element and use xref:planner-configuration/planner-configuration.adoc#customPropertiesConfiguration[custom properties]: [source,xml,options=""nowrap""] ---- ...MyEasyScoreCalculator ---- [[incrementalJavaScoreCalculation]] === Incremental Java score calculation A way to implement your score calculation incrementally in Java. * Advantages: ** Very fast and scalable *** Currently the fastest if implemented correctly * Disadvantages: ** Hard to write *** A scalable implementation heavily uses maps, indexes, ... (things the Drools rule engine can do for you) *** You have to learn, design, write and improve all these performance optimizations yourself ** Hard to read *** Regular score constraint changes can lead to a high maintenance cost Implement all the methods of the interface `IncrementalScoreCalculator`: [source,java,options=""nowrap""] ---- public interface IncrementalScoreCalculator> { void resetWorkingSolution(Solution_ workingSolution); void beforeEntityAdded(Object entity); void afterEntityAdded(Object entity); void beforeVariableChanged(Object entity, String variableName); void afterVariableChanged(Object entity, String variableName); void beforeEntityRemoved(Object entity); void afterEntityRemoved(Object entity); Score_ calculateScore(); } ---- image::score-calculation/incrementalScoreCalculatorSequenceDiagram.png[align=""center""] For example in n queens: [source,java,options=""nowrap""] ---- public class NQueensAdvancedIncrementalScoreCalculator implements IncrementalScoreCalculator { private Map> rowIndexMap; private Map> ascendingDiagonalIndexMap; private Map> descendingDiagonalIndexMap; private int score; public void resetWorkingSolution(NQueens nQueens) { int n = nQueens.getN(); rowIndexMap = new HashMap>(n); ascendingDiagonalIndexMap = new HashMap>(n * 2); descendingDiagonalIndexMap = new HashMap>(n * 2); for (int i = 0; i < n; i++) { rowIndexMap.put(i, new ArrayList(n)); ascendingDiagonalIndexMap.put(i, new ArrayList(n)); descendingDiagonalIndexMap.put(i, new ArrayList(n)); if (i != 0) { ascendingDiagonalIndexMap.put(n - 1 + i, new ArrayList(n)); descendingDiagonalIndexMap.put((-i), new ArrayList(n)); } } score = 0; for (Queen queen : nQueens.getQueenList()) { insert(queen); } } public void beforeEntityAdded(Object entity) { // Do nothing } public void afterEntityAdded(Object entity) { insert((Queen) entity); } public void beforeVariableChanged(Object entity, String variableName) { retract((Queen) entity); } public void afterVariableChanged(Object entity, String variableName) { insert((Queen) entity); } public void beforeEntityRemoved(Object entity) { retract((Queen) entity); } public void afterEntityRemoved(Object entity) { // Do nothing } private void insert(Queen queen) { Row row = queen.getRow(); if (row != null) { int rowIndex = queen.getRowIndex(); List rowIndexList = rowIndexMap.get(rowIndex); score -= rowIndexList.size(); rowIndexList.add(queen); List ascendingDiagonalIndexList = ascendingDiagonalIndexMap.get(queen.getAscendingDiagonalIndex()); score -= ascendingDiagonalIndexList.size(); ascendingDiagonalIndexList.add(queen); List descendingDiagonalIndexList = descendingDiagonalIndexMap.get(queen.getDescendingDiagonalIndex()); score -= descendingDiagonalIndexList.size(); descendingDiagonalIndexList.add(queen); } } private void retract(Queen queen) { Row row = queen.getRow(); if (row != null) { List rowIndexList = rowIndexMap.get(queen.getRowIndex()); rowIndexList.remove(queen); score += rowIndexList.size(); List ascendingDiagonalIndexList = ascendingDiagonalIndexMap.get(queen.getAscendingDiagonalIndex()); ascendingDiagonalIndexList.remove(queen); score += ascendingDiagonalIndexList.size(); List descendingDiagonalIndexList = descendingDiagonalIndexMap.get(queen.getDescendingDiagonalIndex()); descendingDiagonalIndexList.remove(queen); score += descendingDiagonalIndexList.size(); } } public SimpleScore calculateScore() { return SimpleScore.valueOf(score); } } ---- Configure it in the solver configuration: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.nqueens.optional.score.NQueensAdvancedIncrementalScoreCalculator ---- [IMPORTANT] ==== A piece of incremental score calculator code can be difficult to write and to review. <> by using an ``EasyScoreCalculator`` to fulfill the assertions triggered by the ``environmentMode``. ==== To configure values of an `IncrementalScoreCalculator` dynamically in the solver configuration (so the xref:benchmarking-and-tweaking/benchmarking-and-tweaking.adoc#benchmarker[Benchmarker] can tweak those parameters), add the `incrementalScoreCalculatorCustomProperties` element and use xref:planner-configuration/planner-configuration.adoc#customPropertiesConfiguration[custom properties]: [source,xml,options=""nowrap""] ---- ...MyIncrementalScoreCalculator ---- [[constraintMatchAwareIncrementalScoreCalculator]] ==== `ConstraintMatchAwareIncrementalScoreCalculator` Optionally, also implement the `ConstraintMatchAwareIncrementalScoreCalculator` interface to: * Explain a score by splitting it up per score constraint with `ScoreExplanation.getConstraintMatchTotalMap()`. * Visualize or sort planning entities by how many constraints each one breaks with `ScoreExplanation.getIndictmentMap()`. * Receive a detailed analysis if the `IncrementalScoreCalculator` is corrupted in `FAST_ASSERT` or `FULL_ASSERT` `environmentMode`, [source,java,options=""nowrap""] ---- public interface ConstraintMatchAwareIncrementalScoreCalculator> { void resetWorkingSolution(Solution_ workingSolution, boolean constraintMatchEnabled); Collection> getConstraintMatchTotals(); Map> getIndictmentMap(); } ---- For example in machine reassignment, create one `ConstraintMatchTotal` per constraint type and call `addConstraintMatch()` for each constraint match: [source,java,options=""nowrap""] ---- public class MachineReassignmentIncrementalScoreCalculator implements ConstraintMatchAwareIncrementalScoreCalculator { ... @Override public void resetWorkingSolution(MachineReassignment workingSolution, boolean constraintMatchEnabled) { resetWorkingSolution(workingSolution); // ignore constraintMatchEnabled, it is always presumed enabled } @Override public Collection> getConstraintMatchTotals() { ConstraintMatchTotal maximumCapacityMatchTotal = new DefaultConstraintMatchTotal<>(CONSTRAINT_PACKAGE, ""maximumCapacity"", HardSoftLongScore.ZERO); ... for (MrMachineScorePart machineScorePart : machineScorePartMap.values()) { for (MrMachineCapacityScorePart machineCapacityScorePart : machineScorePart.machineCapacityScorePartList) { if (machineCapacityScorePart.maximumAvailable < 0L) { maximumCapacityMatchTotal.addConstraintMatch( Arrays.asList(machineCapacityScorePart.machineCapacity), HardSoftLongScore.valueOf(machineCapacityScorePart.maximumAvailable, 0)); } } } ... List> constraintMatchTotalList = new ArrayList<>(4); constraintMatchTotalList.add(maximumCapacityMatchTotal); ... return constraintMatchTotalList; } @Override public Map> getIndictmentMap() { return null; // Calculate it non-incrementally from getConstraintMatchTotals() } } ---- That `getConstraintMatchTotals()` code often duplicates some of the logic of the normal `IncrementalScoreCalculator` methods. Constraint Streams and Drools Score Calculation don't have this disadvantage, because they are constraint match aware automatically when needed, without any extra domain-specific code. [[initializingScoreTrend]] === `InitializingScoreTrend` The `InitializingScoreTrend` specifies how the Score will change as more and more variables are initialized (while the already initialized variables do not change). Some optimization algorithms (such Construction Heuristics and Exhaustive Search) run faster if they have such information. For the Score (or each <> separately), specify a trend: * `ANY` (default): Initializing an extra variable can change the score positively or negatively. Gives no performance gain. * `ONLY_UP` (rare): Initializing an extra variable can only change the score positively. Implies that: ** There are only positive constraints ** And initializing the next variable cannot unmatch a positive constraint that was matched by a previous initialized variable. * ``ONLY_DOWN``: Initializing an extra variable can only change the score negatively. Implies that: ** There are only negative constraints ** And initializing the next variable cannot unmatch a negative constraint that was matched by a previous initialized variable. Most use cases only have negative constraints. Many of those have an `InitializingScoreTrend` that only goes down: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.cloudbalancing.score.CloudBalancingConstraintProvider ONLY_DOWN ---- Alternatively, you can also specify the trend for each score level separately: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.cloudbalancing.score.CloudBalancingConstraintProvider ONLY_DOWN/ONLY_DOWN ---- [[invalidScoreDetection]] === Invalid score detection When you put the xref:planner-configuration/planner-configuration.adoc#environmentMode[`environmentMode`] in `FULL_ASSERT` (or ``FAST_ASSERT``), it will detect score corruption in the <>. However, that will not verify that your score calculator actually implements your score constraints as your business desires. For example, one constraint might consistently match the wrong pattern. To verify the constraints against an independent implementation, configure a ``assertionScoreDirectorFactory``: [source,xml,options=""nowrap""] ---- FAST_ASSERT ... org.optaplanner.examples.nqueens.optional.score.NQueensConstraintProvider org.optaplanner.examples.nqueens.optional.score.NQueensEasyScoreCalculator ---- This way, the `NQueensConstraintProvider` implementation is validated by the ``EasyScoreCalculator``. [NOTE] ==== This works well to isolate score corruption, but to verify that the constraint implement the real business needs, xref:constraint-streams/constraint-streams.adoc#constraintStreamsTesting[a unit test with a ConstraintVerifier] is usually better. ==== [[scoreCalculationPerformanceTricks]] == Score calculation performance tricks [[scoreCalculationPerformanceTricksOverview]] === Overview The `Solver` will normally spend most of its execution time running the score calculation (which is called in its deepest loops). Faster score calculation will return the same solution in less time with the same algorithm, which normally means a better solution in equal time. [[scoreCalculationSpeed]] === Score calculation speed After solving a problem, the `Solver` will log the __score calculation speed per second__. This is a good measurement of Score calculation performance, despite that it is affected by non score calculation execution time. It depends on the problem scale of the problem dataset. Normally, even for high scale problems, it is higher than ``1000``, except if you are using an ``EasyScoreCalculator``. [IMPORTANT] ==== When improving your score calculation, focus on maximizing the score calculation speed, instead of maximizing the best score. A big improvement in score calculation can sometimes yield little or no best score improvement, for example when the algorithm is stuck in a local or global optima. If you are watching the calculation speed instead, score calculation improvements are far more visible. Furthermore, watching the calculation speed allows you to remove or add score constraints, and still compare it with the original's calculation speed. Comparing the best score with the original's best score is pointless: it's comparing apples and oranges. ==== [[incrementalScoreCalculation]] === Incremental score calculation (with deltas) When a solution changes, incremental score calculation (AKA delta based score calculation) calculates the delta with the previous state to find the new ``Score``, instead of recalculating the entire score on every solution evaluation. For example, when a single queen A moves from row `1` to ``2``, it will not bother to check if queen B and C can attack each other, since neither of them changed: image::score-calculation/incrementalScoreCalculationNQueens04.png[align=""center""] Similarly in employee rostering: image::score-calculation/incrementalScoreCalculationEmployeeRostering.png[align=""center""] This is a huge performance and scalability gain. *xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint Streams] or xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation] give you this huge scalability gain without forcing you to write a complicated incremental score calculation algorithm.* Just let the rule engine do the hard work. Notice that the speedup is relative to the size of your planning problem (your __n__), making incremental score calculation far more scalable. [[avoidCallingRemoteServicesDuringScoreCalculation]] === Avoid calling remote services during score calculation Do not call remote services in your score calculation (except if you are bridging `EasyScoreCalculator` to a legacy system). The network latency will kill your score calculation performance. Cache the results of those remote services if possible. If some parts of a constraint can be calculated once, when the `Solver` starts, and never change during solving, then turn them into xref:planner-configuration/planner-configuration.adoc#cachedProblemFact[cached problem facts]. [[pointlessConstraints]] === Pointless constraints If you know a certain constraint can never be broken (or it is always broken), do not write a score constraint for it. For example in n queens, the score calculation does not check if multiple queens occupy the same column, because a ``Queen``'s `column` never changes and every solution starts with each `Queen` on a different ``column``. [NOTE] ==== Do not go overboard with this. If some datasets do not use a specific constraint but others do, just return out of the constraint as soon as you can. There is no need to dynamically change your score calculation based on the dataset. ==== [[buildInHardConstraint]] === Built-in hard constraint Instead of implementing a hard constraint, it can sometimes be built in. For example, if `Lecture` A should never be assigned to `Room` X, but it uses `ValueRangeProvider` on Solution, so the `Solver` will often try to assign it to `Room` X too (only to find out that it breaks a hard constraint). Use xref:planner-configuration/planner-configuration.adoc#valueRangeProviderOnPlanningEntity[a ValueRangeProvider on the planning entity] or xref:move-and-neighborhood-selection/move-and-neighborhood-selection.adoc#filteredSelection[filtered selection] to define that Course A should only be assigned a `Room` different than X. This can give a good performance gain in some use cases, not just because the score calculation is faster, but mainly because most optimization algorithms will spend less time evaluating infeasible solutions. However, usually this is not a good idea because there is a real risk of trading short term benefits for long term harm: * Many optimization algorithms rely on the freedom to break hard constraints when changing planning entities, to get out of local optima. * Both implementation approaches have limitations (feature compatibility, disabling automatic performance optimizations), as explained in their documentation. [[otherScoreCalculationPerformanceTricks]] === Other score calculation performance tricks * Verify that your score calculation happens in the correct `Number` type. If you are making the sum of `int` values, do not sum it in a `double` which takes longer. * For optimal performance, always use server mode (``java -server``). We have seen performance increases of 50% by turning on server mode. * For optimal performance, use the latest Java version. For example, in the past we have seen performance increases of 30% by switching from java 1.5 to 1.6. * Always remember that premature optimization is the root of all evil. Make sure your design is flexible enough to allow configuration based tweaking. [[scoreTrap]] === Score trap Make sure that none of your score constraints cause a score trap. A trapped score constraint uses the same weight for different constraint matches, when it could just as easily use a different weight. It effectively lumps its constraint matches together, which creates a flatlined score function for that constraint. This can cause a solution state in which several moves need to be done to resolve or lower the weight of that single constraint. Some examples of score traps: * You need two doctors at each table, but you are only moving one doctor at a time. So the solver has no incentive to move a doctor to a table with no doctors. Punish a table with no doctors more than a table with only one doctor in that score constraint in the score function. * Two exams need to be conducted at the same time, but you are only moving one exam at a time. So the solver has to move one of those exams to another timeslot without moving the other in the same move. Add a coarse-grained move that moves both exams at the same time. For example, consider this score trap. If the blue item moves from an overloaded computer to an empty computer, the hard score should improve. The trapped score implementation fails to do that: image::score-calculation/scoreTrap.png[align=""center""] The Solver should eventually get out of this trap, but it will take a lot of effort (especially if there are even more processes on the overloaded computer). Before they do that, they might actually start moving more processes into that overloaded computer, as there is no penalty for doing so. [NOTE] ==== Avoiding score traps does not mean that your score function should be smart enough to avoid local optima. Leave it to the optimization algorithms to deal with the local optima. Avoiding score traps means to avoid, for each score constraint individually, a flatlined score function. ==== [IMPORTANT] ==== Always specify the degree of infeasibility. The business will often say ""if the solution is infeasible, it does not matter how infeasible it is."" While that is true for the business, it is not true for score calculation as it benefits from knowing how infeasible it is. In practice, soft constraints usually do this naturally and it is just a matter of doing it for the hard constraints too. ==== There are several ways to deal with a score trap: * Improve the score constraint to make a distinction in the score weight. For example, penalize `-1hard` for every missing CPU, instead of just `-1hard` if any CPU is missing. * If changing the score constraint is not allowed from the business perspective, add a lower score level with a score constraint that makes such a distinction. For example, penalize `-1subsoft` for every missing CPU, on top of `-1hard` if any CPU is missing. The business ignores the subsoft score level. * Add coarse-grained moves and union select them with the existing fine-grained moves. A coarse-grained move effectively does multiple moves to directly get out of a score trap with a single move. For example, move multiple items from the same container to another container. [[stepLimitBenchmark]] === `stepLimit` benchmark Not all score constraints have the same performance cost. Sometimes one score constraint can kill the score calculation performance outright. Use the xref:benchmarking-and-tweaking/benchmarking-and-tweaking.adoc#benchmarker[Benchmarker] to do a one minute run and check what happens to the score calculation speed if you comment out all but one of the score constraints. [[fairnessScoreConstraints]] === Fairness score constraints Some use cases have a business requirement to provide a fair schedule (usually as a soft score constraint), for example: * Fairly distribute the workload amongst the employees, to avoid envy. * Evenly distribute the workload amongst assets, to improve reliability. Implementing such a constraint can seem difficult (especially because there are different ways to formalize fairness), but usually the _squared workload_ implementation behaves most desirable. For each employee/asset, count the workload `w` and subtract `w²` from the score. image::score-calculation/fairnessScoreConstraint.png[align=""center""] As shown above, the _squared workload_ implementation guarantees that if you select two employees from a given solution and make their distribution between those two employees fairer, then the resulting new solution will have a better overall score. Do not just use the difference from the average workload, as that can lead to unfairness, as demonstrated below. image::score-calculation/fairnessScoreConstraintPitfall.png[align=""center""] [NOTE] ==== Instead of the _squared workload_, it is also possible to use the https://en.wikipedia.org/wiki/Variance[variance] (squared difference to the average) or the http://en.wikipedia.org/wiki/Standard_deviation[standard deviation] (square root of the variance). This has no effect on the score comparison, because the average will not change during planning. It is just more work to implement (because the average needs to be known) and trivially slower (because the calculation is a bit longer). ==== When the workload is perfectly balanced, the user often likes to see a `0` score, instead of the distracting `-34soft` in the image above (for the last solution which is almost perfectly balanced). To nullify this, either add the average multiplied by the number of entities to the score or instead show the variance or standard deviation in the UI. [[constraintConfiguration]] == Constraint configuration: adjust constraint weights dynamically Deciding the correct <> and <> for each constraint is not easy. It often involves negotiating with different stakeholders and their priorities. Furthermore, quantifying the impact of soft constraints is often a new experience for business managers, so they'll need a number of iterations to get it right. Don't get stuck between a rock and a hard place. Provide a UI to adjust the constraint weights and visualize the resulting solution, so the business managers can tweak the constraint weights themselves: image::score-calculation/parameterizeTheScoreWeights.png[align=""center""] [[createAConstraintConfiguration]] === Create a constraint configuration First, create a new class to hold the constraint weights and other constraint parameters. Annotate it with `@ConstraintConfiguration`: [source,java,options=""nowrap""] ---- @ConstraintConfiguration public class ConferenceConstraintConfiguration { ... } ---- There will be exactly one instance of this class per planning solution. The planning solution and the constraint configuration have a one-to-one relationship, but they serve a different purpose, so they aren't merged into a single class. A `@ConstraintConfiguration` class can extend a parent `@ConstraintConfiguration` class, which can be useful in international use cases with many regional constraints. Add the constraint configuration on the planning solution and annotate that field or property with `@ConstraintConfigurationProvider`: [source,java,options=""nowrap""] ---- @PlanningSolution public class ConferenceSolution { @ConstraintConfigurationProvider private ConferenceConstraintConfiguration constraintConfiguration; ... } ---- The `@ConstraintConfigurationProvider` annotation automatically exposes the constraint configuration as a xref:planner-configuration/planner-configuration.adoc#problemFacts[problem fact], there is no need to add a `@ProblemFactProperty` annotation. The constraint configuration class holds the <>, but it can also hold constraint parameters. For example in conference scheduling, the minimum pause constraint has a constraint weight (like any other constraint), but it also has a constraint parameter that defines the length of the minimum pause between two talks of the same speaker. That pause length depends on the conference (= the planning problem): in some big conferences 20 minutes isn't enough to go from one room to the other. That pause length is a field in the constraint configuration without a `@ConstraintWeight` annotation. [[constraintWeight]] === Add a constraint weight for each constraint In the constraint configuration class, add a `@ConstraintWeight` field or property for each constraint: [source,java,options=""nowrap""] ---- @ConstraintConfiguration(constraintPackage = ""...conferencescheduling.score"") public class ConferenceConstraintConfiguration { @ConstraintWeight(""Speaker conflict"") private HardMediumSoftScore speakerConflict = HardMediumSoftScore.ofHard(10); @ConstraintWeight(""Theme track conflict"") private HardMediumSoftScore themeTrackConflict = HardMediumSoftScore.ofSoft(10); @ConstraintWeight(""Content conflict"") private HardMediumSoftScore contentConflict = HardMediumSoftScore.ofSoft(100); ... } ---- The type of the constraint weights must be the same score class as xref:planner-configuration/planner-configuration.adoc#scoreOfASolution[the planning solution's score member]. For example in conference scheduling, `ConferenceSolution.getScore()` and `ConferenceConstraintConfiguration.getSpeakerConflict()` both return a `HardMediumSoftScore`. A constraint weight cannot be null. Give each constraint weight a default value, but expose them in a UI so the business users can tweak them. The example above uses the `ofHard()`, `ofMedium()` and `ofSoft()` methods to do that. Notice how it defaults the _content conflict_ constraint as ten times more important than the _theme track conflict_ constraint. Normally, a constraint weight only uses one score level, but it's possible to use multiple score levels (at a small performance cost). Each constraint has a constraint package and a constraint name, together they form the constraint id. These connect the constraint weight with the constraint implementation. *For each constraint weight, there must be a constraint implementation with the same package and the same name.* * The `@ConstraintConfiguration` annotation has a `constraintPackage` property that defaults to the package of the constraint configuration class. Most cases with xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation], need to override that because the DRLs use another package. For example, the DRL below uses the package `...conferencescheduling.score`, so the constraint configuration above specifies a `constraintPackage`. Cases with xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint streams], normally don't need to specify it. * The `@ConstraintWeight` annotation has a `value` which is the constraint name (for example ""Speaker conflict""). It inherits the constraint package from the `@ConstraintConfiguration`, but it can override that, for example `@ConstraintWeight(constraintPackage = ""...region.france"", ...)` to use a different constraint package than some of the other weights. So every constraint weight ends up with a constraint package and a constraint name. Each constraint weight links with a constraint implementation, for example in xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation]: [source,options=""nowrap""] ---- package ...conferencescheduling.solver; rule ""Speaker conflict"" when ... then scoreHolder.penalize(kcontext); end rule ""Theme track conflict"" when ... then scoreHolder.penalize(kcontext, ...); end rule ""Content conflict"" when ... then scoreHolder.penalize(kcontext, ...); end ---- Each of the constraint weights defines the score level and score weight of their constraint. The constraint implementation calls `reward()` or `penalize()` and the constraint weight is automatically applied. If the constraint implementation provides a match weight, that *match weight is multiplied with the constraint weight*. For example, the _content conflict_ constraint weight defaults to `100soft` and the constraint implementation penalizes each match based on the number of shared content tags: [source,java,options=""nowrap""] ---- @ConstraintWeight(""Content conflict"") private HardMediumSoftScore contentConflict = HardMediumSoftScore.ofSoft(100); ---- [source,options=""nowrap""] ---- rule ""Content conflict"" when $talk1 : Talk(...) $talk2 : Talk(...) then scoreHolder.penalize(kcontext, $talk2.overlappingContentCount($talk1)); end ---- So when 2 overlapping talks share only 1 content tag, the score is impacted by `-100soft`. But when 2 overlapping talks share 3 content tags, the match weight is `3`, so the score is impacted by `-300soft`. [[explainingTheScore]] == Explaining the score: which constraints are broken? The easiest way to explain the score during development is to print the return value of `explainScore()`, but only use that method for diagnostic purposes: [source,java,options=""nowrap""] ---- System.out.println(scoreManager.explainScore(solution)); ---- For example in conference scheduling, this prints that talk `S51` is responsible for breaking the hard constraint `Speaker required room tag`: ---- Explanation of score (-1hard/-806soft): Constraint match totals: -1hard: constraint (Speaker required room tag) has 1 matches: -1hard: justifications ([S51]) -340soft: constraint (Theme track conflict) has 32 matches: -20soft: justifications ([S68, S66]) -20soft: justifications ([S61, S44]) ... ... Indictments (top 5 of 72): -1hard/-22soft: justification (S51) has 12 matches: -1hard: constraint (Speaker required room tag) -10soft: constraint (Theme track conflict) ... ... ---- [IMPORTANT] ==== Do not attempt to parse this string or use it in your UI or exposed services. Instead use the ConstraintMatch API below and do it properly. ==== [[usingScoreCalculationOutsideTheSolver]] === Using score calculation outside the `Solver` If other parts of your application, for example your webUI, need to calculate the score of a solution, use the `ScoreManager` API: [source,java,options=""nowrap""] ---- ScoreManager scoreManager = ScoreManager.create(solverFactory); ScoreExplanation scoreExplanation = scoreManager.explain(cloudBalance); ---- Then use it when you need to calculate the `Score` of a solution: [source,java,options=""nowrap""] ---- HardSoftScore score = scoreExplanation.getScore(); ---- Furthermore, the `ScoreExplanation` can help explain the score through constraint match totals and/or indictments: image::score-calculation/scoreVisualization.png[align=""center""] [[constraintMatchTotal]] === Constraint match total: break down the score by constraint To break down the score per constraint, get the ``ConstraintMatchTotal``s from the ``ScoreExplanation``: [source,java,options=""nowrap""] ---- Collection> constraintMatchTotals = scoreExplanation.getConstraintMatchTotalMap().values(); for (ConstraintMatchTotal constraintMatchTotal : constraintMatchTotals) { String constraintName = constraintMatchTotal.getConstraintName(); // The score impact of that constraint HardSoftScore totalScore = constraintMatchTotal.getScore(); for (ConstraintMatch constraintMatch : constraintMatchTotal.getConstraintMatchSet()) { List justificationList = constraintMatch.getJustificationList(); HardSoftScore score = constraintMatch.getScore(); ... } } ---- Each `ConstraintMatchTotal` represents one constraint and has a part of the overall score. The sum of all the `ConstraintMatchTotal.getScore()` equals the overall score. [NOTE] ==== xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint streams] and xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation] supports constraint matches automatically, but <> requires <>. ==== [[indictmentHeatMap]] === Indictment heat map: visualize the hot planning entities To show a heat map in the UI that highlights the planning entities and problem facts have an impact on the ``Score``, get the `Indictment` map from the ``ScoreExplanation``: [source,java,options=""nowrap""] ---- Map> indictmentMap = scoreExplanation.getIndictmentMap(); for (CloudProcess process : cloudBalance.getProcessList()) { Indictment indictment = indictmentMap.get(process); if (indictment == null) { continue; } // The score impact of that planning entity HardSoftScore totalScore = indictment.getScore(); for (ConstraintMatch constraintMatch : indictment.getConstraintMatchSet()) { String constraintName = constraintMatch.getConstraintName(); HardSoftScore score = constraintMatch.getScore(); ... } } ---- Each `Indictment` is the sum of all constraints where that justification object is involved with. The sum of all the `Indictment.getScoreTotal()` differs from the overall score, because multiple ``Indictment``s can share the same `ConstraintMatch`. [NOTE] ==== xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint streams] and xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation] supports constraint matches automatically, but <> requires <>. ==== [[testingScoreConstraints]] == Testing score constraints It's recommended to write a unit test for each score constraint individually to check that it behaves correctly. Different score calculation types come with different tools for testing. For more, see xref:constraint-streams/constraint-streams.adoc#constraintStreamsTesting[testing Constraint Streams] or xref:drools-score-calculation/drools-score-calculation.adoc#testingDroolsConstraints[testing Drools constraints]. ",12270,False,2171.9442003326503,median "/* * Copyright (C) 2005 - 2013 MaNGOS * * Copyright (C) 2008 - 2013 Trinity * * Copyright (C) 2010 - 2013 ProjectSkyfire * * Copyright (C) 2011 - 2013 ArkCORE * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include ""gamePCH.h"" #include ""LootMgr.h"" #include ""Log.h"" #include ""ObjectMgr.h"" #include ""World.h"" #include ""Util.h"" #include ""SharedDefines.h"" #include ""SpellMgr.h"" #include ""Group.h"" static Rates const qualityToRate[MAX_ITEM_QUALITY] = { RATE_DROP_ITEM_POOR, // ITEM_QUALITY_POOR RATE_DROP_ITEM_NORMAL, // ITEM_QUALITY_NORMAL RATE_DROP_ITEM_UNCOMMON, // ITEM_QUALITY_UNCOMMON RATE_DROP_ITEM_RARE, // ITEM_QUALITY_RARE RATE_DROP_ITEM_EPIC, // ITEM_QUALITY_EPIC RATE_DROP_ITEM_LEGENDARY, // ITEM_QUALITY_LEGENDARY RATE_DROP_ITEM_ARTIFACT, // ITEM_QUALITY_ARTIFACT }; LootStore LootTemplates_Creature(""creature_loot_template"", ""creature entry"", true); LootStore LootTemplates_Disenchant(""disenchant_loot_template"", ""item disenchant id"", true); LootStore LootTemplates_Fishing(""fishing_loot_template"", ""area id"", true); LootStore LootTemplates_Gameobject(""gameobject_loot_template"", ""gameobject entry"", true); LootStore LootTemplates_Item(""item_loot_template"", ""item entry"", true); LootStore LootTemplates_Mail(""mail_loot_template"", ""mail template id"", false); LootStore LootTemplates_Milling(""milling_loot_template"", ""item entry (herb)"", true); LootStore LootTemplates_Pickpocketing(""pickpocketing_loot_template"", ""creature pickpocket lootid"", true); LootStore LootTemplates_Prospecting(""prospecting_loot_template"", ""item entry (ore)"", true); LootStore LootTemplates_Reference(""reference_loot_template"", ""reference id"", false); LootStore LootTemplates_Skinning(""skinning_loot_template"", ""creature skinning id"", true); LootStore LootTemplates_Spell(""spell_loot_template"", ""spell id (random item creating)"", false); class LootTemplate::LootGroup // A set of loot definitions for items (refs are not allowed) { public: void AddEntry (LootStoreItem& item); // Adds an entry to the group (at loading stage) bool HasQuestDrop () const; // True if group includes at least 1 quest drop entry bool HasQuestDropForPlayer (Player const * player) const; // The same for active quests of the player void Process (Loot& loot, uint16 lootMode) const; // Rolls an item from the group (if any) and adds the item to the loot float RawTotalChance () const; // Overall chance for the group (without equal chanced items) float TotalChance () const; // Overall chance for the group void Verify (LootStore const& lootstore, uint32 id, uint8 group_id) const; void CollectLootIds (LootIdSet& set) const; void CheckLootRefs (LootTemplateMap const& store, LootIdSet* ref_set) const; LootStoreItemList * GetExplicitlyChancedItemList () { return &ExplicitlyChanced; } LootStoreItemList * GetEqualChancedItemList () { return &EqualChanced; } void CopyConditions (ConditionList conditions); private: LootStoreItemList ExplicitlyChanced; // Entries with chances defined in DB LootStoreItemList EqualChanced; // Zero chances - every entry takes the same chance LootStoreItem const * Roll () const; // Rolls an item from the group, returns NULL if all miss their chances }; //Remove all data and free all memory void LootStore::Clear () { for (LootTemplateMap::const_iterator itr = m_LootTemplates.begin(); itr != m_LootTemplates.end(); ++itr) delete itr->second; m_LootTemplates.clear(); } // Checks validity of the loot store // Actual checks are done within LootTemplate::Verify() which is called for every template void LootStore::Verify () const { for (LootTemplateMap::const_iterator i = m_LootTemplates.begin(); i != m_LootTemplates.end(); ++i) i->second->Verify(*this, i->first); } // Loads a *_loot_template DB table into loot store // All checks of the loaded template are called from here, no error reports at loot generation required uint32 LootStore::LoadLootTable () { LootTemplateMap::const_iterator tab; // Clearing store (for reloading case) Clear(); // 0 1 2 3 4 5 6 QueryResult result = WorldDatabase.PQuery(""SELECT entry, item, ChanceOrQuestChance, lootmode, groupid, mincountOrRef, maxcount FROM %s"", GetName()); if (!result) { return 0; } uint32 count = 0; do { Field *fields = result->Fetch(); uint32 entry = fields[0].GetUInt32(); uint32 item = fields[1].GetUInt32(); float chanceOrQuestChance = fields[2].GetFloat(); uint16 lootmode = fields[3].GetUInt16(); uint8 group = fields[4].GetUInt8(); int32 mincountOrRef = fields[5].GetInt32(); int32 maxcount = fields[6].GetInt32(); if (maxcount > std::numeric_limits < uint8 > ::max()) { sLog->outErrorDb(""Table '%s' entry %d item %d: maxcount value (%u) to large. must be less %u - skipped"", GetName(), entry, item, maxcount, std::numeric_limits < uint8 > ::max()); continue; // error already printed to log/console. } LootStoreItem storeitem = LootStoreItem(item, chanceOrQuestChance, lootmode, group, mincountOrRef, maxcount); if (!storeitem.IsValid(*this, entry)) // Validity checks continue; // Looking for the template of the entry // often entries are put together if (m_LootTemplates.empty() || tab->first != entry) { // Searching the template (in case template Id changed) tab = m_LootTemplates.find(entry); if (tab == m_LootTemplates.end()) { std::pair pr = m_LootTemplates.insert(LootTemplateMap::value_type(entry, new LootTemplate)); tab = pr.first; } } // else is empty - template Id and iter are the same // finally iter refers to already existed or just created // Adds current row to the template tab->second->AddEntry(storeitem); ++count; } while (result->NextRow()); Verify(); // Checks validity of the loot store return count; } bool LootStore::HaveQuestLootFor (uint32 loot_id) const { LootTemplateMap::const_iterator itr = m_LootTemplates.find(loot_id); if (itr == m_LootTemplates.end()) return false; // scan loot for quest items return itr->second->HasQuestDrop(m_LootTemplates); } bool LootStore::HaveQuestLootForPlayer (uint32 loot_id, Player* player) const { LootTemplateMap::const_iterator tab = m_LootTemplates.find(loot_id); if (tab != m_LootTemplates.end()) if (tab->second->HasQuestDropForPlayer(m_LootTemplates, player)) return true; return false; } void LootStore::ResetConditions () { for (LootTemplateMap::iterator itr = m_LootTemplates.begin(); itr != m_LootTemplates.end(); ++itr) { ConditionList empty; (*itr).second->CopyConditions(empty); } } LootTemplate const* LootStore::GetLootFor (uint32 loot_id) const { LootTemplateMap::const_iterator tab = m_LootTemplates.find(loot_id); if (tab == m_LootTemplates.end()) return NULL; return tab->second; } LootTemplate* LootStore::GetLootForConditionFill (uint32 loot_id) { LootTemplateMap::iterator tab = m_LootTemplates.find(loot_id); if (tab == m_LootTemplates.end()) return NULL; return tab->second; } uint32 LootStore::LoadAndCollectLootIds (LootIdSet& ids_set) { uint32 count = LoadLootTable(); for (LootTemplateMap::const_iterator tab = m_LootTemplates.begin(); tab != m_LootTemplates.end(); ++tab) ids_set.insert(tab->first); return count; } void LootStore::CheckLootRefs (LootIdSet* ref_set) const { for (LootTemplateMap::const_iterator ltItr = m_LootTemplates.begin(); ltItr != m_LootTemplates.end(); ++ltItr) ltItr->second->CheckLootRefs(m_LootTemplates, ref_set); } void LootStore::ReportUnusedIds (LootIdSet const& ids_set) const { // all still listed ids isn't referenced for (LootIdSet::const_iterator itr = ids_set.begin(); itr != ids_set.end(); ++itr) sLog->outErrorDb(""Table '%s' entry %d isn't %s and not referenced from loot, and then useless."", GetName(), *itr, GetEntryName()); } void LootStore::ReportNotExistedId (uint32 id) const { sLog->outErrorDb(""Table '%s' entry %d (%s) not exist but used as loot id in DB."", GetName(), id, GetEntryName()); } // // --------- LootStoreItem --------- // // Checks if the entry (quest, non-quest, reference) takes it's chance (at loot generation) // RATE_DROP_ITEMS is no longer used for all types of entries bool LootStoreItem::Roll (bool rate) const { if (chance >= 100.0f) return true; if (mincountOrRef < 0) // reference case return roll_chance_f(chance * (rate ? sWorld->getRate(RATE_DROP_ITEM_REFERENCED) : 1.0f)); ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(itemid); float qualityModifier = pProto && rate ? sWorld->getRate(qualityToRate[pProto->Quality]) : 1.0f; return roll_chance_f(chance * qualityModifier); } // Checks correctness of values bool LootStoreItem::IsValid (LootStore const& store, uint32 entry) const { if (group >= 1 << 7) // it stored in 7 bit field { sLog->outErrorDb(""Table '%s' entry %d item %d: group (%u) must be less %u - skipped"", store.GetName(), entry, itemid, group, 1 << 7); return false; } if (mincountOrRef == 0) { sLog->outErrorDb(""Table '%s' entry %d item %d: wrong mincountOrRef (%d) - skipped"", store.GetName(), entry, itemid, mincountOrRef); return false; } if (mincountOrRef > 0) // item (quest or non-quest) entry, maybe grouped { ItemPrototype const *proto = ObjectMgr::GetItemPrototype(itemid); if (!proto) { sLog->outErrorDb(""Table '%s' entry %d item %d: item entry not listed in `item_template` - skipped"", store.GetName(), entry, itemid); return false; } if (chance == 0 && group == 0) // Zero chance is allowed for grouped entries only { sLog->outErrorDb(""Table '%s' entry %d item %d: equal-chanced grouped entry, but group not defined - skipped"", store.GetName(), entry, itemid); return false; } if (chance != 0 && chance < 0.000001f) // loot with low chance { sLog->outErrorDb(""Table '%s' entry %d item %d: low chance (%f) - skipped"", store.GetName(), entry, itemid, chance); return false; } if (maxcount < mincountOrRef) // wrong max count { sLog->outErrorDb(""Table '%s' entry %d item %d: max count (%u) less that min count (%i) - skipped"", store.GetName(), entry, itemid, int32(maxcount), mincountOrRef); return false; } } else // mincountOrRef < 0 { if (needs_quest) sLog->outErrorDb(""Table '%s' entry %d item %d: quest chance will be treated as non-quest chance"", store.GetName(), entry, itemid); else if (chance == 0) // no chance for the reference { sLog->outErrorDb(""Table '%s' entry %d item %d: zero chance is specified for a reference, skipped"", store.GetName(), entry, itemid); return false; } } return true; // Referenced template existence is checked at whole store level } // // --------- LootItem --------- // // Constructor, copies most fields from LootStoreItem and generates random count LootItem::LootItem (LootStoreItem const& li) { itemid = li.itemid; conditions = li.conditions; ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemid); freeforall = proto && (proto->Flags & ITEM_PROTO_FLAG_PARTY_LOOT); needs_quest = li.needs_quest; count = urand(li.mincountOrRef, li.maxcount); // constructor called for mincountOrRef > 0 only randomSuffix = GenerateEnchSuffixFactor(itemid); randomPropertyId = Item::GenerateItemRandomPropertyId(itemid); is_looted = 0; is_blocked = 0; is_underthreshold = 0; is_counted = 0; } // Basic checks for player/item compatibility - if false no chance to see the item in the loot bool LootItem::AllowedForPlayer (Player const * player) const { // DB conditions check if (!sConditionMgr->IsPlayerMeetToConditions(const_cast(player), conditions)) return false; ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(itemid); if (!pProto) return false; // not show loot for players without profession or those who already know the recipe if ((pProto->Flags & ITEM_PROTO_FLAG_SMART_LOOT) && (!player->HasSkill(pProto->RequiredSkill) || player->HasSpell(pProto->Spells[1].SpellId))) return false; // not show loot for not own team if ((pProto->Flags2 & ITEM_FLAGS_EXTRA_HORDE_ONLY) && player->GetTeam() != HORDE) return false; if ((pProto->Flags2 & ITEM_FLAGS_EXTRA_ALLIANCE_ONLY) && player->GetTeam() != ALLIANCE) return false; if (needs_quest) { // Checking quests for quest-only drop (check only quests requirements in this case) if (!player->HasQuestForItem(itemid)) return false; } else { // Not quest only drop (check quest starting items for already accepted non-repeatable quests) if (pProto->StartQuest && player->GetQuestStatus(pProto->StartQuest) != QUEST_STATUS_NONE && !player->HasQuestForItem(itemid)) return false; } return true; } void LootItem::AddAllowedLooter (const Player *player) { allowedGUIDs.insert(player->GetGUIDLow()); } // // --------- Loot --------- // // Inserts the item into the loot (called by LootTemplate processors) void Loot::AddItem (LootStoreItem const & item) { if (item.needs_quest) // Quest drop { if (quest_items.size() < MAX_NR_QUEST_ITEMS) quest_items.push_back(LootItem(item)); } else if (items.size() < MAX_NR_LOOT_ITEMS) // Non-quest drop { items.push_back(LootItem(item)); // non-conditional one-player only items are counted here, // free for all items are counted in FillFFALoot(), // non-ffa conditionals are counted in FillNonQuestNonFFAConditionalLoot() if (item.conditions.empty()) { ItemPrototype const* proto = ObjectMgr::GetItemPrototype(item.itemid); if (!proto || (proto->Flags & ITEM_PROTO_FLAG_PARTY_LOOT) == 0) ++unlootedCount; } } } // Calls processor of corresponding LootTemplate (which handles everything including references) bool Loot::FillLoot (uint32 lootId, LootStore const& store, Player* lootOwner, bool personal, bool noEmptyError, uint16 lootMode /*= LOOT_MODE_DEFAULT*/) { // Must be provided if (!lootOwner) return false; LootTemplate const* tab = store.GetLootFor(lootId); if (!tab) { if (!noEmptyError) sLog->outErrorDb(""Table '%s' loot id #%u used but it doesn't have records."", store.GetName(), lootId); return false; } items.reserve(MAX_NR_LOOT_ITEMS); quest_items.reserve(MAX_NR_QUEST_ITEMS); tab->Process(*this, store.IsRatesAllowed(), lootMode); // Processing is done there, callback via Loot::AddItem() // Setting access rights for group loot case Group * pGroup = lootOwner->GetGroup(); if (!personal && pGroup) { roundRobinPlayer = lootOwner->GetGUID(); for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) if (Player* pl = itr->getSource()) // should actually be looted object instead of lootOwner but looter has to be really close so doesnt really matter FillNotNormalLootFor(pl, pl->IsAtGroupRewardDistance(lootOwner)); for (uint8 i = 0; i < items.size(); ++i) { if (ItemPrototype const *proto = sItemStorage.LookupEntry(items[i].itemid)) if (proto->Quality < uint32(pGroup->GetLootThreshold())) items[i].is_underthreshold = true; } } // ... for personal loot else FillNotNormalLootFor(lootOwner, true); return true; } void Loot::FillNotNormalLootFor (Player* pl, bool withCurrency) { uint32 plguid = pl->GetGUIDLow(); QuestItemMap::const_iterator qmapitr = PlayerQuestItems.find(plguid); if (qmapitr == PlayerQuestItems.end()) FillQuestLoot(pl); qmapitr = PlayerFFAItems.find(plguid); if (qmapitr == PlayerFFAItems.end()) FillFFALoot(pl); qmapitr = PlayerNonQuestNonFFAConditionalItems.find(plguid); if (qmapitr == PlayerNonQuestNonFFAConditionalItems.end()) FillNonQuestNonFFAConditionalLoot(pl); // if not auto-processed player will have to come and pick it up manually if (!withCurrency) return; // Process currency items uint32 max_slot = GetMaxSlotInLootFor(pl); LootItem const *item = NULL; uint32 itemsSize = uint32(items.size()); for (uint32 i = 0; i < max_slot; ++i) { if (i < items.size()) item = &items[i]; else item = &quest_items[i - itemsSize]; if (!item->is_looted && item->freeforall && item->AllowedForPlayer(pl)) if (ItemPrototype const* proto = ObjectMgr::GetItemPrototype(item->itemid)) if (proto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS) pl->StoreLootItem(i, this); } } QuestItemList* Loot::FillFFALoot (Player* player) { QuestItemList *ql = new QuestItemList(); for (uint8 i = 0; i < items.size(); ++i) { LootItem &item = items[i]; if (!item.is_looted && item.freeforall && item.AllowedForPlayer(player)) { ql->push_back(QuestItem(i)); ++unlootedCount; } } if (ql->empty()) { delete ql; return NULL; } PlayerFFAItems[player->GetGUIDLow()] = ql; return ql; } QuestItemList* Loot::FillQuestLoot (Player* player) { if (items.size() == MAX_NR_LOOT_ITEMS) return NULL; QuestItemList *ql = new QuestItemList(); for (uint8 i = 0; i < quest_items.size(); ++i) { LootItem &item = quest_items[i]; if (!item.is_looted && item.AllowedForPlayer(player)) { ql->push_back(QuestItem(i)); // questitems get blocked when they first appear in a // player's quest vector // // increase once if one looter only, looter-times if free for all if (item.freeforall || !item.is_blocked) ++unlootedCount; item.is_blocked = true; if (items.size() + ql->size() == MAX_NR_LOOT_ITEMS) break; } } if (ql->empty()) { delete ql; return NULL; } PlayerQuestItems[player->GetGUIDLow()] = ql; return ql; } QuestItemList* Loot::FillNonQuestNonFFAConditionalLoot (Player* player) { QuestItemList *ql = new QuestItemList(); for (uint8 i = 0; i < items.size(); ++i) { LootItem &item = items[i]; if (!item.is_looted && !item.freeforall && item.AllowedForPlayer(player)) { item.AddAllowedLooter(player); if (!item.conditions.empty()) { ql->push_back(QuestItem(i)); if (!item.is_counted) { ++unlootedCount; item.is_counted = true; } } } } if (ql->empty()) { delete ql; return NULL; } PlayerNonQuestNonFFAConditionalItems[player->GetGUIDLow()] = ql; return ql; } //=================================================== void Loot::NotifyItemRemoved (uint8 lootIndex) { // notify all players that are looting this that the item was removed // convert the index to the slot the player sees std::set::iterator i_next; for (std::set::iterator i = PlayersLooting.begin(); i != PlayersLooting.end(); i = i_next) { i_next = i; ++i_next; if (Player* pl = ObjectAccessor::FindPlayer(*i)) pl->SendNotifyLootItemRemoved(lootIndex); else PlayersLooting.erase(i); } } void Loot::NotifyMoneyRemoved () { // notify all players that are looting this that the money was removed std::set::iterator i_next; for (std::set::iterator i = PlayersLooting.begin(); i != PlayersLooting.end(); i = i_next) { i_next = i; ++i_next; if (Player* pl = ObjectAccessor::FindPlayer(*i)) pl->SendNotifyLootMoneyRemoved(); else PlayersLooting.erase(i); } } void Loot::NotifyQuestItemRemoved (uint8 questIndex) { // when a free for all questitem is looted // all players will get notified of it being removed // (other questitems can be looted by each group member) // bit inefficient but isn't called often std::set::iterator i_next; for (std::set::iterator i = PlayersLooting.begin(); i != PlayersLooting.end(); i = i_next) { i_next = i; ++i_next; if (Player* pl = ObjectAccessor::FindPlayer(*i)) { QuestItemMap::const_iterator pq = PlayerQuestItems.find(pl->GetGUIDLow()); if (pq != PlayerQuestItems.end() && pq->second) { // find where/if the player has the given item in it's vector QuestItemList& pql = *pq->second; uint8 j; for (j = 0; j < pql.size(); ++j) if (pql[j].index == questIndex) break; if (j < pql.size()) pl->SendNotifyLootItemRemoved(items.size() + j); } } else PlayersLooting.erase(i); } } void Loot::generateMoneyLoot (uint32 minAmount, uint32 maxAmount) { if (maxAmount > 0) { if (maxAmount <= minAmount) gold = uint32(maxAmount * sWorld->getRate(RATE_DROP_MONEY)); else if ((maxAmount - minAmount) < 32700) gold = uint32(urand(minAmount, maxAmount) * sWorld->getRate(RATE_DROP_MONEY)); else gold = uint32(urand(minAmount >> 8, maxAmount >> 8) * sWorld->getRate(RATE_DROP_MONEY)) << 8; } } LootItem* Loot::LootItemInSlot (uint32 lootSlot, Player* player, QuestItem **qitem, QuestItem **ffaitem, QuestItem **conditem) { LootItem* item = NULL; bool is_looted = true; if (lootSlot >= items.size()) { uint32 questSlot = lootSlot - items.size(); QuestItemMap::const_iterator itr = PlayerQuestItems.find(player->GetGUIDLow()); if (itr != PlayerQuestItems.end() && questSlot < itr->second->size()) { QuestItem *qitem2 = &itr->second->at(questSlot); if (qitem) *qitem = qitem2; item = &quest_items[qitem2->index]; is_looted = qitem2->is_looted; } } else { item = &items[lootSlot]; is_looted = item->is_looted; if (item->freeforall) { QuestItemMap::const_iterator itr = PlayerFFAItems.find(player->GetGUIDLow()); if (itr != PlayerFFAItems.end()) { for (QuestItemList::const_iterator iter = itr->second->begin(); iter != itr->second->end(); ++iter) if (iter->index == lootSlot) { QuestItem *ffaitem2 = (QuestItem*) &(*iter); if (ffaitem) *ffaitem = ffaitem2; is_looted = ffaitem2->is_looted; break; } } } else if (!item->conditions.empty()) { QuestItemMap::const_iterator itr = PlayerNonQuestNonFFAConditionalItems.find(player->GetGUIDLow()); if (itr != PlayerNonQuestNonFFAConditionalItems.end()) { for (QuestItemList::const_iterator iter = itr->second->begin(); iter != itr->second->end(); ++iter) { if (iter->index == lootSlot) { QuestItem *conditem2 = (QuestItem*) &(*iter); if (conditem) *conditem = conditem2; is_looted = conditem2->is_looted; break; } } } } } // Player Bind to instance on loot if (player->HasPendingBind()) player->BindToInstance(); if (is_looted) return NULL; return item; } uint32 Loot::GetMaxSlotInLootFor (Player* player) const { QuestItemMap::const_iterator itr = PlayerQuestItems.find(player->GetGUIDLow()); return items.size() + (itr != PlayerQuestItems.end() ? itr->second->size() : 0); } // return true if there is any FFA, quest or conditional item for the player. bool Loot::hasItemFor (Player* player) const { QuestItemMap const& lootPlayerQuestItems = GetPlayerQuestItems(); QuestItemMap::const_iterator q_itr = lootPlayerQuestItems.find(player->GetGUIDLow()); if (q_itr != lootPlayerQuestItems.end()) { QuestItemList *q_list = q_itr->second; for (QuestItemList::const_iterator qi = q_list->begin(); qi != q_list->end(); ++qi) { const LootItem &item = quest_items[qi->index]; if (!qi->is_looted && !item.is_looted) return true; } } QuestItemMap const& lootPlayerFFAItems = GetPlayerFFAItems(); QuestItemMap::const_iterator ffa_itr = lootPlayerFFAItems.find(player->GetGUIDLow()); if (ffa_itr != lootPlayerFFAItems.end()) { QuestItemList *ffa_list = ffa_itr->second; for (QuestItemList::const_iterator fi = ffa_list->begin(); fi != ffa_list->end(); ++fi) { const LootItem &item = items[fi->index]; if (!fi->is_looted && !item.is_looted) return true; } } QuestItemMap const& lootPlayerNonQuestNonFFAConditionalItems = GetPlayerNonQuestNonFFAConditionalItems(); QuestItemMap::const_iterator nn_itr = lootPlayerNonQuestNonFFAConditionalItems.find(player->GetGUIDLow()); if (nn_itr != lootPlayerNonQuestNonFFAConditionalItems.end()) { QuestItemList *conditional_list = nn_itr->second; for (QuestItemList::const_iterator ci = conditional_list->begin(); ci != conditional_list->end(); ++ci) { const LootItem &item = items[ci->index]; if (!ci->is_looted && !item.is_looted) return true; } } return false; } // return true if there is any item over the group threshold (i.e. not underthreshold). bool Loot::hasOverThresholdItem () const { for (uint8 i = 0; i < items.size(); ++i) { if (!items[i].is_looted && !items[i].is_underthreshold && !items[i].freeforall) return true; } return false; } ByteBuffer& operator<< (ByteBuffer& b, LootItem const& li) { b << uint32(li.itemid); b << uint32(li.count); // nr of items of this type b << uint32(ObjectMgr::GetItemPrototype(li.itemid)->DisplayInfoID); b << uint32(li.randomSuffix); b << uint32(li.randomPropertyId); //b << uint8(0); // slot type - will send after this function call return b; } ByteBuffer& operator<< (ByteBuffer& b, LootView const& lv) { if (lv.permission == NONE_PERMISSION) { b << uint32(0); //gold b << uint8(0); // item count return b; // nothing output more } Loot &l = lv.loot; uint8 itemsShown = 0; //gold b << uint32(l.gold); size_t count_pos = b.wpos(); // pos of item count byte b << uint8(0); // item count placeholder b << uint8(0); // unk 4.0.x switch (lv.permission) { case GROUP_PERMISSION: { // if you are not the round-robin group looter, you can only see // blocked rolled items and quest items, and !ffa items for (uint8 i = 0; i < l.items.size(); ++i) { if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) { uint8 slot_type; if (l.items[i].is_blocked) slot_type = LOOT_SLOT_TYPE_ROLL_ONGOING; else if (l.roundRobinPlayer == 0 || !l.items[i].is_underthreshold || lv.viewer->GetGUID() == l.roundRobinPlayer) { // no round robin owner or he has released the loot // or it IS the round robin group owner // => item is lootable slot_type = LOOT_SLOT_TYPE_ALLOW_LOOT; } else // item shall not be displayed. continue; b << uint8(i) << l.items[i]; b << uint8(slot_type); ++itemsShown; } } break; } case ROUND_ROBIN_PERMISSION: { for (uint8 i = 0; i < l.items.size(); ++i) { if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) { if (l.roundRobinPlayer != 0 && lv.viewer->GetGUID() != l.roundRobinPlayer) // item shall not be displayed. continue; b << uint8(i) << l.items[i]; b << uint8(LOOT_SLOT_TYPE_ALLOW_LOOT); ++itemsShown; } } break; } case ALL_PERMISSION: case MASTER_PERMISSION: case OWNER_PERMISSION: { uint8 slot_type = LOOT_SLOT_TYPE_ALLOW_LOOT; switch (lv.permission) { case MASTER_PERMISSION: slot_type = LOOT_SLOT_TYPE_MASTER; break; case OWNER_PERMISSION: slot_type = LOOT_SLOT_TYPE_OWNER; break; default: break; } for (uint8 i = 0; i < l.items.size(); ++i) { if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) { b << uint8(i) << l.items[i]; b << uint8(slot_type); ++itemsShown; } } break; } default: return b; // nothing output more } LootSlotType slotType = lv.permission == OWNER_PERMISSION ? LOOT_SLOT_TYPE_OWNER : LOOT_SLOT_TYPE_ALLOW_LOOT; QuestItemMap const& lootPlayerQuestItems = l.GetPlayerQuestItems(); QuestItemMap::const_iterator q_itr = lootPlayerQuestItems.find(lv.viewer->GetGUIDLow()); if (q_itr != lootPlayerQuestItems.end()) { QuestItemList *q_list = q_itr->second; for (QuestItemList::const_iterator qi = q_list->begin(); qi != q_list->end(); ++qi) { LootItem &item = l.quest_items[qi->index]; if (!qi->is_looted && !item.is_looted) { b << uint8(l.items.size() + (qi - q_list->begin())); b << item; b << uint8(slotType); ++itemsShown; } } } QuestItemMap const& lootPlayerFFAItems = l.GetPlayerFFAItems(); QuestItemMap::const_iterator ffa_itr = lootPlayerFFAItems.find(lv.viewer->GetGUIDLow()); if (ffa_itr != lootPlayerFFAItems.end()) { QuestItemList *ffa_list = ffa_itr->second; for (QuestItemList::const_iterator fi = ffa_list->begin(); fi != ffa_list->end(); ++fi) { LootItem &item = l.items[fi->index]; if (!fi->is_looted && !item.is_looted) { b << uint8(fi->index); b << item; b << uint8(slotType); ++itemsShown; } } } QuestItemMap const& lootPlayerNonQuestNonFFAConditionalItems = l.GetPlayerNonQuestNonFFAConditionalItems(); QuestItemMap::const_iterator nn_itr = lootPlayerNonQuestNonFFAConditionalItems.find(lv.viewer->GetGUIDLow()); if (nn_itr != lootPlayerNonQuestNonFFAConditionalItems.end()) { QuestItemList *conditional_list = nn_itr->second; for (QuestItemList::const_iterator ci = conditional_list->begin(); ci != conditional_list->end(); ++ci) { LootItem &item = l.items[ci->index]; if (!ci->is_looted && !item.is_looted) { b << uint8(ci->index); b << item; b << uint8(slotType); ++itemsShown; } } } //update number of items shown b.put(count_pos, itemsShown); return b; } // // --------- LootTemplate::LootGroup --------- // // Adds an entry to the group (at loading stage) void LootTemplate::LootGroup::AddEntry (LootStoreItem& item) { if (item.chance != 0) ExplicitlyChanced.push_back(item); else EqualChanced.push_back(item); } // Rolls an item from the group, returns NULL if all miss their chances LootStoreItem const * LootTemplate::LootGroup::Roll () const { if (!ExplicitlyChanced.empty()) // First explicitly chanced entries are checked { float Roll = (float) rand_chance(); for (uint32 i = 0; i < ExplicitlyChanced.size(); ++i) // check each explicitly chanced entry in the template and modify its chance based on quality. { if (ExplicitlyChanced[i].chance >= 100.0f) return &ExplicitlyChanced[i]; Roll -= ExplicitlyChanced[i].chance; if (Roll < 0) return &ExplicitlyChanced[i]; } } if (!EqualChanced.empty()) // If nothing selected yet - an item is taken from equal-chanced part return &EqualChanced[irand(0, EqualChanced.size() - 1)]; return NULL; // Empty drop from the group } // True if group includes at least 1 quest drop entry bool LootTemplate::LootGroup::HasQuestDrop () const { for (LootStoreItemList::const_iterator i = ExplicitlyChanced.begin(); i != ExplicitlyChanced.end(); ++i) if (i->needs_quest) return true; for (LootStoreItemList::const_iterator i = EqualChanced.begin(); i != EqualChanced.end(); ++i) if (i->needs_quest) return true; return false; } // True if group includes at least 1 quest drop entry for active quests of the player bool LootTemplate::LootGroup::HasQuestDropForPlayer (Player const * player) const { for (LootStoreItemList::const_iterator i = ExplicitlyChanced.begin(); i != ExplicitlyChanced.end(); ++i) if (player->HasQuestForItem(i->itemid)) return true; for (LootStoreItemList::const_iterator i = EqualChanced.begin(); i != EqualChanced.end(); ++i) if (player->HasQuestForItem(i->itemid)) return true; return false; } void LootTemplate::LootGroup::CopyConditions (ConditionList /*conditions*/) { for (LootStoreItemList::iterator i = ExplicitlyChanced.begin(); i != ExplicitlyChanced.end(); ++i) { i->conditions.clear(); } for (LootStoreItemList::iterator i = EqualChanced.begin(); i != EqualChanced.end(); ++i) { i->conditions.clear(); } } // Rolls an item from the group (if any takes its chance) and adds the item to the loot void LootTemplate::LootGroup::Process (Loot& loot, uint16 lootMode) const { // build up list of possible drops LootStoreItemList EqualPossibleDrops = EqualChanced; LootStoreItemList ExplicitPossibleDrops = ExplicitlyChanced; uint8 uiAttemptCount = 0; const uint8 uiMaxAttempts = ExplicitlyChanced.size() + EqualChanced.size(); while (!ExplicitPossibleDrops.empty() || !EqualPossibleDrops.empty()) { if (uiAttemptCount == uiMaxAttempts) // already tried rolling too many times, just abort return; LootStoreItem *item = NULL; // begin rolling (normally called via Roll()) LootStoreItemList::iterator itr; uint8 itemSource = 0; if (!ExplicitPossibleDrops.empty()) // First explicitly chanced entries are checked { itemSource = 1; float Roll = (float) rand_chance(); // check each explicitly chanced entry in the template and modify its chance based on quality for (itr = ExplicitPossibleDrops.begin(); itr != ExplicitPossibleDrops.end(); itr = ExplicitPossibleDrops.erase(itr)) { if (itr->chance >= 100.0f) { item = &*itr; break; } Roll -= itr->chance; if (Roll < 0) { item = &*itr; break; } } } if (item == NULL && !EqualPossibleDrops.empty()) // If nothing selected yet - an item is taken from equal-chanced part { itemSource = 2; itr = EqualPossibleDrops.begin(); std::advance(itr, irand(0, EqualPossibleDrops.size() - 1)); item = &*itr; } // finish rolling ++uiAttemptCount; if (item != NULL && item->lootmode & lootMode) // only add this item if roll succeeds and the mode matches { bool duplicate = false; if (ItemPrototype const *_proto = sItemStorage.LookupEntry(item->itemid)) { uint8 _item_counter = 0; for (LootItemList::const_iterator _item = loot.items.begin(); _item != loot.items.end(); ++_item) if (_item->itemid == item->itemid) // search through the items that have already dropped { ++_item_counter; if (_proto->InventoryType == 0 && _item_counter == 3) // Non-equippable items are limited to 3 drops duplicate = true; else if (_proto->InventoryType != 0 && _item_counter == 1) // Equippable item are limited to 1 drop duplicate = true; } } if (duplicate) // if item->itemid is a duplicate, remove it switch (itemSource) { case 1: // item came from ExplicitPossibleDrops ExplicitPossibleDrops.erase(itr); break; case 2: // item came from EqualPossibleDrops EqualPossibleDrops.erase(itr); break; } else // otherwise, add the item and exit the function { loot.AddItem(*item); return; } } } } // Overall chance for the group without equal chanced items float LootTemplate::LootGroup::RawTotalChance () const { float result = 0; for (LootStoreItemList::const_iterator i = ExplicitlyChanced.begin(); i != ExplicitlyChanced.end(); ++i) if (!i->needs_quest) result += i->chance; return result; } // Overall chance for the group float LootTemplate::LootGroup::TotalChance () const { float result = RawTotalChance(); if (!EqualChanced.empty() && result < 100.0f) return 100.0f; return result; } void LootTemplate::LootGroup::Verify (LootStore const& lootstore, uint32 id, uint8 group_id) const { float chance = RawTotalChance(); if (chance > 101.0f) // TODO: replace with 100% when DBs will be ready { sLog->outErrorDb(""Table '%s' entry %u group %d has total chance > 100%% (%f)"", lootstore.GetName(), id, group_id, chance); } if (chance >= 100.0f && !EqualChanced.empty()) { sLog->outErrorDb(""Table '%s' entry %u group %d has items with chance=0%% but group total chance >= 100%% (%f)"", lootstore.GetName(), id, group_id, chance); } } void LootTemplate::LootGroup::CheckLootRefs (LootTemplateMap const& /*store*/, LootIdSet* ref_set) const { for (LootStoreItemList::const_iterator ieItr = ExplicitlyChanced.begin(); ieItr != ExplicitlyChanced.end(); ++ieItr) { if (ieItr->mincountOrRef < 0) { if (!LootTemplates_Reference.GetLootFor(-ieItr->mincountOrRef)) LootTemplates_Reference.ReportNotExistedId(-ieItr->mincountOrRef); else if (ref_set) ref_set->erase(-ieItr->mincountOrRef); } } for (LootStoreItemList::const_iterator ieItr = EqualChanced.begin(); ieItr != EqualChanced.end(); ++ieItr) { if (ieItr->mincountOrRef < 0) { if (!LootTemplates_Reference.GetLootFor(-ieItr->mincountOrRef)) LootTemplates_Reference.ReportNotExistedId(-ieItr->mincountOrRef); else if (ref_set) ref_set->erase(-ieItr->mincountOrRef); } } } // // --------- LootTemplate --------- // // Adds an entry to the group (at loading stage) void LootTemplate::AddEntry (LootStoreItem& item) { if (item.group > 0 && item.mincountOrRef > 0) // Group { if (item.group >= Groups.size()) Groups.resize(item.group); // Adds new group the the loot template if needed Groups[item.group - 1].AddEntry(item); // Adds new entry to the group } else // Non-grouped entries and references are stored together Entries.push_back(item); } void LootTemplate::CopyConditions (ConditionList conditions) { for (LootStoreItemList::iterator i = Entries.begin(); i != Entries.end(); ++i) i->conditions.clear(); for (LootGroups::iterator i = Groups.begin(); i != Groups.end(); ++i) i->CopyConditions(conditions); } // Rolls for every item in the template and adds the rolled items the the loot void LootTemplate::Process (Loot& loot, bool rate, uint16 lootMode, uint8 groupId) const { if (groupId) // Group reference uses own processing of the group { if (groupId > Groups.size()) return; // Error message already printed at loading stage Groups[groupId - 1].Process(loot, lootMode); return; } // Rolling non-grouped items for (LootStoreItemList::const_iterator i = Entries.begin(); i != Entries.end(); ++i) { if (i->lootmode & ~lootMode) // Do not add if mode mismatch continue; if (!i->Roll(rate)) continue; // Bad luck for the entry if (ItemPrototype const *_proto = sItemStorage.LookupEntry(i->itemid)) { uint8 _item_counter = 0; LootItemList::const_iterator _item = loot.items.begin(); for (; _item != loot.items.end(); ++_item) if (_item->itemid == i->itemid) // search through the items that have already dropped { ++_item_counter; if (_proto->InventoryType == 0 && _item_counter == 3) // Non-equippable items are limited to 3 drops continue; else if (_proto->InventoryType != 0 && _item_counter == 1) // Equippable item are limited to 1 drop continue; } if (_item != loot.items.end()) continue; } if (i->mincountOrRef < 0) // References processing { LootTemplate const* Referenced = LootTemplates_Reference.GetLootFor(-i->mincountOrRef); if (!Referenced) continue; // Error message already printed at loading stage uint32 maxcount = uint32(float(i->maxcount) * sWorld->getRate(RATE_DROP_ITEM_REFERENCED_AMOUNT)); for (uint32 loop = 0; loop < maxcount; ++loop) // Ref multiplicator Referenced->Process(loot, rate, lootMode, i->group); } else // Plain entries (not a reference, not grouped) loot.AddItem(*i); // Chance is already checked, just add } // Now processing groups for (LootGroups::const_iterator i = Groups.begin(); i != Groups.end(); ++i) i->Process(loot, lootMode); } // True if template includes at least 1 quest drop entry bool LootTemplate::HasQuestDrop (LootTemplateMap const& store, uint8 groupId) const { if (groupId) // Group reference { if (groupId > Groups.size()) return false; // Error message [should be] already printed at loading stage return Groups[groupId - 1].HasQuestDrop(); } for (LootStoreItemList::const_iterator i = Entries.begin(); i != Entries.end(); ++i) { if (i->mincountOrRef < 0) // References { LootTemplateMap::const_iterator Referenced = store.find(-i->mincountOrRef); if (Referenced == store.end()) continue; // Error message [should be] already printed at loading stage if (Referenced->second->HasQuestDrop(store, i->group)) return true; } else if (i->needs_quest) return true; // quest drop found } // Now processing groups for (LootGroups::const_iterator i = Groups.begin(); i != Groups.end(); ++i) if (i->HasQuestDrop()) return true; return false; } // True if template includes at least 1 quest drop for an active quest of the player bool LootTemplate::HasQuestDropForPlayer (LootTemplateMap const& store, Player const* player, uint8 groupId) const { if (groupId) // Group reference { if (groupId > Groups.size()) return false; // Error message already printed at loading stage return Groups[groupId - 1].HasQuestDropForPlayer(player); } // Checking non-grouped entries for (LootStoreItemList::const_iterator i = Entries.begin(); i != Entries.end(); ++i) { if (i->mincountOrRef < 0) // References processing { LootTemplateMap::const_iterator Referenced = store.find(-i->mincountOrRef); if (Referenced == store.end()) continue; // Error message already printed at loading stage if (Referenced->second->HasQuestDropForPlayer(store, player, i->group)) return true; } else if (player->HasQuestForItem(i->itemid)) return true; // active quest drop found } // Now checking groups for (LootGroups::const_iterator i = Groups.begin(); i != Groups.end(); ++i) if (i->HasQuestDropForPlayer(player)) return true; return false; } // Checks integrity of the template void LootTemplate::Verify (LootStore const& lootstore, uint32 id) const { // Checking group chances for (uint32 i = 0; i < Groups.size(); ++i) Groups[i].Verify(lootstore, id, i + 1); // TODO: References validity checks } void LootTemplate::CheckLootRefs (LootTemplateMap const& store, LootIdSet* ref_set) const { for (LootStoreItemList::const_iterator ieItr = Entries.begin(); ieItr != Entries.end(); ++ieItr) { if (ieItr->mincountOrRef < 0) { if (!LootTemplates_Reference.GetLootFor(-ieItr->mincountOrRef)) LootTemplates_Reference.ReportNotExistedId(-ieItr->mincountOrRef); else if (ref_set) ref_set->erase(-ieItr->mincountOrRef); } } for (LootGroups::const_iterator grItr = Groups.begin(); grItr != Groups.end(); ++grItr) grItr->CheckLootRefs(store, ref_set); } bool LootTemplate::addConditionItem (Condition* cond) { if (!cond || !cond->isLoaded()) //should never happen, checked at loading { sLog->outError(""LootTemplate::addConditionItem: condition is null""); return false; } if (!Entries.empty()) { for (LootStoreItemList::iterator i = Entries.begin(); i != Entries.end(); ++i) { if (i->itemid == cond->mSourceEntry) { i->conditions.push_back(cond); return true; } } } if (!Groups.empty()) { for (LootGroups::iterator groupItr = Groups.begin(); groupItr != Groups.end(); ++groupItr) { LootStoreItemList* itemList = (*groupItr).GetExplicitlyChancedItemList(); if (!itemList->empty()) { for (LootStoreItemList::iterator i = itemList->begin(); i != itemList->end(); ++i) { if ((*i).itemid == cond->mSourceEntry) { (*i).conditions.push_back(cond); return true; } } } itemList = (*groupItr).GetEqualChancedItemList(); if (!itemList->empty()) { for (LootStoreItemList::iterator i = itemList->begin(); i != itemList->end(); ++i) { if ((*i).itemid == cond->mSourceEntry) { (*i).conditions.push_back(cond); return true; } } } } } return false; } bool LootTemplate::isReference (uint32 id) { for (LootStoreItemList::const_iterator ieItr = Entries.begin(); ieItr != Entries.end(); ++ieItr) { if (ieItr->itemid == id && ieItr->mincountOrRef < 0) return true; } return false; //not found or not reference } void LoadLootTemplates_Creature () { sLog->outString(""Loading creature loot templates...""); uint32 oldMSTime = getMSTime(); LootIdSet ids_set, ids_setUsed; uint32 count = LootTemplates_Creature.LoadAndCollectLootIds(ids_set); // remove real entries and check existence loot for (uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i) { if (CreatureInfo const* cInfo = sCreatureStorage.LookupEntry(i)) { if (uint32 lootid = cInfo->lootid) { if (ids_set.find(lootid) == ids_set.end()) LootTemplates_Creature.ReportNotExistedId(lootid); else ids_setUsed.insert(lootid); } } } for (LootIdSet::const_iterator itr = ids_setUsed.begin(); itr != ids_setUsed.end(); ++itr) ids_set.erase(*itr); // output error for any still listed (not referenced from appropriate table) ids LootTemplates_Creature.ReportUnusedIds(ids_set); if (count) sLog->outString("">> Loaded %u creature loot templates in %u ms"", count, GetMSTimeDiffToNow(oldMSTime)); else sLog->outErrorDb("">> Loaded 0 creature loot templates. DB table `creature_loot_template` is empty""); sLog->outString(); } void LoadLootTemplates_Disenchant () { sLog->outString(""Loading disenchanting loot templates...""); uint32 oldMSTime = getMSTime(); LootIdSet ids_set, ids_setUsed; uint32 count = LootTemplates_Disenchant.LoadAndCollectLootIds(ids_set); // remove real entries and check existence loot for (uint32 i = 1; i < sItemStorage.MaxEntry; ++i) { if (ItemPrototype const *proto = sItemStorage.LookupEntry(i)) { if (uint32 lootid = proto->DisenchantID) { if (ids_set.find(lootid) == ids_set.end()) LootTemplates_Disenchant.ReportNotExistedId(lootid); else ids_setUsed.insert(lootid); } } } for (LootIdSet::const_iterator itr = ids_setUsed.begin(); itr != ids_setUsed.end(); ++itr) ids_set.erase(*itr); // output error for any still listed (not referenced from appropriate table) ids LootTemplates_Disenchant.ReportUnusedIds(ids_set); if (count) sLog->outString("">> Loaded %u disenchanting loot templates in %u ms"", count, GetMSTimeDiffToNow(oldMSTime)); else sLog->outErrorDb("">> Loaded 0 disenchanting loot templates. DB table `disenchant_loot_template` is empty""); sLog->outString(); } void LoadLootTemplates_Fishing () { sLog->outString(""Loading fishing loot templates...""); uint32 oldMSTime = getMSTime(); LootIdSet ids_set; uint32 count = LootTemplates_Fishing.LoadAndCollectLootIds(ids_set); // remove real entries and check existence loot for (uint32 i = 1; i < sAreaStore.GetNumRows(); ++i) if (AreaTableEntry const* areaEntry = sAreaStore.LookupEntry(i)) if (ids_set.find(areaEntry->ID) != ids_set.end()) ids_set.erase(areaEntry->ID); // output error for any still listed (not referenced from appropriate table) ids LootTemplates_Fishing.ReportUnusedIds(ids_set); if (count) sLog->outString("">> Loaded %u fishing loot templates in %u ms"", count, GetMSTimeDiffToNow(oldMSTime)); else sLog->outErrorDb("">> Loaded 0 fishing loot templates. DB table `fishing_loot_template` is empty""); sLog->outString(); } void LoadLootTemplates_Gameobject () { sLog->outString(""Loading gameobject loot templates...""); uint32 oldMSTime = getMSTime(); LootIdSet ids_set, ids_setUsed; uint32 count = LootTemplates_Gameobject.LoadAndCollectLootIds(ids_set); // remove real entries and check existence loot for (uint32 i = 1; i < sGOStorage.MaxEntry; ++i) { if (GameObjectInfo const* gInfo = sGOStorage.LookupEntry(i)) { if (uint32 lootid = gInfo->GetLootId()) { if (sObjectMgr->IsGoOfSpecificEntrySpawned(gInfo->id) && ids_set.find(lootid) == ids_set.end()) LootTemplates_Gameobject.ReportNotExistedId(lootid); else ids_setUsed.insert(lootid); } } } for (LootIdSet::const_iterator itr = ids_setUsed.begin(); itr != ids_setUsed.end(); ++itr) ids_set.erase(*itr); // output error for any still listed (not referenced from appropriate table) ids LootTemplates_Gameobject.ReportUnusedIds(ids_set); if (count) sLog->outString("">> Loaded %u gameobject loot templates in %u ms"", count, GetMSTimeDiffToNow(oldMSTime)); else sLog->outErrorDb("">> Loaded 0 gameobject loot templates. DB table `gameobject_loot_template` is empty""); sLog->outString(); } void LoadLootTemplates_Item () { sLog->outString(""Loading item loot templates...""); uint32 oldMSTime = getMSTime(); LootIdSet ids_set; uint32 count = LootTemplates_Item.LoadAndCollectLootIds(ids_set); // remove real entries and check existence loot for (uint32 i = 1; i < sItemStorage.MaxEntry; ++i) if (ItemPrototype const *proto = sItemStorage.LookupEntry(i)) if (ids_set.find(proto->ItemId) != ids_set.end() && proto->Flags & ITEM_PROTO_FLAG_OPENABLE) ids_set.erase(proto->ItemId); // output error for any still listed (not referenced from appropriate table) ids LootTemplates_Item.ReportUnusedIds(ids_set); if (count) sLog->outString("">> Loaded %u prospecting loot templates in %u ms"", count, GetMSTimeDiffToNow(oldMSTime)); else sLog->outErrorDb("">> Loaded 0 prospecting loot templates. DB table `item_loot_template` is empty""); sLog->outString(); } void LoadLootTemplates_Milling () { sLog->outString(""Loading milling loot templates...""); uint32 oldMSTime = getMSTime(); LootIdSet ids_set; uint32 count = LootTemplates_Milling.LoadAndCollectLootIds(ids_set); // remove real entries and check existence loot for (uint32 i = 1; i < sItemStorage.MaxEntry; ++i) { ItemPrototype const *proto = sItemStorage.LookupEntry(i); if (!proto) continue; if (!(proto->Flags & ITEM_PROTO_FLAG_MILLABLE)) continue; if (ids_set.find(proto->ItemId) != ids_set.end()) ids_set.erase(proto->ItemId); } // output error for any still listed (not referenced from appropriate table) ids LootTemplates_Milling.ReportUnusedIds(ids_set); if (count) sLog->outString("">> Loaded %u milling loot templates in %u ms"", count, GetMSTimeDiffToNow(oldMSTime)); else sLog->outErrorDb("">> Loaded 0 milling loot templates. DB table `milling_loot_template` is empty""); sLog->outString(); } void LoadLootTemplates_Pickpocketing () { sLog->outString(""Loading pickpocketing loot templates...""); uint32 oldMSTime = getMSTime(); LootIdSet ids_set, ids_setUsed; uint32 count = LootTemplates_Pickpocketing.LoadAndCollectLootIds(ids_set); // remove real entries and check existence loot for (uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i) { if (CreatureInfo const* cInfo = sCreatureStorage.LookupEntry(i)) { if (uint32 lootid = cInfo->pickpocketLootId) { if (ids_set.find(lootid) == ids_set.end()) LootTemplates_Pickpocketing.ReportNotExistedId(lootid); else ids_setUsed.insert(lootid); } } } for (LootIdSet::const_iterator itr = ids_setUsed.begin(); itr != ids_setUsed.end(); ++itr) ids_set.erase(*itr); // output error for any still listed (not referenced from appropriate table) ids LootTemplates_Pickpocketing.ReportUnusedIds(ids_set); if (count) sLog->outString("">> Loaded %u pickpocketing loot templates in %u ms"", count, GetMSTimeDiffToNow(oldMSTime)); else sLog->outErrorDb("">> Loaded 0 pickpocketing loot templates. DB table `pickpocketing_loot_template` is empty""); sLog->outString(); } void LoadLootTemplates_Prospecting () { sLog->outString(""Loading prospecting loot templates...""); uint32 oldMSTime = getMSTime(); LootIdSet ids_set; uint32 count = LootTemplates_Prospecting.LoadAndCollectLootIds(ids_set); // remove real entries and check existence loot for (uint32 i = 1; i < sItemStorage.MaxEntry; ++i) { ItemPrototype const *proto = sItemStorage.LookupEntry(i); if (!proto) continue; if (!(proto->Flags & ITEM_PROTO_FLAG_PROSPECTABLE)) continue; if (ids_set.find(proto->ItemId) != ids_set.end()) ids_set.erase(proto->ItemId); } // output error for any still listed (not referenced from appropriate table) ids LootTemplates_Prospecting.ReportUnusedIds(ids_set); if (count) sLog->outString("">> Loaded %u prospecting loot templates in %u ms"", count, GetMSTimeDiffToNow(oldMSTime)); else sLog->outErrorDb("">> Loaded 0 prospecting loot templates. DB table `prospecting_loot_template` is empty""); sLog->outString(); } void LoadLootTemplates_Mail () { sLog->outString(""Loading mail loot templates...""); uint32 oldMSTime = getMSTime(); LootIdSet ids_set; uint32 count = LootTemplates_Mail.LoadAndCollectLootIds(ids_set); // remove real entries and check existence loot for (uint32 i = 1; i < sMailTemplateStore.GetNumRows(); ++i) if (sMailTemplateStore.LookupEntry(i)) if (ids_set.find(i) != ids_set.end()) ids_set.erase(i); // output error for any still listed (not referenced from appropriate table) ids LootTemplates_Mail.ReportUnusedIds(ids_set); if (count) sLog->outString("">> Loaded %u mail loot templates in %u ms"", count, GetMSTimeDiffToNow(oldMSTime)); else sLog->outErrorDb("">> Loaded 0 mail loot templates. DB table `mail_loot_template` is empty""); sLog->outString(); } void LoadLootTemplates_Skinning () { sLog->outString(""Loading skinning loot templates...""); uint32 oldMSTime = getMSTime(); LootIdSet ids_set, ids_setUsed; uint32 count = LootTemplates_Skinning.LoadAndCollectLootIds(ids_set); // remove real entries and check existence loot for (uint32 i = 1; i < sCreatureStorage.MaxEntry; ++i) { if (CreatureInfo const* cInfo = sCreatureStorage.LookupEntry(i)) { if (uint32 lootid = cInfo->SkinLootId) { if (ids_set.find(lootid) == ids_set.end()) LootTemplates_Skinning.ReportNotExistedId(lootid); else ids_setUsed.insert(lootid); } } } for (LootIdSet::const_iterator itr = ids_setUsed.begin(); itr != ids_setUsed.end(); ++itr) ids_set.erase(*itr); // output error for any still listed (not referenced from appropriate table) ids LootTemplates_Skinning.ReportUnusedIds(ids_set); if (count) sLog->outString("">> Loaded %u skinning loot templates in %u ms"", count, GetMSTimeDiffToNow(oldMSTime)); else sLog->outErrorDb("">> Loaded 0 skinning loot templates. DB table `skinning_loot_template` is empty""); sLog->outString(); } void LoadLootTemplates_Spell () { sLog->outString(""Loading spell loot templates...""); uint32 oldMSTime = getMSTime(); LootIdSet ids_set; uint32 count = LootTemplates_Spell.LoadAndCollectLootIds(ids_set); // remove real entries and check existence loot for (uint32 spell_id = 1; spell_id < sSpellStore.GetNumRows(); ++spell_id) { SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell_id); if (!spellInfo) continue; // possible cases if (!IsLootCraftingSpell(spellInfo)) continue; if (ids_set.find(spell_id) == ids_set.end()) { // not report about not trainable spells (optionally supported by DB) // ignore 61756 (Northrend Inscription Research (FAST QA VERSION) for example if (!(spellInfo->Attributes & SPELL_ATTR0_NOT_SHAPESHIFT) || (spellInfo->Attributes & SPELL_ATTR0_TRADESPELL)) { LootTemplates_Spell.ReportNotExistedId(spell_id); } } else ids_set.erase(spell_id); } // output error for any still listed (not referenced from appropriate table) ids LootTemplates_Spell.ReportUnusedIds(ids_set); if (count) sLog->outString("">> Loaded %u spell loot templates in %u ms"", count, GetMSTimeDiffToNow(oldMSTime)); else sLog->outErrorDb("">> Loaded 0 spell loot templates. DB table `spell_loot_template` is empty""); sLog->outString(); } void LoadLootTemplates_Reference () { sLog->outString(""Loading reference loot templates...""); uint32 oldMSTime = getMSTime(); LootIdSet ids_set; LootTemplates_Reference.LoadAndCollectLootIds(ids_set); // check references and remove used LootTemplates_Creature.CheckLootRefs(&ids_set); LootTemplates_Fishing.CheckLootRefs(&ids_set); LootTemplates_Gameobject.CheckLootRefs(&ids_set); LootTemplates_Item.CheckLootRefs(&ids_set); LootTemplates_Milling.CheckLootRefs(&ids_set); LootTemplates_Pickpocketing.CheckLootRefs(&ids_set); LootTemplates_Skinning.CheckLootRefs(&ids_set); LootTemplates_Disenchant.CheckLootRefs(&ids_set); LootTemplates_Prospecting.CheckLootRefs(&ids_set); LootTemplates_Mail.CheckLootRefs(&ids_set); LootTemplates_Reference.CheckLootRefs(&ids_set); // output error for any still listed ids (not referenced from any loot table) LootTemplates_Reference.ReportUnusedIds(ids_set); sLog->outString("">> Loaded refence loot templates in %u ms"", GetMSTimeDiffToNow(oldMSTime)); sLog->outString(); } ",16193,True,3035.4762762763403,median "/* Chien 2D Mapa Copyright 2007-2010, Paulo Vinicius Wolski Radtke (pvwradtke@gmail.com) Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** Data Programador Alteração ===================================================== 13/08/2010 Paulo VW Radtke Funções para mudar uma camada do mapa e para pegar a camada de marcas. **/ #include #include #include #if defined(linux) #include #else #include #endif #include #include char cabecalhos[6][5] ={ ""FORM"", ""FMAP"", ""MPHD"", ""ANDT"", ""BODY"", ""LYR?""}; // indica se a Chien2D2 Mappy já foi inicializada. Por default, não foi ainda. bool m_inicializado = false; // O vetor com os mapas C2D2M_Mapa mapas[C2D2M_MAX_MAPAS]; // Indica se o sistema está em shutdown ou não bool m_shutdown = false; // Funções exclusivas para desenvolvimento interno. Não use no seu programa!! // Função para zerar os dados da Chien2D 2 void m_reset(); // Funções da C2D2 Mapa // Função para zerar os dados da Chien2D 2 // // Data: 29/03/2007 void m_reset() { // Zera os mapas for(int i=0;itamanho; if(SDL_BYTEORDER == SDL_LIL_ENDIAN) tamanho = SDL_Swap32(tamanho); // O tamanho total soma 8 tamanho+=8; // Índice dentro do buffer lido, já pulando o header de 12 bytes int indice=12; // Indica se o arquivo é armazenado em little endian (recupera do MPHD) bool arquivoLilEndian=false; // Indica se o sistema é lil endian (usado com a variável em arquivo) bool sistemaLilEndian = false; if(SDL_BYTEORDER == SDL_LIL_ENDIAN) sistemaLilEndian=true; // Processa os chunks do arquivo enquanto o índice estiver dentro do arquivo while(indice < tamanho) { // pega o próximo chunk CabecalhoBloco *bloco = (CabecalhoBloco *)&(buffer[indice]); // Faz o indice apontar para os dados do bloco (pula 8 bytes) indice += 8; // Pega o tamanho do bloco (está no formato intel) int tamBloco = bloco->tamanho; if(SDL_BYTEORDER == SDL_LIL_ENDIAN) tamBloco = SDL_Swap32(tamBloco); // Aqui extraímos as informações dos blocos. Nos interessam apenas // o header do arquivo (MPHD), o cenário (BODY), os layers (LYR""X"") // e as animações (ANDT) switch(C2D2M_TipoBloco(bloco)) { case CABECALHO_MPHD: { // Acessa o header MPHD *mphd = (MPHD *)&(buffer[indice]); // O arquivo é codificado em Little Endian? if(mphd->lsb) arquivoLilEndian=true; // Extra as informações relevantes mapas[idx].altura = mphd->mapheight; mapas[idx].largura = mphd->mapwidth; mapas[idx].dimensaoBlocoH = mphd->blockwidth; mapas[idx].dimensaoBlocoV = mphd->blockheight; // Se o sistema e arquivo não baterem if(arquivoLilEndian != sistemaLilEndian) { mapas[idx].altura = SDL_Swap16(mapas[idx].altura); mapas[idx].largura = SDL_Swap16(mapas[idx].largura); mapas[idx].dimensaoBlocoH = SDL_Swap16(mapas[idx].dimensaoBlocoH); mapas[idx].dimensaoBlocoV = SDL_Swap16(mapas[idx].dimensaoBlocoV); } // Calcula a largura do mapa em pixels mapas[idx].larguraPixel = mapas[idx].largura*mapas[idx].dimensaoBlocoH; mapas[idx].alturaPixel = mapas[idx].altura*mapas[idx].dimensaoBlocoV; break; } // Bloco dos dados da camada principal (0) case CABECALHO_BODY: { // Aloca a memória do layer principal mapas[idx].camadas[0] = (short int*)malloc(mapas[idx].altura*mapas[idx].largura*sizeof(short int)); // Copia os dados do buffer para a camada memcpy(mapas[idx].camadas[0], (short int*)&(buffer[indice]), mapas[idx].largura*mapas[idx].altura*sizeof(short int)); if(arquivoLilEndian != sistemaLilEndian) for(int i=0;itipo[3]-'0'; // Aloca a memória do layer principal mapas[idx].camadas[camada] = (short int*)malloc(mapas[idx].altura*mapas[idx].largura*sizeof(short int)); // Copia os dados do buffer para a camada memcpy(mapas[idx].camadas[camada], (short int*)&(buffer[indice]), mapas[idx].altura*mapas[idx].largura*sizeof(short int)); if(arquivoLilEndian != sistemaLilEndian) for(int i=0;i= C2D2M_MAX_MAPAS || id == 0) return; // Só apaga se o número de usuários for um ou se estiver em shutdown if(mapas[id-1].usuarios > 1 && !m_shutdown) { mapas[id-1].usuarios -= 1; return; } // Se cair aqui, é porquê não tem mais usuários mapas[id-1].usuarios = 0; // Tem uma surface SDL associada? if(mapas[id-1].idSpriteset != 0) { C2D2_RemoveSpriteSet(mapas[id-1].idSpriteset); mapas[id-1].idSpriteset = 0; } for(int i=0;i= C2D2M_MAX_MAPAS) return false; // Se não foi inicializado, falha! if(!mapas[idMapa-1].inicializado) return false; // Preenche os valores *largura = mapas[idMapa-1].larguraPixel; *altura = mapas[idMapa-1].alturaPixel; return true; } // Posiciona o mapa nas coordenadas x,y indicadas // // Data: 16/08/2006 void C2D2M_PosicionaMapa(unsigned int idMapa, int x, int y) { // O identificador é válido? if(idMapa >= C2D2M_MAX_MAPAS || idMapa == 0) return; // Se não foi inicializado, falha! if(!mapas[idMapa-1].inicializado) return; mapas[idMapa-1].x = x; mapas[idMapa-1].y = y; } // Recupera a posição do mapa // // Data: 16/08/2006 bool C2D2M_PosicaoXY(unsigned int idMapa, int *x, int *y) { // O identificador é válido? if(idMapa >= C2D2M_MAX_MAPAS || idMapa == 0) return false; // Se não foi inicializado, falha! if(!mapas[idMapa-1].inicializado) return false; *x = mapas[idMapa-1].x; *y = mapas[idMapa-1].y; return true; } // Função para dar velocidade a uma camada do mapa // // Data: 02/08/2007 void C2D2M_VelocidadeCamadaMapa(unsigned int idMapa, int camada, int velocidade) { // É um mapa válido? if(idMapa==0 || idMapa >= C2D2M_MAX_MAPAS) return; // É um índice válido? if(camada >= C2D2M_MAX_MAPAS || camada <0) return; // Se não foi inicializado, falha! if(!mapas[idMapa-1].inicializado) return; // A camada é válida? if(camada<0 || camada>=C2D2M_MAX_CAMADAS) return; mapas[idMapa-1].vCamadas[camada] = velocidade; } // Função para indicar a camada de marcas do mapa e o número do bloco inicial de marcas no cenário // // Data: 16/08/2007 // bool C2D2M_CamadaMarcas(unsigned int idMapa, int camada, int offbloco) { // É um mapa válido? if(idMapa==0 || idMapa >= C2D2M_MAX_MAPAS) return false; // É um índice válido? if(camada >= C2D2M_MAX_MAPAS) return false; // Enfim, marca a camada mapas[idMapa-1].camadaMarcas = camada; mapas[idMapa-1].offbloco = offbloco; // Reseta a busca de blocos, caso alguém use um dia a habilidade de mudar as camadas do mapa mapas[idMapa-1].buscaProximo = false; return true; } // Método para desenhar o mapa na tela a partir das coordenadas x,y do mapa // // Data: 26/01/2005 // Última atualização: 28/01/2005 // Função para desenhar uma camada do mapa na tela a partir das coordenadas do mapa (x,y na estrutura), dentro da janela especificada // por xtela,ytela e as dimensões largura e altura. // // Data: 28/01/2005 // Última atualização: 16/08/2007 void C2D2M_DesenhaCamadaMapa(unsigned int idMapa, int camada, int xtela, int ytela, int largura, int altura) { // É um índice válido? if(idMapa > C2D2M_MAX_MAPAS || idMapa ==0) return; if(!mapas[idMapa-1].inicializado) return; // TEsta se é um layer válido if(camada >= C2D2M_MAX_CAMADAS || camada <0) return; // Pega o ponteiro do mapa (mais rápido) C2D2M_Mapa *mapa = &mapas[idMapa-1]; // Testa se o layer existe if(mapa->camadas[camada] == 0) return; // Só desenha o mapa se o ponto âncora for dentro do mapa e o mapa couber na tela if(mapa->x<0 || mapa->y<0 || mapa->x>(mapa->larguraPixel-largura) || mapa->y>( mapa->alturaPixel - altura)) return; int xmapa, ymapa; // Calcula o ponto de acordo com a velocidade do mapa if(mapa->vCamadas[camada]) { xmapa=mapa->x/mapa->vCamadas[camada]; ymapa=mapa->y/mapa->vCamadas[camada]; } else { xmapa=0; ymapa=0; } // Pega a surface da tela /* SDL_Surface *tela = SDL_GetVideoSurface(); // Prepara o retângulo de cliping SDL_Rect rect; rect.x=xtela; rect.y=ytela; rect.w=largura; rect.h=altura; // Clipa! SDL_SetClipRect(tela, &rect);*/ //C2D2_LimitaAreaDesenho(xtela, ytela, largura, altura); // Determina as dimensões da tela em sprites (quanto vai desenhar) int larguraSprites = largura/mapa->dimensaoBlocoH; int alturaSprites = altura/mapa->dimensaoBlocoV; // Se as dimensões da janela não são múltiplos do tamanho do sprite, tem que desenhar um bloco a mais if(largura%mapa->dimensaoBlocoH) larguraSprites++; if(altura%mapa->dimensaoBlocoV) alturaSprites++; // Determina os blocos iniciais no mapa int blocoX = xmapa/mapa->dimensaoBlocoH; int blocoY = ymapa/mapa->dimensaoBlocoV; // DEtermina o offset em pixels DENTRO do sprite int offsetX = xmapa%mapa->dimensaoBlocoH; int offsetY = ymapa%mapa->dimensaoBlocoV; // Se tem offset, pode ser preciso desenhar um bloco a mais em cada direção // Para determinar se precisa ou não do offset, verificamos se o offset é maior que o resto da divisão pelo tamanho do bloco // Nota: não precisa verificar se vai ultrapassar o limite físico do mapa // porque o teste da posição no mapa acima já faz isso if(offsetX) larguraSprites++; if(offsetY) alturaSprites++; // O sprite a ser desenhado em cada posição int sprite; // Desenha o mapa for(int linha=0;linhacamadas[camada][mapa->largura*(linha+blocoY)+coluna+blocoX]; // Se o sprite for negativo, recupera o sprite na lista de animações if(sprite < 0) // Como o valor é negativo, tem que negar antes, // pegando na sequência de animação sprite = mapa->seqAnimacao[mapa->estrutAnimacao[-sprite].ancuroff]; // Não desenha o sprite 0 (transparente) if(sprite!=0) C2D2_DesenhaSprite(mapa->idSpriteset, sprite-1, xtela+coluna*mapa->dimensaoBlocoH-offsetX, ytela+linha*mapa->dimensaoBlocoV-offsetY); } // Retira o Clip //SDL_SetClipRect(tela, 0); //C2D2_LiberaAreaDesenho(); } // função para buscar as coordenadas da primeira ocorrência de um bloco de marca dentro de um mapa // // Data: 17/08/2007 bool C2D2M_PrimeiroBlocoMarca(unsigned int idMapa, int bloco, int *x, int *y) { // É um índice válido? if(idMapa >= C2D2M_MAX_MAPAS || idMapa ==0) return false; if(!mapas[idMapa-1].inicializado) return false; // Recupera o mapa C2D2M_Mapa *mapa = &mapas[idMapa-1]; // TEsta se op layer de marcas existe if(mapa->camadaMarcas == -1) return false; int pos; // Procura em cada posição até achar for(pos=0;poslargura*mapa->altura;pos++) { if(mapa->camadas[mapa->camadaMarcas][pos]==bloco+mapa->offbloco) break; } // Se achou, pos é menor que o número total de blocos na camada if(pos>=mapa->largura*mapa->altura) return false; // Se chegou aqui, achou o bloco!! // Calcula a posição *x = (pos % mapa->largura) * mapa->dimensaoBlocoH + mapa->dimensaoBlocoH/2; *y = (pos / mapa->largura) * mapa->dimensaoBlocoV + mapa->dimensaoBlocoV/2; // Guarda a informação para a chamada de C2D2M_ProximoBlocoMarca mapa->buscaProximo = true; mapa->posicaoUltimo = pos; mapa->blocoProcurado = bloco; // Retorna verdade return true; } // função para buscar as coordenadas da próxima ocorrência de um bloco de marca dentro de um mapa. Usar apenas APÓS C2D2M_PrimeiroBlocoMarca. // // Data: 23/08/2007 bool C2D2M_ProximoBlocoMarca(unsigned int idMapa, int *x, int *y) { // É um índice válido? if(idMapa >= C2D2M_MAX_MAPAS || idMapa ==0) return false; if(!mapas[idMapa-1].inicializado) return false; // Recupera o mapa C2D2M_Mapa *mapa = &mapas[idMapa-1]; // TEsta: está procurando uma seqüência de blocos?? if(!mapa->buscaProximo) return false; // Se chegou aqui, a camada de marcas existe e é válida. Busca int pos; // Procura em cada posição até achar for(pos=mapa->posicaoUltimo+1;poslargura*mapa->altura;pos++) { if(mapa->camadas[mapa->camadaMarcas][pos]==mapa->blocoProcurado+mapa->offbloco) break; } // Se achou, pos é menor que o número total de blocos na camada if(pos>=mapa->largura*mapa->altura) { // Indica que não está mais procurando o próximo mapa->buscaProximo = false; return false; } // Se chegou aqui, achou o bloco!! // Calcula a posição *x = (pos % mapa->largura) * mapa->dimensaoBlocoH + mapa->dimensaoBlocoH/2; *y = (pos / mapa->largura) * mapa->dimensaoBlocoV + mapa->dimensaoBlocoV/2; // Guarda a informação para a próxima chamada de C2D2M_ProximoBlocoMarca mapa->posicaoUltimo = pos; // Retorna verdade return true; } // Função que indica a aceleração de gravidade do mapa, em pixels por segundo, e a velocidade máxima de gravidade para simular atrito bool C2D2M_GravidadeMapa(unsigned int idMapa, double gravidade, double maxgravidade) { // É um índice válido? if(idMapa >= C2D2M_MAX_MAPAS || idMapa ==0) return false; if(!mapas[idMapa-1].inicializado) return false; // Recupera o mapa C2D2M_Mapa *mapa = &mapas[idMapa-1]; // Muda a gravidade mapa->gravidade = gravidade; mapa->maxgravidade = maxgravidade; return true; } // Anima os blocos animados do mapa. Atualiza os quadros, reseta e etc e tal // // Data: 27/01/2005 // Última atualização: 02/08/2007 void C2D2M_AnimaMapa(unsigned int id) { if(id > C2D2M_MAX_MAPAS) return; // Pega o ponteiro do mapa C2D2M_Mapa *mapa = &mapas[id-1]; // Testa se pode fazer a operação if(!mapa->inicializado) return; // Procura as animações (0 não existe, lembrando) int indice = 1; while(mapa->estrutAnimacao[indice].antype != AN_END) { // Verifica se não é uma animação (só Deus sabe porque isso existe) // Se verdade, pula (acredite, isso faz tanto sentido pra mim como // pra você, afinal, não é pra ser ANIMADO?!? if(mapa->estrutAnimacao[indice].antype == AN_NONE) continue; // Se a animação zera, tem que atualizar if((mapa->estrutAnimacao[indice].ancount-=1) == 0) { // Armazena o delay novo mapa->estrutAnimacao[indice].ancount = mapa->estrutAnimacao[indice].andelay; // Atualiza o frame e, se estourou, volta para o início de acordo // com o tipo da animação switch(mapa->estrutAnimacao[indice].antype) { // Loop pra frente case AN_LOOPF: { if((mapa->estrutAnimacao[indice].ancuroff+=1) == mapa->estrutAnimacao[indice].anendoff) mapa->estrutAnimacao[indice].ancuroff = mapa->estrutAnimacao[indice].anstartoff; break; } // Loop reverso case AN_LOOPR: { if((mapa->estrutAnimacao[indice].ancuroff-=1) < mapa->estrutAnimacao[indice].anstartoff) mapa->estrutAnimacao[indice].ancuroff = mapa->estrutAnimacao[indice].anendoff-1; break; } // Anima uma única vez (não muit oútil se não for na primeira tela) case AN_ONCE: { if(mapa->estrutAnimacao[indice].anuser) break; // Testa se chegou no final if((mapa->estrutAnimacao[indice].ancuroff+=1) == mapa->estrutAnimacao[indice].anendoff-1) mapa->estrutAnimacao[indice].anuser = true; break; } // Animação ping-pong pra frente case AN_PPFF: { // Se verdade, vai de marcha-ré if(mapa->estrutAnimacao[indice].anuser==0) { if((mapa->estrutAnimacao[indice].ancuroff-=1) < mapa->estrutAnimacao[indice].anstartoff) { mapa->estrutAnimacao[indice].ancuroff = mapa->estrutAnimacao[indice].anstartoff+1; mapa->estrutAnimacao[indice].anuser = 1; } } else { if((mapa->estrutAnimacao[indice].ancuroff+=1) == mapa->estrutAnimacao[indice].anendoff) { mapa->estrutAnimacao[indice].ancuroff = mapa->estrutAnimacao[indice].anendoff-2; mapa->estrutAnimacao[indice].anuser = 0; } } break; } // Animação ping-pong pra trás case AN_PPRR: { // Se verdade, vai pra frente if(mapa->estrutAnimacao[indice].anuser==0) { if((mapa->estrutAnimacao[indice].ancuroff+=1) == mapa->estrutAnimacao[indice].anendoff) { mapa->estrutAnimacao[indice].ancuroff = mapa->estrutAnimacao[indice].anendoff-2; mapa->estrutAnimacao[indice].anuser = 1; } } else { if((mapa->estrutAnimacao[indice].ancuroff-=1) < mapa->estrutAnimacao[indice].anstartoff) { mapa->estrutAnimacao[indice].ancuroff = mapa->estrutAnimacao[indice].anstartoff+1; mapa->estrutAnimacao[indice].anuser = 0; } } break; } default: break; } } // Próxima animação indice++; } } // Ajusta o deslocamento de um boundingbox no mapa. Recebe o mapa aonde o deslocamento // se realiza, a posição do bounding box e o quanto deve mover no eixo x e y. O booleano // gravidade indica se há gravidade, situação na qual deslocamentos verticais para baixo // e cima não implicam em deslocamento no eixo x. // // Os parâmetros são o identificador do mapa (idMapa), as coordenadas do bounding box // (x,y), as dimensões do bounding box (largura), os ponteiros para o deslocamento // (dx e dy) e se a gravidade está em ação. // // Data: XX/XX/2007 // Última atualização: 28/08/2008 // void C2D2M_AjustaDeslocamento(unsigned int idMapa, int xorig, int yorig, int larg, int alt, int *dx, int *dy, bool gravidade) { if(idMapa == 0 || idMapa>=C2D2M_MAX_MAPAS) return; // SE o mapa não foi inicializado, ou se a camada de marcas está na default (-1) if(!mapas[idMapa-1].inicializado || mapas[idMapa-1].camadaMarcas==-1) return; // REcupera o valor de x e y originais int x=xorig,y=yorig; // Recupera o mapa C2D2M_Mapa *mapa = &mapas[idMapa-1]; // Bounding box int topo, baixo, esquerda, direita; // A referência do ator para inclinações, o quanto entra no bloco e a diferença de pontos int meio, entrou, dif; // Qual a maior distância percorrida (mais tarde, passa para o personagem) int maior; // Qual o bloco int bloco; if(abs(*dx) > abs(*dy)) maior = abs(*dx); else maior = abs(*dy); // O deslocamento no eixo a cada passo (mais tarde, passa para o personagem) int dxl=0, dyl=0; if(*dx>0) dxl=1; else if(*dx < 0) dxl=-1; if(*dy>0) dyl=1; else if(*dy < 0) dyl=-1; // As variáveis para indicar se deve deslocar ou não int xant=0, yant=0; // Percorre os pixels no maior eixo for(int i = 1; i <= maior ; i++) { // Aplica o deslocamento no eixo x? if(dxl !=0 && (i * *dx)/maior != xant) { xant = (i * *dx)/maior; // Desloca x += dxl; // Calcula o bounding box topo = (y)/mapa->dimensaoBlocoV; baixo = (y+alt-1)/mapa->dimensaoBlocoV; esquerda = (x)/mapa->dimensaoBlocoH; direita = (x+larg-1)/mapa->dimensaoBlocoH; // Calcula o bloco em que se encontra o meio meio = (x+larg/2)/mapa->dimensaoBlocoH; // Testa a colisão com blocos inclinados if(meio >=0 && meio <= mapa->largura && mapa->dimensaoBlocoH == mapa->dimensaoBlocoV) { // ajusta pela parte de baixo if(baixo >= 0 && baixo<= mapa->altura) { bloco =mapa->camadas[mapa->camadaMarcas][mapa->largura*baixo+meio]-mapa->offbloco; switch(bloco) { case C2D2M_SOLIDO45: case C2D2M_SOLIDO135: entrou=x+larg/2 - meio*mapa->dimensaoBlocoH; if(bloco == C2D2M_SOLIDO45) entrou++; else entrou = mapa->dimensaoBlocoH-entrou; dif = (baixo+1)*mapa->dimensaoBlocoV-1-(y+alt); // Aqui colide e ajusta if(dif < entrou) y -= entrou-dif; //ATOR_InsereEvento(a, EVT_COLIDIU_PAREDE_BAIXO); // Não verifica a colisão na horizontal nesta linha baixo--; break; case C2D2M_SOLIDO22A: case C2D2M_SOLIDO157B: entrou=x+larg/2 - meio*mapa->dimensaoBlocoH; if(bloco == C2D2M_SOLIDO22A) entrou++; else entrou = mapa->dimensaoBlocoH-entrou; dif = (baixo+1)*mapa->dimensaoBlocoV-1-(y+alt); // Aqui colide e ajusta if(dif < entrou/2) y -= entrou/2-dif; // Não verifica a colisão na horizontal nesta linha baixo--; break; case C2D2M_SOLIDO22B: case C2D2M_SOLIDO157A: entrou=x+larg/2 - meio*mapa->dimensaoBlocoH; if(bloco == C2D2M_SOLIDO22B) entrou++; else entrou = mapa->dimensaoBlocoH-entrou; dif = (baixo+1)*mapa->dimensaoBlocoV-1-(y+alt); // Aqui colide e ajusta if(dif < (entrou+mapa->dimensaoBlocoV)/2) { y -= (entrou+mapa->dimensaoBlocoV)/2-dif; //ATOR_InsereEvento(a, EVT_COLIDIU_PAREDE_BAIXO); } // Não verifica a colisão na horizontal nesta linha baixo--; break; } } // ajusta pela parte de cima if(topo >= 0 && topo<= mapa->altura) { bloco =mapa->camadas[mapa->camadaMarcas][mapa->largura*topo+meio]-mapa->offbloco; switch(bloco) { case C2D2M_SOLIDO225: case C2D2M_SOLIDO315: entrou=x+larg/2 - meio*mapa->dimensaoBlocoH; if(bloco == C2D2M_SOLIDO315) entrou++; else entrou = mapa->dimensaoBlocoH-entrou; dif = y - (topo)*mapa->dimensaoBlocoV; // Aqui colide e ajusta if(dif < entrou) y += entrou-dif; // Não verifica a colisão na horizontal nesta linha topo++; break; case C2D2M_SOLIDO202B: case C2D2M_SOLIDO337A: entrou=x+larg/2 - meio*mapa->dimensaoBlocoH; if(bloco == C2D2M_SOLIDO337A) entrou++; else entrou = mapa->dimensaoBlocoH-entrou; dif = y - topo*mapa->dimensaoBlocoV; // Aqui colide e ajusta if(dif < entrou/2) { y += entrou/2-dif; //ATOR_InsereEvento(a, EVT_COLIDIU_PAREDE_CIMA); } // Não verifica a colisão na horizontal nesta linha topo++; break; case C2D2M_SOLIDO202A: case C2D2M_SOLIDO337B: entrou=x+larg/2 - meio*mapa->dimensaoBlocoH; if(bloco == C2D2M_SOLIDO337B) entrou++; else entrou = mapa->dimensaoBlocoH-entrou; dif = y - topo*mapa->dimensaoBlocoV; // Aqui colide e ajusta if(dif < (entrou+mapa->dimensaoBlocoV)/2) { y += (entrou+mapa->dimensaoBlocoV)/2-dif; //ATOR_InsereEvento(a, EVT_COLIDIU_PAREDE_CIMA); } // Não verifica a colisão na horizontal nesta linha topo++; break; } } } // Testa a colisão com blocos completamente sólidos for(int lin=topo;lin<=baixo;lin++) { // Testa se está dentro das coordenadas válidas if(lin < 0 || lin >= mapa->altura) continue; // Testa se ainda está dentro do mapa à esquerda if(esquerda >= 0 && esquerda <= mapa->largura && dxl<0) // Testa se colidiu if(mapa->camadas[mapa->camadaMarcas][mapa->largura*lin+esquerda] == mapa->offbloco + C2D2M_SOLIDO) { // Se colidiu, aumenta um ponto e encerra x++; break; } // Testa se ainda está dentro do mapa à direita if(direita >= 0 && direita <= mapa->largura && dxl>0) // Testa se colidiu if(mapa->camadas[mapa->camadaMarcas][mapa->largura*lin+direita] == mapa->offbloco + C2D2M_SOLIDO) { // Se colidiu, diminui um ponto e encerra x--; break; } } } // Teste de ajuste na vertical para quando não há gravidade if(dyl !=0 && (i * *dy)/maior != yant && !gravidade) { yant = (i * *dy)/maior; // Desloca y += dyl; // Calcula o bounding box topo = (y)/mapa->dimensaoBlocoV; baixo = (y+alt-1)/mapa->dimensaoBlocoV; esquerda = (x)/mapa->dimensaoBlocoH; direita = (x+larg-1)/mapa->dimensaoBlocoH; // Calcula o bloco em que se encontra o meio. Agora, o meio é na horizontal! meio = (y+alt/2)/mapa->dimensaoBlocoV; // Testa a colisão com blocos inclinados if(meio >=0 && meio <= mapa->altura && mapa->dimensaoBlocoH == mapa->dimensaoBlocoV) { // ajusta pela parte da esquerda if(esquerda >= 0 && esquerda<= mapa->largura) { bloco =mapa->camadas[mapa->camadaMarcas][mapa->largura*meio+esquerda]-mapa->offbloco; switch(bloco) { case C2D2M_SOLIDO135: case C2D2M_SOLIDO225: entrou=y+alt/2 - meio*mapa->dimensaoBlocoV; if(bloco == C2D2M_SOLIDO135) entrou++; else entrou = mapa->dimensaoBlocoV-entrou; dif = x-esquerda*mapa->dimensaoBlocoH; // Aqui colide e ajusta if(dif < entrou) x += entrou-dif; // Encerra a verificação esquerda++; break; case C2D2M_SOLIDO157A: case C2D2M_SOLIDO202A: entrou=y+alt/2 - meio*mapa->dimensaoBlocoV; if(bloco == C2D2M_SOLIDO157A) entrou++; else entrou = mapa->dimensaoBlocoV-entrou; dif = x-esquerda*mapa->dimensaoBlocoH; // Aqui colide e ajusta if(dif < entrou*2) { x += entrou*2-dif; } // Encerra a verificação esquerda++; break; case C2D2M_SOLIDO157B: case C2D2M_SOLIDO202B: entrou=y+alt/2 - meio*mapa->dimensaoBlocoV; if(bloco == C2D2M_SOLIDO157B) entrou++; else entrou = mapa->dimensaoBlocoV-entrou; dif = x-esquerda*mapa->dimensaoBlocoH; // Aqui colide e ajusta if(dif < entrou*2 - mapa->dimensaoBlocoV) { x += entrou*2 - mapa->dimensaoBlocoV-dif; } // Encerra a verificação esquerda++; break; } } // ajusta pela parte da direita if(direita >= 0 && direita<= mapa->largura) { bloco =mapa->camadas[mapa->camadaMarcas][mapa->largura*meio+direita]-mapa->offbloco; switch(bloco) { case C2D2M_SOLIDO45: case C2D2M_SOLIDO315: entrou=y +alt/2- meio*mapa->dimensaoBlocoV; if(bloco == C2D2M_SOLIDO45) entrou++; else entrou = mapa->dimensaoBlocoV-entrou; dif = (direita+1)*mapa->dimensaoBlocoH-1-(x+larg); // Aqui colide e ajusta if(dif < entrou) x -= entrou-dif; // Encerra a verificação direita--; break; case C2D2M_SOLIDO22B: case C2D2M_SOLIDO337B: entrou=y +alt/2- meio*mapa->dimensaoBlocoV; if(bloco == C2D2M_SOLIDO22B) entrou++; else entrou = mapa->dimensaoBlocoV-entrou; dif = (direita+1)*mapa->dimensaoBlocoH-1-(x+larg); // Aqui colide e ajusta if(dif < entrou*2) { x -= entrou*2-dif; //ATOR_InsereEvento(a, EVT_COLIDIU_PAREDE_BAIXO); } // Encerra a verificação direita--; break; case C2D2M_SOLIDO22A: case C2D2M_SOLIDO337A: entrou=y +alt/2- meio*mapa->dimensaoBlocoV; if(bloco == C2D2M_SOLIDO22A) entrou++; else entrou = mapa->dimensaoBlocoV-entrou; dif = (direita+1)*mapa->dimensaoBlocoH-1-(x+larg); // Aqui colide e ajusta if(dif < entrou*2-mapa->dimensaoBlocoV) { //ATOR_InsereEvento(a, EVT_COLIDIU_PAREDE_BAIXO); x -= entrou*2-mapa->dimensaoBlocoV-dif; } // Encerra a verificação direita--; break; } } } // Testa a colisão com bloco completamente sólido na vertical for(int col=esquerda;col<=direita;col++) { // Testa se está dentro das coordenadas válidas if(col < 0 || col >= mapa->largura) continue; // Testa se ainda está dentro do mapa acima if(topo >= 0 && topo <= mapa->altura && dyl<0) // Testa se colidiu if(mapa->camadas[mapa->camadaMarcas][mapa->largura*topo+col] == mapa->offbloco + C2D2M_SOLIDO) { // Se colidiu, aumenta um ponto e encerra y++; //dxl; //ATOR_InsereEvento(a, EVT_COLIDIU_PAREDE_CIMA); break; } // Testa se ainda está dentro do mapa abaixo if(baixo >= 0 && baixo <= mapa->altura && dyl>0) // Testa se colidiu if(mapa->camadas[mapa->camadaMarcas][mapa->largura*baixo+col] == mapa->offbloco + C2D2M_SOLIDO) { // Se colidiu, diminui um ponto e encerra y--; //dxl; //ATOR_InsereEvento(a, EVT_COLIDIU_PAREDE_BAIXO); break; } } } // Teste de ajuste na vertical para quando há gravidade e velocidade no y if(dyl != 0 && (i * *dy)/maior != yant && gravidade) { yant = (i * *dy)/maior; // Desloca y += dyl; // Calcula o bounding box topo = (y)/mapa->dimensaoBlocoV; baixo = (y+alt-1)/mapa->dimensaoBlocoV; esquerda = (x)/mapa->dimensaoBlocoH; direita = (x+larg-1)/mapa->dimensaoBlocoH; // Calcula o bloco em que se encontra o meio. Agora, o meio é na horizontal! meio = (x+larg/2)/mapa->dimensaoBlocoH; // Testa a colisão com blocos inclinados if(meio >=0 && meio <= mapa->largura && mapa->dimensaoBlocoH == mapa->dimensaoBlocoV) { // ajusta pela parte de baixo if(baixo >= 0 && baixo<= mapa->altura) { bloco =mapa->camadas[mapa->camadaMarcas][mapa->largura*baixo+meio]-mapa->offbloco; switch(bloco) { case C2D2M_SOLIDO45: case C2D2M_SOLIDO135: entrou=x+larg/2 - meio*mapa->dimensaoBlocoH; if(bloco == C2D2M_SOLIDO45) entrou++; else entrou = mapa->dimensaoBlocoH-entrou; dif = (baixo+1)*mapa->dimensaoBlocoV-1-(y+alt); // Aqui colide e ajusta if(dif < entrou) y -= 1;//entrou-dif; // Não verifica a colisão na horizontal nesta linha //baixo--; esquerda++; break; case C2D2M_SOLIDO22A: case C2D2M_SOLIDO157B: entrou=x+larg/2 - meio*mapa->dimensaoBlocoH; if(bloco == C2D2M_SOLIDO22A) entrou++; else entrou = mapa->dimensaoBlocoH-entrou; dif = (baixo+1)*mapa->dimensaoBlocoV-1-(y+alt); // Aqui colide e ajusta if(dif < entrou/2) y --;//= entrou/2-dif; //baixo--; esquerda++; break; case C2D2M_SOLIDO22B: case C2D2M_SOLIDO157A: entrou=x+larg/2 - meio*mapa->dimensaoBlocoH; if(bloco == C2D2M_SOLIDO22B) entrou++; else entrou = mapa->dimensaoBlocoH-entrou; dif = (baixo+1)*mapa->dimensaoBlocoV-1-(y+alt); // Aqui colide e ajusta if(dif < (entrou+mapa->dimensaoBlocoV)/2) { y --;//= (entrou+mapa->dimensaoBlocoV)/2-dif; } // Não verifica a colisão na horizontal nesta linha //baixo--; esquerda++; break; } } // ajusta pela parte de cima if(topo >= 0 && topo<= mapa->altura) { bloco =mapa->camadas[mapa->camadaMarcas][mapa->largura*topo+meio]-mapa->offbloco; switch(bloco) { case C2D2M_SOLIDO225: case C2D2M_SOLIDO315: entrou=x+larg/2 - meio*mapa->dimensaoBlocoH; if(bloco == C2D2M_SOLIDO315) entrou++; else entrou = mapa->dimensaoBlocoH-entrou; dif = y - (topo)*mapa->dimensaoBlocoV; // Aqui colide e ajusta if(dif < entrou) y += entrou-dif; //topo++; direita--; break; case C2D2M_SOLIDO202B: case C2D2M_SOLIDO337A: entrou=x+larg/2 - meio*mapa->dimensaoBlocoH; if(bloco == C2D2M_SOLIDO337A) entrou++; else entrou = mapa->dimensaoBlocoH-entrou; dif = y - topo*mapa->dimensaoBlocoV; // Aqui colide e ajusta if(dif < entrou/2) y += entrou/2-dif; // Não verifica a colisão na horizontal nesta linha //topo++; direita--; break; case C2D2M_SOLIDO202A: case C2D2M_SOLIDO337B: entrou=x+larg/2 - meio*mapa->dimensaoBlocoH; if(bloco == C2D2M_SOLIDO337B) entrou++; else entrou = mapa->dimensaoBlocoH-entrou; dif = y - topo*mapa->dimensaoBlocoV; // Aqui colide e ajusta if(dif < (entrou+mapa->dimensaoBlocoV)/2) y += (entrou+mapa->dimensaoBlocoV)/2-dif; // Não verifica a colisão na horizontal nesta linha //topo++; direita--; break; } } } // Testa a colisão com bloco completamente sólido na vertical for(int col=esquerda;col<=direita;col++) { // Testa se está dentro das coordenadas válidas if(col < 0 || col >= mapa->largura) continue; // Testa se ainda está dentro do mapa acima if(topo >= 0 && topo <= mapa->altura && dyl<0) // Testa se colidiu if(mapa->camadas[mapa->camadaMarcas][mapa->largura*topo+col] == mapa->offbloco + C2D2M_SOLIDO) { // Se colidiu, aumenta um ponto e encerra y++; //dxl; //ATOR_InsereEvento(a, EVT_COLIDIU_PAREDE_CIMA); break; } // Testa se ainda está dentro do mapa abaixo if(baixo >= 0 && baixo <= mapa->altura && dyl>0) // Testa se colidiu if(mapa->camadas[mapa->camadaMarcas][mapa->largura*baixo+col] == mapa->offbloco + C2D2M_SOLIDO) { // Se colidiu, diminui um ponto e encerra y--; //dxl; //ATOR_InsereEvento(a, EVT_COLIDIU_PAREDE_BAIXO); break; } } } // Para cada passo, verifica as colisões //ATOR_ColideBoundingBox(a, mapa); } // Atualiza o dx e dy *dx = x-xorig; *dy = y-yorig; return;// (cx || cy); } // Para um mapa, calcula a velocidade de um corpo de acordo com o tempo total da queda // expresso em quadros (60 quadros por segundo) bool C2D2M_CalculaQueda(unsigned int idMapa, int quadrosQueda, double *vqueda) { if(idMapa == 0 || idMapa>=C2D2M_MAX_MAPAS) return false; // SE o mapa não foi inicializado, ou se a camada de marcas está na default (-1) if(!mapas[idMapa-1].inicializado || mapas[idMapa-1].camadaMarcas==-1) return false; // Recupera o mapa C2D2M_Mapa *mapa = &mapas[idMapa-1]; // Se a gravidade do mapa for zerada ... if(mapa->gravidade == 0) return false; // Calcula o tempo, considerando 60 quadros por segundo double tempo = quadrosQueda*1.0/60.0; // Calcula a velocidade. *vqueda = mapa->gravidade*tempo*tempo; // Limita a velocidade (""atrito com o ar"") if(*vqueda > mapa->maxgravidade/60.0) *vqueda = mapa->maxgravidade/60.0; // Retorna o resultado return true; } // Testa se um bounding box colide com um bloco qualquer de cenário. // // Data: 28/08/2008 // bool C2D2M_ColidiuBlocoCenario(unsigned int idMapa, int x, int y, int larg, int alt, int bloco) { if(idMapa == 0 || idMapa>=C2D2M_MAX_MAPAS) return false; // SE o mapa não foi inicializado, ou se a camada de marcas está na default (-1) if(!mapas[idMapa-1].inicializado || mapas[idMapa-1].camadaMarcas==-1) return false; // Recupera o mapa C2D2M_Mapa *mapa = &mapas[idMapa-1]; // Intervalo de blocos em que verificamos a colisão int topo, baixo, esquerda, direita; // Calcula o extremo esquerdo topo = y/mapa->dimensaoBlocoV; esquerda = x/mapa->dimensaoBlocoH; // Calcula o extremo direito baixo = (y+alt-1)/mapa->dimensaoBlocoV; direita = (x+larg-1)/mapa->dimensaoBlocoH; // Indica se houve colisao bool cxy=false; // Para cada bloco no intervalo for(int lin=topo;lin<=baixo && ! cxy;lin++) for(int col=esquerda;col<=direita && !cxy ;col++) { // O bloco é válido para colisão? // Ele é SE: // - Ele está dentro do mapa // - Se ele é bloco (ele pode ser colidido) // Testa então se está dentro do mapa if(lin< 0 || lin >= mapa->altura || col < 0 || col >= mapa->largura) continue; // Testa se ele é válido if(mapa->camadas[mapa->camadaMarcas][mapa->largura*lin+col]==mapa->offbloco+bloco) cxy = true; } return cxy; } // Método para verificar se o cabeçalho do FMP/FMA é correto // // Data: 26/01/2005 // Última atualização: 29/07/2007 bool C2D2M_VerificaCabecalhoArquivo(CabecalhoArquivo *cabecalho) { // Está certo por definição bool ok=true; // Verifica se tem o FORM no começo for(int i=0;i<4;i++) if(cabecalho->tipo[i] != cabecalhos[0][i]) { ok=false; break; } if(!ok) return ok; // Verifica se tem o FMAP no subtipo for(int i=0;i<4;i++) if(cabecalho->subtipo[i] != cabecalhos[1][i]) { ok=false; break; } return ok; } // Função para verificar o tipo do cabeçalho. Retorna um dos tipos enumerados // // Data: 26/01/2005 // Última atualização: 29/07/2007 int C2D2M_TipoBloco(CabecalhoBloco *cabecalho) { // Verifica se é o bloco do MPHD no começo bool ok=true; for(int i=0;i<4;i++) if(cabecalho->tipo[i] != cabecalhos[2][i]) { ok=false; break; } if(ok) return CABECALHO_MPHD; // Verifica se é o bloco do ANDT no começo ok=true; for(int i=0;i<4;i++) if(cabecalho->tipo[i] != cabecalhos[3][i]) { ok=false; break; } if(ok) return CABECALHO_ANDT; // Verifica se é o bloco do BODY no começo ok=true; for(int i=0;i<4;i++) if(cabecalho->tipo[i] != cabecalhos[4][i]) { ok=false; break; } if(ok) return CABECALHO_BODY; // Verifica se é uma camada (o quarto caracter é o número da camada) ok=true; for(int i=0;i<3;i++) if(cabecalho->tipo[i] != cabecalhos[5][i]) { ok=false; break; } if(ok) return CABECALHO_LYR; // Por default return CABECALHO_IGNORADO; } // Função que recupera a camazda de marcas // // Data: 30/01/2010 // // unsigned int C2D2M_PegaCamadaMarcas(unsigned int idMapa) { // � um mapa v�lido? if(idMapa==0 || idMapa >= C2D2M_MAX_MAPAS) return -1; return(mapas[idMapa-1].camadaMarcas); } // Função para mudar o valor de um bloco em uma camada específica // // Data: 30/01/2010 // �ltima atualiza��o: 30/01/2010 // void C2D2M_AlteraBloco(unsigned int idMapa, int camada, int x, int y, unsigned int valor) { // � um mapa v�lido? if(idMapa==0 || idMapa >= C2D2M_MAX_MAPAS) return; // Se n�o foi inicializado, falha! if(!mapas[idMapa-1].inicializado) return; // A camada � v�lida? if(camada<0 || camada>=C2D2M_MAX_CAMADAS) return; // Pega o ponteiro do mapa (mais r�pido) C2D2M_Mapa *mapa = &mapas[idMapa-1]; // Testa se o layer existe if(mapa->camadas[camada] == 0) return; // So muda o bloco se ele estiver dentro do mapa if(x<0 || y<0 || x>=mapa->largura || y>=mapa->altura) return; mapa->camadas[camada][mapa->largura*y+x]=valor+mapa->offbloco; } ",16312,True,3073.302866171888,median "// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. /*============================================================================= =============================================================================*/ #include ""Components/ReflectionCaptureComponent.h"" #include ""Serialization/MemoryWriter.h"" #include ""UObject/RenderingObjectVersion.h"" #include ""UObject/ConstructorHelpers.h"" #include ""GameFramework/Actor.h"" #include ""RHI.h"" #include ""RenderingThread.h"" #include ""RenderResource.h"" #include ""Misc/ScopeLock.h"" #include ""Components/BillboardComponent.h"" #include ""Engine/CollisionProfile.h"" #include ""Serialization/MemoryReader.h"" #include ""UObject/UObjectHash.h"" #include ""UObject/UObjectIterator.h"" #include ""Engine/Texture2D.h"" #include ""SceneManagement.h"" #include ""Engine/ReflectionCapture.h"" #include ""DerivedDataCacheInterface.h"" #include ""Interfaces/ITargetPlatform.h"" #include ""EngineModule.h"" #include ""ShaderCompiler.h"" #include ""LoadTimesObjectVersion.h"" #include ""RenderingObjectVersion.h"" #include ""Engine/SphereReflectionCapture.h"" #include ""Components/SphereReflectionCaptureComponent.h"" #include ""Components/DrawSphereComponent.h"" #include ""Components/BoxReflectionCaptureComponent.h"" #include ""Engine/PlaneReflectionCapture.h"" #include ""Engine/BoxReflectionCapture.h"" #include ""Components/PlaneReflectionCaptureComponent.h"" #include ""Components/BoxComponent.h"" #include ""Components/SkyLightComponent.h"" #include ""ProfilingDebugging/CookStats.h"" #if ENABLE_COOK_STATS namespace ReflectionCaptureCookStats { static FCookStats::FDDCResourceUsageStats UsageStats; static FCookStatsManager::FAutoRegisterCallback RegisterCookStats([](FCookStatsManager::AddStatFuncRef AddStat) { UsageStats.LogStats(AddStat, TEXT(""ReflectionCapture.Usage""), TEXT("""")); }); } #endif // ES3.0+ devices support seamless cubemap filtering, averaging edges will produce artifacts on those devices #define MOBILE_AVERAGE_CUBEMAP_EDGES 0 /** * Size of all reflection captures. * Reflection capture derived data versions must be changed if modifying this */ ENGINE_API TAutoConsoleVariable CVarReflectionCaptureSize( TEXT(""r.ReflectionCaptureResolution""), 128, TEXT(""Set the resolution for all reflection capture cubemaps. Should be set via project's Render Settings. Must be power of 2. Defaults to 128.\\n"") ); static int32 SanatizeReflectionCaptureSize(int32 ReflectionCaptureSize) { static const int32 MaxReflectionCaptureSize = 1024; static const int32 MinReflectionCaptureSize = 1; return FMath::Clamp(ReflectionCaptureSize, MinReflectionCaptureSize, MaxReflectionCaptureSize); } int32 UReflectionCaptureComponent::GetReflectionCaptureSize_GameThread() { return SanatizeReflectionCaptureSize(CVarReflectionCaptureSize.GetValueOnGameThread()); } int32 UReflectionCaptureComponent::GetReflectionCaptureSize_RenderThread() { return SanatizeReflectionCaptureSize(CVarReflectionCaptureSize.GetValueOnRenderThread()); } void UReflectionCaptureComponent::ReleaseHDRData() { ENQUEUE_UNIQUE_RENDER_COMMAND_ONEPARAMETER( ReleaseHDRData, FReflectionCaptureFullHDR*, FullHDRData, FullHDRData, { delete FullHDRData; }); FullHDRData = nullptr; } void UWorld::UpdateAllReflectionCaptures() { if ( FeatureLevel < ERHIFeatureLevel::SM4) { UE_LOG(LogMaterial, Warning, TEXT(""Update reflection captures only works with an active feature level of SM4 or greater."")); return; } TArray Packages; for (TObjectIterator It; It; ++It) { UReflectionCaptureComponent* CaptureComponent = *It; if (ContainsActor(CaptureComponent->GetOwner()) && !CaptureComponent->IsPendingKill()) { // Purge cached derived data and force an update CaptureComponent->SetCaptureIsDirty(); Packages.AddUnique(CaptureComponent->GetOutermost()); } } for (UPackage* Package : Packages) { if (Package) { // Need to dirty capture packages for new HDR data Package->MarkPackageDirty(); } } UReflectionCaptureComponent::UpdateReflectionCaptureContents(this); for (TObjectIterator It; It; ++It) { USkyLightComponent* SkylightComponent = *It; if (ContainsActor(SkylightComponent->GetOwner()) && !SkylightComponent->IsPendingKill()) { SkylightComponent->SetCaptureIsDirty(); } } USkyLightComponent::UpdateSkyCaptureContents(this); } AReflectionCapture::AReflectionCapture(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { CaptureComponent = CreateAbstractDefaultSubobject(TEXT(""NewReflectionComponent"")); bCanBeInCluster = true; #if WITH_EDITORONLY_DATA SpriteComponent = CreateEditorOnlyDefaultSubobject(TEXT(""Sprite"")); if (!IsRunningCommandlet() && (SpriteComponent != nullptr)) { // Structure to hold one-time initialization struct FConstructorStatics { FName NAME_ReflectionCapture; ConstructorHelpers::FObjectFinderOptional DecalTexture; FConstructorStatics() : NAME_ReflectionCapture(TEXT(""ReflectionCapture"")) , DecalTexture(TEXT(""/Engine/EditorResources/S_ReflActorIcon"")) { } }; static FConstructorStatics ConstructorStatics; SpriteComponent->Sprite = ConstructorStatics.DecalTexture.Get(); SpriteComponent->RelativeScale3D = FVector(0.5f, 0.5f, 0.5f); SpriteComponent->bHiddenInGame = true; SpriteComponent->bAbsoluteScale = true; SpriteComponent->SetCollisionProfileName(UCollisionProfile::NoCollision_ProfileName); SpriteComponent->bIsScreenSizeScaled = true; } CaptureOffsetComponent = CreateEditorOnlyDefaultSubobject(TEXT(""CaptureOffset"")); if (!IsRunningCommandlet() && (CaptureOffsetComponent != nullptr)) { // Structure to hold one-time initialization struct FConstructorStatics { FName NAME_ReflectionCapture; ConstructorHelpers::FObjectFinderOptional DecalTexture; FConstructorStatics() : NAME_ReflectionCapture(TEXT(""ReflectionCapture"")) , DecalTexture(TEXT(""/Engine/EditorResources/S_ReflActorIcon"")) { } }; static FConstructorStatics ConstructorStatics; CaptureOffsetComponent->Sprite = ConstructorStatics.DecalTexture.Get(); CaptureOffsetComponent->RelativeScale3D = FVector(0.2f, 0.2f, 0.2f); CaptureOffsetComponent->bHiddenInGame = true; CaptureOffsetComponent->bAbsoluteScale = true; CaptureOffsetComponent->SetCollisionProfileName(UCollisionProfile::NoCollision_ProfileName); CaptureOffsetComponent->bIsScreenSizeScaled = true; } if (CaptureComponent) { CaptureComponent->CaptureOffsetComponent = CaptureOffsetComponent; } #endif // WITH_EDITORONLY_DATA } #if WITH_EDITOR void AReflectionCapture::PostEditMove(bool bFinished) { Super::PostEditMove(bFinished); CaptureComponent->SetCaptureIsDirty(); } #endif // WITH_EDITOR ASphereReflectionCapture::ASphereReflectionCapture(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer.SetDefaultSubobjectClass(TEXT(""NewReflectionComponent""))) { USphereReflectionCaptureComponent* SphereComponent = CastChecked(GetCaptureComponent()); RootComponent = SphereComponent; #if WITH_EDITORONLY_DATA if (GetSpriteComponent()) { GetSpriteComponent()->SetupAttachment(SphereComponent); } if (GetCaptureOffsetComponent()) { GetCaptureOffsetComponent()->SetupAttachment(SphereComponent); } #endif //WITH_EDITORONLY_DATA UDrawSphereComponent* DrawInfluenceRadius = CreateDefaultSubobject(TEXT(""DrawRadius0"")); DrawInfluenceRadius->SetupAttachment(GetCaptureComponent()); DrawInfluenceRadius->bDrawOnlyIfSelected = true; DrawInfluenceRadius->bUseEditorCompositing = true; DrawInfluenceRadius->SetCollisionProfileName(UCollisionProfile::NoCollision_ProfileName); SphereComponent->PreviewInfluenceRadius = DrawInfluenceRadius; DrawCaptureRadius = CreateDefaultSubobject(TEXT(""DrawRadius1"")); DrawCaptureRadius->SetupAttachment(GetCaptureComponent()); DrawCaptureRadius->bDrawOnlyIfSelected = true; DrawCaptureRadius->bUseEditorCompositing = true; DrawCaptureRadius->SetCollisionProfileName(UCollisionProfile::NoCollision_ProfileName); DrawCaptureRadius->ShapeColor = FColor(100, 90, 40); } #if WITH_EDITOR void ASphereReflectionCapture::EditorApplyScale(const FVector& DeltaScale, const FVector* PivotLocation, bool bAltDown, bool bShiftDown, bool bCtrlDown) { USphereReflectionCaptureComponent* SphereComponent = Cast(GetCaptureComponent()); check(SphereComponent); const FVector ModifiedScale = DeltaScale * ( AActor::bUsePercentageBasedScaling ? 5000.0f : 50.0f ); FMath::ApplyScaleToFloat(SphereComponent->InfluenceRadius, ModifiedScale); GetCaptureComponent()->SetCaptureIsDirty(); PostEditChange(); } void APlaneReflectionCapture::EditorApplyScale(const FVector& DeltaScale, const FVector* PivotLocation, bool bAltDown, bool bShiftDown, bool bCtrlDown) { UPlaneReflectionCaptureComponent* PlaneComponent = Cast(GetCaptureComponent()); check(PlaneComponent); const FVector ModifiedScale = DeltaScale * ( AActor::bUsePercentageBasedScaling ? 5000.0f : 50.0f ); FMath::ApplyScaleToFloat(PlaneComponent->InfluenceRadiusScale, ModifiedScale); GetCaptureComponent()->SetCaptureIsDirty(); PostEditChange(); } #endif ABoxReflectionCapture::ABoxReflectionCapture(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer.SetDefaultSubobjectClass(TEXT(""NewReflectionComponent""))) { UBoxReflectionCaptureComponent* BoxComponent = CastChecked(GetCaptureComponent()); BoxComponent->RelativeScale3D = FVector(1000, 1000, 400); RootComponent = BoxComponent; #if WITH_EDITORONLY_DATA if (GetSpriteComponent()) { GetSpriteComponent()->SetupAttachment(BoxComponent); } if (GetCaptureOffsetComponent()) { GetCaptureOffsetComponent()->SetupAttachment(BoxComponent); } #endif //WITH_EDITORONLY_DATA UBoxComponent* DrawInfluenceBox = CreateDefaultSubobject(TEXT(""DrawBox0"")); DrawInfluenceBox->SetupAttachment(GetCaptureComponent()); DrawInfluenceBox->bDrawOnlyIfSelected = true; DrawInfluenceBox->bUseEditorCompositing = true; DrawInfluenceBox->SetCollisionProfileName(UCollisionProfile::NoCollision_ProfileName); DrawInfluenceBox->InitBoxExtent(FVector(1, 1, 1)); BoxComponent->PreviewInfluenceBox = DrawInfluenceBox; UBoxComponent* DrawCaptureBox = CreateDefaultSubobject(TEXT(""DrawBox1"")); DrawCaptureBox->SetupAttachment(GetCaptureComponent()); DrawCaptureBox->bDrawOnlyIfSelected = true; DrawCaptureBox->bUseEditorCompositing = true; DrawCaptureBox->SetCollisionProfileName(UCollisionProfile::NoCollision_ProfileName); DrawCaptureBox->ShapeColor = FColor(100, 90, 40); DrawCaptureBox->InitBoxExtent(FVector(1, 1, 1)); BoxComponent->PreviewCaptureBox = DrawCaptureBox; } APlaneReflectionCapture::APlaneReflectionCapture(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer.SetDefaultSubobjectClass(TEXT(""NewReflectionComponent""))) { UPlaneReflectionCaptureComponent* PlaneComponent = CastChecked(GetCaptureComponent()); PlaneComponent->RelativeScale3D = FVector(1, 1000, 1000); RootComponent = PlaneComponent; #if WITH_EDITORONLY_DATA if (GetSpriteComponent()) { GetSpriteComponent()->SetupAttachment(PlaneComponent); } if (GetCaptureOffsetComponent()) { GetCaptureOffsetComponent()->SetupAttachment(PlaneComponent); } #endif //#if WITH_EDITORONLY_DATA UDrawSphereComponent* DrawInfluenceRadius = CreateDefaultSubobject(TEXT(""DrawRadius0"")); DrawInfluenceRadius->SetupAttachment(GetCaptureComponent()); DrawInfluenceRadius->bDrawOnlyIfSelected = true; DrawInfluenceRadius->bAbsoluteScale = true; DrawInfluenceRadius->bUseEditorCompositing = true; DrawInfluenceRadius->SetCollisionProfileName(UCollisionProfile::NoCollision_ProfileName); PlaneComponent->PreviewInfluenceRadius = DrawInfluenceRadius; UBoxComponent* DrawCaptureBox = CreateDefaultSubobject(TEXT(""DrawBox1"")); DrawCaptureBox->SetupAttachment(GetCaptureComponent()); DrawCaptureBox->bDrawOnlyIfSelected = true; DrawCaptureBox->bUseEditorCompositing = true; DrawCaptureBox->SetCollisionProfileName(UCollisionProfile::NoCollision_ProfileName); DrawCaptureBox->ShapeColor = FColor(100, 90, 40); DrawCaptureBox->InitBoxExtent(FVector(1, 1, 1)); PlaneComponent->PreviewCaptureBox = DrawCaptureBox; } // Generate a new guid to force a recapture of all reflection data // Note: changing this will cause saved capture data in maps to be discarded // A resave of those maps will be required to guarantee valid reflections when cooking for ES2 FGuid ReflectionCaptureDDCVer(0x0c669396, 0x9cb849ae, 0x9f4120ff, 0x5812f4d3); // Bumping this version will invalidate only encoded capture data #define REFLECTIONCAPTURE_ENCODED_DERIVEDDATA_VER 1 FReflectionCaptureFullHDR::~FReflectionCaptureFullHDR() { DEC_MEMORY_STAT_BY(STAT_ReflectionCaptureMemory, CompressedCapturedData.GetAllocatedSize()); } void FReflectionCaptureFullHDR::InitializeFromUncompressedData(const TArray& UncompressedData, int32 InCubemapSize) { CubemapSize = InCubemapSize; DEC_MEMORY_STAT_BY(STAT_ReflectionCaptureMemory, CompressedCapturedData.GetAllocatedSize()); int32 UncompressedSize = UncompressedData.Num() * UncompressedData.GetTypeSize(); TArray TempCompressedMemory; // Compressed can be slightly larger than uncompressed TempCompressedMemory.Empty(UncompressedSize * 4 / 3); TempCompressedMemory.AddUninitialized(UncompressedSize * 4 / 3); int32 CompressedSize = TempCompressedMemory.Num() * TempCompressedMemory.GetTypeSize(); verify(FCompression::CompressMemory( (ECompressionFlags)(COMPRESS_ZLIB | COMPRESS_BiasMemory), TempCompressedMemory.GetData(), CompressedSize, UncompressedData.GetData(), UncompressedSize)); // Note: change REFLECTIONCAPTURE_FULL_DERIVEDDATA_VER when modifying the serialization layout FMemoryWriter FinalArchive(CompressedCapturedData, true); FinalArchive << UncompressedSize; FinalArchive << CompressedSize; FinalArchive.Serialize(TempCompressedMemory.GetData(), CompressedSize); INC_MEMORY_STAT_BY(STAT_ReflectionCaptureMemory, CompressedCapturedData.GetAllocatedSize()); } TRefCountPtr FReflectionCaptureFullHDR::GetUncompressedData() const { // If we have serialized uncompressed data (from a cook), use it rather than uncompressing if (StoredUncompressedData) { return StoredUncompressedData; } else { check(CompressedCapturedData.Num() > 0); FMemoryReader Ar(CompressedCapturedData); // Note: change REFLECTIONCAPTURE_FULL_DERIVEDDATA_VER when modifying the serialization layout int32 UncompressedSize; Ar << UncompressedSize; int32 CompressedSize; Ar << CompressedSize; TRefCountPtr UncompressedDataOut = new FReflectionCaptureUncompressedData(UncompressedSize); const uint8* SourceData = &CompressedCapturedData[Ar.Tell()]; verify(FCompression::UncompressMemory((ECompressionFlags)COMPRESS_ZLIB, UncompressedDataOut->GetData(), UncompressedSize, SourceData, CompressedSize)); return UncompressedDataOut; } } FColor RGBMEncode( FLinearColor Color ) { FColor Encoded; // Convert to gamma space Color.R = FMath::Sqrt( Color.R ); Color.G = FMath::Sqrt( Color.G ); Color.B = FMath::Sqrt( Color.B ); // Range Color /= 16.0f; float MaxValue = FMath::Max( FMath::Max(Color.R, Color.G), FMath::Max(Color.B, DELTA) ); if( MaxValue > 0.75f ) { // Fit to valid range by leveling off intensity float Tonemapped = ( MaxValue - 0.75 * 0.75 ) / ( MaxValue - 0.5 ); Color *= Tonemapped / MaxValue; MaxValue = Tonemapped; } Encoded.A = FMath::Min( FMath::CeilToInt( MaxValue * 255.0f ), 255 ); Encoded.R = FMath::RoundToInt( ( Color.R * 255.0f / Encoded.A ) * 255.0f ); Encoded.G = FMath::RoundToInt( ( Color.G * 255.0f / Encoded.A ) * 255.0f ); Encoded.B = FMath::RoundToInt( ( Color.B * 255.0f / Encoded.A ) * 255.0f ); return Encoded; } // Based off of CubemapGen // https://code.google.com/p/cubemapgen/ #define FACE_X_POS 0 #define FACE_X_NEG 1 #define FACE_Y_POS 2 #define FACE_Y_NEG 3 #define FACE_Z_POS 4 #define FACE_Z_NEG 5 #define EDGE_LEFT 0 // u = 0 #define EDGE_RIGHT 1 // u = 1 #define EDGE_TOP 2 // v = 0 #define EDGE_BOTTOM 3 // v = 1 #define CORNER_NNN 0 #define CORNER_NNP 1 #define CORNER_NPN 2 #define CORNER_NPP 3 #define CORNER_PNN 4 #define CORNER_PNP 5 #define CORNER_PPN 6 #define CORNER_PPP 7 // D3D cube map face specification // mapping from 3D x,y,z cube map lookup coordinates // to 2D within face u,v coordinates // // --------------------> U direction // | (within-face texture space) // | _____ // | | | // | | +Y | // | _____|_____|_____ _____ // | | | | | | // | | -X | +Z | +X | -Z | // | |_____|_____|_____|_____| // | | | // | | -Y | // | |_____| // | // v V direction // (within-face texture space) // Index by [Edge][FaceOrEdge] static const int32 CubeEdgeListA[12][2] = { {FACE_X_POS, EDGE_LEFT}, {FACE_X_POS, EDGE_RIGHT}, {FACE_X_POS, EDGE_TOP}, {FACE_X_POS, EDGE_BOTTOM}, {FACE_X_NEG, EDGE_LEFT}, {FACE_X_NEG, EDGE_RIGHT}, {FACE_X_NEG, EDGE_TOP}, {FACE_X_NEG, EDGE_BOTTOM}, {FACE_Z_POS, EDGE_TOP}, {FACE_Z_POS, EDGE_BOTTOM}, {FACE_Z_NEG, EDGE_TOP}, {FACE_Z_NEG, EDGE_BOTTOM} }; static const int32 CubeEdgeListB[12][2] = { {FACE_Z_POS, EDGE_RIGHT }, {FACE_Z_NEG, EDGE_LEFT }, {FACE_Y_POS, EDGE_RIGHT }, {FACE_Y_NEG, EDGE_RIGHT }, {FACE_Z_NEG, EDGE_RIGHT }, {FACE_Z_POS, EDGE_LEFT }, {FACE_Y_POS, EDGE_LEFT }, {FACE_Y_NEG, EDGE_LEFT }, {FACE_Y_POS, EDGE_BOTTOM }, {FACE_Y_NEG, EDGE_TOP }, {FACE_Y_POS, EDGE_TOP }, {FACE_Y_NEG, EDGE_BOTTOM }, }; // Index by [Face][Corner] static const int32 CubeCornerList[6][4] = { { CORNER_PPP, CORNER_PPN, CORNER_PNP, CORNER_PNN }, { CORNER_NPN, CORNER_NPP, CORNER_NNN, CORNER_NNP }, { CORNER_NPN, CORNER_PPN, CORNER_NPP, CORNER_PPP }, { CORNER_NNP, CORNER_PNP, CORNER_NNN, CORNER_PNN }, { CORNER_NPP, CORNER_PPP, CORNER_NNP, CORNER_PNP }, { CORNER_PPN, CORNER_NPN, CORNER_PNN, CORNER_NNN } }; static void EdgeWalkSetup( bool ReverseDirection, int32 Edge, int32 MipSize, int32& EdgeStart, int32& EdgeStep ) { if( ReverseDirection ) { switch( Edge ) { case EDGE_LEFT: //start at lower left and walk up EdgeStart = MipSize * (MipSize - 1); EdgeStep = -MipSize; break; case EDGE_RIGHT: //start at lower right and walk up EdgeStart = MipSize * (MipSize - 1) + (MipSize - 1); EdgeStep = -MipSize; break; case EDGE_TOP: //start at upper right and walk left EdgeStart = (MipSize - 1); EdgeStep = -1; break; case EDGE_BOTTOM: //start at lower right and walk left EdgeStart = MipSize * (MipSize - 1) + (MipSize - 1); EdgeStep = -1; break; } } else { switch( Edge ) { case EDGE_LEFT: //start at upper left and walk down EdgeStart = 0; EdgeStep = MipSize; break; case EDGE_RIGHT: //start at upper right and walk down EdgeStart = (MipSize - 1); EdgeStep = MipSize; break; case EDGE_TOP: //start at upper left and walk left EdgeStart = 0; EdgeStep = 1; break; case EDGE_BOTTOM: //start at lower left and walk left EdgeStart = MipSize * (MipSize - 1); EdgeStep = 1; break; } } } void FReflectionCaptureEncodedHDRDerivedData::GenerateFromDerivedDataSource(const FReflectionCaptureFullHDR& FullHDRData, float Brightness) { const int32 NumMips = FMath::CeilLogTwo(FullHDRData.CubemapSize) + 1; TRefCountPtr SourceCubemapData = FullHDRData.GetUncompressedData(); int32 SourceMipBaseIndex = 0; int32 DestMipBaseIndex = 0; CapturedData = new FReflectionCaptureUncompressedData(SourceCubemapData->Size() * sizeof(FColor) / sizeof(FFloat16Color)); // Note: change REFLECTIONCAPTURE_ENCODED_DERIVEDDATA_VER when modifying the encoded data layout or contents for (int32 MipIndex = 0; MipIndex < NumMips; MipIndex++) { const int32 MipSize = 1 << (NumMips - MipIndex - 1); const int32 SourceCubeFaceBytes = MipSize * MipSize * sizeof(FFloat16Color); const int32 DestCubeFaceBytes = MipSize * MipSize * sizeof(FColor); const FFloat16Color* MipSrcData = (const FFloat16Color*)SourceCubemapData->GetData(SourceMipBaseIndex); FColor* MipDstData = (FColor*)CapturedData->GetData(DestMipBaseIndex); #if MOBILE_AVERAGE_CUBEMAP_EDGES // Fix cubemap seams by averaging colors across edges int32 CornerTable[4] = { 0, MipSize - 1, MipSize * (MipSize - 1), MipSize * (MipSize - 1) + MipSize - 1, }; // Average corner colors FLinearColor AvgCornerColors[8]; memset( AvgCornerColors, 0, sizeof( AvgCornerColors ) ); for( int32 Face = 0; Face < CubeFace_MAX; Face++ ) { const FFloat16Color* FaceSrcData = MipSrcData + Face * MipSize * MipSize; for( int32 Corner = 0; Corner < 4; Corner++ ) { AvgCornerColors[ CubeCornerList[Face][Corner] ] += FLinearColor( FaceSrcData[ CornerTable[Corner] ] ); } } // Encode corners for( int32 Face = 0; Face < CubeFace_MAX; Face++ ) { FColor* FaceDstData = MipDstData + Face * MipSize * MipSize; for( int32 Corner = 0; Corner < 4; Corner++ ) { const FLinearColor LinearColor = AvgCornerColors[ CubeCornerList[Face][Corner] ] / 3.0f; FaceDstData[ CornerTable[Corner] ] = RGBMEncode( LinearColor * Brightness ); } } // Average edge colors for( int32 EdgeIndex = 0; EdgeIndex < 12; EdgeIndex++ ) { int32 FaceA = CubeEdgeListA[ EdgeIndex ][0]; int32 EdgeA = CubeEdgeListA[ EdgeIndex ][1]; int32 FaceB = CubeEdgeListB[ EdgeIndex ][0]; int32 EdgeB = CubeEdgeListB[ EdgeIndex ][1]; const FFloat16Color* FaceSrcDataA = MipSrcData + FaceA * MipSize * MipSize; FColor* FaceDstDataA = MipDstData + FaceA * MipSize * MipSize; const FFloat16Color* FaceSrcDataB = MipSrcData + FaceB * MipSize * MipSize; FColor* FaceDstDataB = MipDstData + FaceB * MipSize * MipSize; int32 EdgeStartA = 0; int32 EdgeStepA = 0; int32 EdgeStartB = 0; int32 EdgeStepB = 0; EdgeWalkSetup( false, EdgeA, MipSize, EdgeStartA, EdgeStepA ); EdgeWalkSetup( EdgeA == EdgeB || EdgeA + EdgeB == 3, EdgeB, MipSize, EdgeStartB, EdgeStepB ); // Walk edge // Skip corners for( int32 Texel = 1; Texel < MipSize - 1; Texel++ ) { int32 EdgeTexelA = EdgeStartA + EdgeStepA * Texel; int32 EdgeTexelB = EdgeStartB + EdgeStepB * Texel; check( 0 <= EdgeTexelA && EdgeTexelA < MipSize * MipSize ); check( 0 <= EdgeTexelB && EdgeTexelB < MipSize * MipSize ); const FLinearColor EdgeColorA = FLinearColor( FaceSrcDataA[ EdgeTexelA ] ); const FLinearColor EdgeColorB = FLinearColor( FaceSrcDataB[ EdgeTexelB ] ); const FLinearColor AvgColor = 0.5f * ( EdgeColorA + EdgeColorB ); FaceDstDataA[ EdgeTexelA ] = FaceDstDataB[ EdgeTexelB ] = RGBMEncode( AvgColor * Brightness ); } } #endif // MOBILE_AVERAGE_CUBEMAP_EDGES // Encode rest of texels for (int32 CubeFace = 0; CubeFace < CubeFace_MAX; CubeFace++) { const int32 FaceSourceIndex = SourceMipBaseIndex + CubeFace * SourceCubeFaceBytes; const int32 FaceDestIndex = DestMipBaseIndex + CubeFace * DestCubeFaceBytes; const FFloat16Color* FaceSourceData = (const FFloat16Color*)SourceCubemapData->GetData(FaceSourceIndex); FColor* FaceDestData = (FColor*)CapturedData->GetData(FaceDestIndex); // Convert each texel from linear space FP16 to RGBM FColor // Note: Brightness on the capture is baked into the encoded HDR data // Skip edges const int32 SkipEdges = MOBILE_AVERAGE_CUBEMAP_EDGES ? 1 : 0; for( int32 y = SkipEdges; y < MipSize - SkipEdges; y++ ) { for( int32 x = SkipEdges; x < MipSize - SkipEdges; x++ ) { int32 TexelIndex = x + y * MipSize; const FLinearColor LinearColor = FLinearColor( FaceSourceData[ TexelIndex ]) * Brightness; FaceDestData[ TexelIndex ] = RGBMEncode( LinearColor ); } } } SourceMipBaseIndex += SourceCubeFaceBytes * CubeFace_MAX; DestMipBaseIndex += DestCubeFaceBytes * CubeFace_MAX; } } FString FReflectionCaptureEncodedHDRDerivedData::GetDDCKeyString(const FGuid& StateId, int32 CubemapDimension) { return FDerivedDataCacheInterface::BuildCacheKey( TEXT(""REFL_ENC""), *ReflectionCaptureDDCVer.ToString(), *StateId.ToString().Append(""_"").Append(FString::FromInt(CubemapDimension)).Append(""_"").Append(FString::FromInt(REFLECTIONCAPTURE_ENCODED_DERIVEDDATA_VER)) ); } FReflectionCaptureEncodedHDRDerivedData::~FReflectionCaptureEncodedHDRDerivedData() { } TRefCountPtr FReflectionCaptureEncodedHDRDerivedData::GenerateEncodedHDRData(const FReflectionCaptureFullHDR& FullHDRData, const FGuid& StateId, float Brightness) { TRefCountPtr EncodedHDRData = new FReflectionCaptureEncodedHDRDerivedData(); const FString KeyString = GetDDCKeyString(StateId, FullHDRData.CubemapSize); COOK_STAT(auto Timer = ReflectionCaptureCookStats::UsageStats.TimeSyncWork()); bool DDCHit = GetDerivedDataCacheRef().GetSynchronous(*KeyString, EncodedHDRData->CapturedData->GetArray() ); if (!DDCHit) { EncodedHDRData->GenerateFromDerivedDataSource(FullHDRData, Brightness); if (EncodedHDRData->CapturedData->Size() > 0) { GetDerivedDataCacheRef().Put(*KeyString, EncodedHDRData->CapturedData->GetArray() ); } } EncodedHDRData->CapturedData->UpdateMemoryTracking(); COOK_STAT(Timer.AddHitOrMiss(DDCHit ? FCookStats::CallStats::EHitOrMiss::Hit : FCookStats::CallStats::EHitOrMiss::Miss, EncodedHDRData->CapturedData->Size())); check(EncodedHDRData->CapturedData->Size() > 0); return EncodedHDRData; } /** * A cubemap texture resource that knows how to upload the packed capture data from a reflection capture. * @todo - support texture streaming and compression */ class FReflectionTextureCubeResource : public FTexture { public: FReflectionTextureCubeResource() : Size(0), NumMips(0), Format(PF_Unknown) {} void SetupParameters(int32 InSize, int32 InNumMips, EPixelFormat InFormat, TRefCountPtr InSourceData) { Size = InSize; NumMips = InNumMips; Format = InFormat; SourceData = InSourceData; } virtual void InitRHI() override { FRHIResourceCreateInfo CreateInfo; TextureCubeRHI = RHICreateTextureCube(Size, Format, NumMips, 0, CreateInfo); TextureRHI = TextureCubeRHI; if (SourceData) { check(SourceData->Size() > 0); const int32 BlockBytes = GPixelFormats[Format].BlockBytes; int32 MipBaseIndex = 0; for (int32 MipIndex = 0; MipIndex < NumMips; MipIndex++) { const int32 MipSize = 1 << (NumMips - MipIndex - 1); const int32 CubeFaceBytes = MipSize * MipSize * BlockBytes; for (int32 CubeFace = 0; CubeFace < CubeFace_MAX; CubeFace++) { uint32 DestStride = 0; uint8* DestBuffer = (uint8*)RHILockTextureCubeFace(TextureCubeRHI, CubeFace, 0, MipIndex, RLM_WriteOnly, DestStride, false); // Handle DestStride by copying each row for (int32 Y = 0; Y < MipSize; Y++) { uint8* DestPtr = ((uint8*)DestBuffer + Y * DestStride); const int32 SourceIndex = MipBaseIndex + CubeFace * CubeFaceBytes + Y * MipSize * BlockBytes; const uint8* SourcePtr = SourceData->GetData(SourceIndex); FMemory::Memcpy(DestPtr, SourcePtr, MipSize * BlockBytes); } RHIUnlockTextureCubeFace(TextureCubeRHI, CubeFace, 0, MipIndex, false); } MipBaseIndex += CubeFaceBytes * CubeFace_MAX; } if (!GIsEditor) { // Toss the source data now that we've created the cubemap // Note: can't do this if we ever use this texture resource in the editor and want to save the data later SourceData = nullptr; } } // Create the sampler state RHI resource. FSamplerStateInitializerRHI SamplerStateInitializer ( SF_Trilinear, AM_Clamp, AM_Clamp, AM_Clamp ); SamplerStateRHI = RHICreateSamplerState(SamplerStateInitializer); INC_MEMORY_STAT_BY(STAT_ReflectionCaptureTextureMemory,CalcTextureSize(Size,Size,Format,NumMips) * 6); } virtual void ReleaseRHI() override { DEC_MEMORY_STAT_BY(STAT_ReflectionCaptureTextureMemory,CalcTextureSize(Size,Size,Format,NumMips) * 6); TextureCubeRHI.SafeRelease(); FTexture::ReleaseRHI(); } virtual uint32 GetSizeX() const override { return Size; } virtual uint32 GetSizeY() const override //-V524 { return Size; } FTextureRHIParamRef GetTextureRHI() { return TextureCubeRHI; } private: int32 Size; int32 NumMips; EPixelFormat Format; FTextureCubeRHIRef TextureCubeRHI; // Source data. Note that this is owned by the cubemap TRefCountPtr SourceData; }; TArray UReflectionCaptureComponent::ReflectionCapturesToUpdate; TArray UReflectionCaptureComponent::ReflectionCapturesToUpdateForLoad; FCriticalSection UReflectionCaptureComponent::ReflectionCapturesToUpdateForLoadLock; UReflectionCaptureComponent::UReflectionCaptureComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { Brightness = 1; // Shouldn't be able to change reflection captures at runtime Mobility = EComponentMobility::Static; bCaptureDirty = false; bDerivedDataDirty = false; bLoadedCookedData = false; AverageBrightness = 1.0f; } void UReflectionCaptureComponent::CreateRenderState_Concurrent() { Super::CreateRenderState_Concurrent(); UpdatePreviewShape(); if (ShouldRender()) { GetWorld()->Scene->AddReflectionCapture(this); } } void UReflectionCaptureComponent::SendRenderTransform_Concurrent() { // Don't update the transform of a component that needs to be recaptured, // Otherwise the RT will get the new transform one frame before the capture if (!bCaptureDirty) { UpdatePreviewShape(); if (ShouldRender()) { GetWorld()->Scene->UpdateReflectionCaptureTransform(this); } } Super::SendRenderTransform_Concurrent(); } void UReflectionCaptureComponent::OnRegister() { Super::OnRegister(); UWorld* World = GetWorld(); if (World->FeatureLevel < ERHIFeatureLevel::SM4) { if (EncodedHDRDerivedData == nullptr) { World->NumInvalidReflectionCaptureComponents+= 1; } } } void UReflectionCaptureComponent::OnUnregister() { UWorld* World = GetWorld(); if (World->FeatureLevel < ERHIFeatureLevel::SM4) { if (EncodedHDRDerivedData == nullptr && World->NumInvalidReflectionCaptureComponents > 0) { World->NumInvalidReflectionCaptureComponents-= 1; } } Super::OnUnregister(); } void UReflectionCaptureComponent::DestroyRenderState_Concurrent() { Super::DestroyRenderState_Concurrent(); GetWorld()->Scene->RemoveReflectionCapture(this); } void UReflectionCaptureComponent::PostInitProperties() { Super::PostInitProperties(); // Create a new guid in case this is a newly created component // If not, this guid will be overwritten when serialized FPlatformMisc::CreateGuid(StateId); if (!HasAnyFlags(RF_ClassDefaultObject | RF_ArchetypeObject)) { FScopeLock Lock(&ReflectionCapturesToUpdateForLoadLock); ReflectionCapturesToUpdateForLoad.AddUnique(this); bCaptureDirty = true; } } void UReflectionCaptureComponent::SerializeSourceData(FArchive& Ar) { if (Ar.UE4Ver() >= VER_UE4_REFLECTION_DATA_IN_PACKAGES) { if (Ar.IsSaving()) { Ar << ReflectionCaptureDDCVer; Ar << AverageBrightness; int32 StartOffset = Ar.Tell(); Ar << StartOffset; bool bValid = FullHDRData != NULL; Ar << bValid; if (FullHDRData) { Ar << FullHDRData->CubemapSize; Ar << FullHDRData->CompressedCapturedData; } int32 EndOffset = Ar.Tell(); Ar.Seek(StartOffset); Ar << EndOffset; Ar.Seek(EndOffset); } else if (Ar.IsLoading()) { FGuid SavedVersion; Ar << SavedVersion; if (Ar.CustomVer(FRenderingObjectVersion::GUID) >= FRenderingObjectVersion::ReflectionCapturesStoreAverageBrightness) { Ar << AverageBrightness; } int32 EndOffset = 0; Ar << EndOffset; if (SavedVersion != ReflectionCaptureDDCVer) { // Guid version of saved source data doesn't match latest, skip the data // The skipping is done so we don't have to maintain legacy serialization code paths when changing the format Ar.Seek(EndOffset); } else { bool bValid = false; Ar << bValid; if (bValid) { FullHDRData = new FReflectionCaptureFullHDR(); if (Ar.CustomVer(FRenderingObjectVersion::GUID) >= FRenderingObjectVersion::CustomReflectionCaptureResolutionSupport) { Ar << FullHDRData->CubemapSize; } else { FullHDRData->CubemapSize = 128; } Ar << FullHDRData->CompressedCapturedData; INC_MEMORY_STAT_BY(STAT_ReflectionCaptureMemory, FullHDRData->CompressedCapturedData.GetAllocatedSize()); } } } } } void UReflectionCaptureComponent::Serialize(FArchive& Ar) { DECLARE_SCOPE_CYCLE_COUNTER(TEXT(""UReflectionCaptureComponent::Serialize""), STAT_ReflectionCaptureComponent_Serialize, STATGROUP_LoadTime); Ar.UsingCustomVersion(FRenderingObjectVersion::GUID); Ar.UsingCustomVersion(FLoadTimesObjectVersion::GUID); Super::Serialize(Ar); bool bCooked = false; if (Ar.UE4Ver() >= VER_UE4_REFLECTION_CAPTURE_COOKING) { bCooked = Ar.IsCooking() || bLoadedCookedData; // Save a bool indicating whether this is cooked data // This is needed when loading cooked data, to know to serialize differently Ar << bCooked; // Save the cooked bool in a member so that if this object was loaded with cooked data, // it can be saved correctly later, such as if it needs to be duplicated. if (Ar.IsLoading()) { bLoadedCookedData = bCooked; } } if (FPlatformProperties::RequiresCookedData() && !bCooked && Ar.IsLoading()) { UE_LOG(LogMaterial, Fatal, TEXT(""This platform requires cooked packages, and this reflection capture does not contain cooked data %s.""), *GetName()); } if (bCooked) { static FName FullHDR(TEXT(""FullHDR"")); static FName EncodedHDR(TEXT(""EncodedHDR"")); // Saving for cooking, or previously loaded cooked data if (Ar.IsSaving()) { Ar << AverageBrightness; TArray Formats; // Get all the reflection capture formats that the target platform wants if (Ar.IsCooking()) { // Get all the reflection capture formats that the target platform wants Ar.CookingTarget()->GetReflectionCaptureFormats(Formats); } else { // Get the reflection capture formats that were loaded from cooked data Formats = LoadedFormats; } int32 NumFormats = Formats.Num(); Ar << NumFormats; for (int32 FormatIndex = 0; FormatIndex < NumFormats; FormatIndex++) { FName CurrentFormat = Formats[FormatIndex]; Ar << CurrentFormat; if (CurrentFormat == FullHDR) { // FullHDRData would have been set in PostLoad during cooking // Can't generate it if missing, since that requires rendering the scene bool bValid = FullHDRData != NULL; Ar << bValid; if (FullHDRData) { Ar << FullHDRData->CubemapSize; // Raw data needs to be uncompressed on cooked platforms to avoid decompression hitches TRefCountPtr UncompressedData = FullHDRData->GetUncompressedData(); Ar << UncompressedData->GetArray(); } } else { check(CurrentFormat == EncodedHDR); TRefCountPtr EncodedHDRData; // FullHDRData would have been set in PostLoad during cooking // Generate temporary encoded HDR data for saving if (FullHDRData != NULL && Ar.IsCooking()) { EncodedHDRData = FReflectionCaptureEncodedHDRDerivedData::GenerateEncodedHDRData(*FullHDRData, StateId, Brightness); } bool bValid = EncodedHDRData != NULL; Ar << bValid; if (bValid) { Ar << EncodedHDRData->CapturedData->GetArray(); } else if (!IsTemplate()) { // Temporary warning until the cooker can do scene captures itself in the case of missing DDC UE_LOG(LogMaterial, Warning, TEXT(""Reflection capture requires encoded HDR data but none was found in the DDC! This reflection will be black."")); UE_LOG(LogMaterial, Warning, TEXT(""Fix by resaving the map in the editor. %s.""), *GetFullName()); } } } } else { // Loading cooked data path Ar << AverageBrightness; int32 NumFormats = 0; Ar << NumFormats; LoadedFormats.SetNum(NumFormats); for (int32 FormatIndex = 0; FormatIndex < NumFormats; FormatIndex++) { FName CurrentFormat; Ar << CurrentFormat; LoadedFormats[FormatIndex] = CurrentFormat; bool bValid = false; Ar << bValid; if (bValid) { if (CurrentFormat == FullHDR) { FullHDRData = new FReflectionCaptureFullHDR(); Ar << FullHDRData->CubemapSize; if (Ar.CustomVer(FLoadTimesObjectVersion::GUID) >= FLoadTimesObjectVersion::UncompressedReflectionCapturesForCookedBuilds) { // Raw data needs to be uncompressed on cooked platforms to avoid hitches FullHDRData->StoredUncompressedData = new FReflectionCaptureUncompressedData(); Ar << FullHDRData->StoredUncompressedData->GetArray(); FullHDRData->StoredUncompressedData->UpdateMemoryTracking(); } else { Ar << FullHDRData->CompressedCapturedData; INC_MEMORY_STAT_BY(STAT_ReflectionCaptureMemory, FullHDRData->CompressedCapturedData.GetAllocatedSize()); } } else { check(CurrentFormat == EncodedHDR); EncodedHDRDerivedData = new FReflectionCaptureEncodedHDRDerivedData(); Ar << EncodedHDRDerivedData->CapturedData->GetArray(); EncodedHDRDerivedData->CapturedData->UpdateMemoryTracking(); } } else if (CurrentFormat == EncodedHDR) { // Temporary warning until the cooker can do scene captures itself in the case of missing DDC UE_LOG(LogMaterial, Error, TEXT(""Reflection capture was loaded without any valid capture data and will be black. This can happen if the DDC was not up to date during cooking."")); UE_LOG(LogMaterial, Error, TEXT(""Load the map in the editor once before cooking to fix. %s.""), *GetFullName()); } } } } else { SerializeSourceData(Ar); } } void UReflectionCaptureComponent::PostLoad() { Super::PostLoad(); bool bRetainAllFeatureLevelData = GIsEditor && GMaxRHIFeatureLevel >= ERHIFeatureLevel::SM4; bool bEncodedDataRequired = bRetainAllFeatureLevelData || (GMaxRHIFeatureLevel == ERHIFeatureLevel::ES2 || GMaxRHIFeatureLevel == ERHIFeatureLevel::ES3_1); bool bFullDataRequired = GMaxRHIFeatureLevel >= ERHIFeatureLevel::SM4; const int32 ReflectionCaptureSize = UReflectionCaptureComponent::GetReflectionCaptureSize_GameThread(); // If we're loading on a platform that doesn't require cooked data, attempt to load missing data from the DDC if (!FPlatformProperties::RequiresCookedData()) { // if we don't have the FullHDRData then recapture it since we are on a platform that can capture it. if (!FullHDRData || FullHDRData->CubemapSize != ReflectionCaptureSize || (EncodedHDRDerivedData && FullHDRData->CubemapSize != EncodedHDRDerivedData->CalculateCubemapDimension())) { bDerivedDataDirty = true; delete FullHDRData; FullHDRData = nullptr; EncodedHDRDerivedData = nullptr; } // If we have full HDR data but not encoded HDR data, generate the encoded data now if (FullHDRData && !EncodedHDRDerivedData && bEncodedDataRequired) { EncodedHDRDerivedData = FReflectionCaptureEncodedHDRDerivedData::GenerateEncodedHDRData(*FullHDRData, StateId, Brightness); } } // Initialize rendering resources for the current feature level, and toss data only needed by other feature levels (unless in editor mode, in which all feature level data should be resident.) if (FullHDRData && bFullDataRequired) { // Don't need encoded HDR data for rendering on this feature level INC_MEMORY_STAT_BY(STAT_ReflectionCaptureMemory, FullHDRData->CompressedCapturedData.GetAllocatedSize()); if (GMaxRHIFeatureLevel == ERHIFeatureLevel::SM4) { SM4FullHDRCubemapTexture = new FReflectionTextureCubeResource(); SM4FullHDRCubemapTexture->SetupParameters(FullHDRData->CubemapSize, FMath::CeilLogTwo(FullHDRData->CubemapSize) + 1, PF_FloatRGBA, FullHDRData->GetCapturedDataForSM4Load() ); BeginInitResource(SM4FullHDRCubemapTexture); } if (!bEncodedDataRequired) { EncodedHDRDerivedData = nullptr; } } if (EncodedHDRDerivedData && bEncodedDataRequired) { int32 EncodedCubemapSize = EncodedHDRDerivedData->CalculateCubemapDimension(); if (EncodedCubemapSize == ReflectionCaptureSize) { // Create a cubemap texture out of the encoded HDR data EncodedHDRCubemapTexture = new FReflectionTextureCubeResource(); EncodedHDRCubemapTexture->SetupParameters(EncodedCubemapSize, FMath::CeilLogTwo(EncodedCubemapSize) + 1, PF_B8G8R8A8, EncodedHDRDerivedData->CapturedData); BeginInitResource(EncodedHDRCubemapTexture); } else { UE_LOG( LogMaterial, Error, TEXT(""Encoded reflection caputure resolution and project setting mismatch.\\n(Project Setting: %d, Encoded Reflection Capture: %d.\\nReflection cubemaps will be unavailable and cooking will fail.""), CVarReflectionCaptureSize.GetValueOnGameThread(), EncodedCubemapSize ); } // free up the full hdr data if we no longer need it. if (FullHDRData && !bFullDataRequired) { delete FullHDRData; FullHDRData = NULL; } } } void UReflectionCaptureComponent::PreSave(const class ITargetPlatform* TargetPlatform) { Super::PreSave(TargetPlatform); // This is done on save of the package, because this capture data can only be generated by the renderer // So we must make efforts to ensure that it is generated in the editor, because it can't be generated during cooking when missing // Note: This will only work when registered UWorld* World = GetWorld(); if (World) { ReadbackFromGPU(World); } } void UReflectionCaptureComponent::PostDuplicate(bool bDuplicateForPIE) { if (!bDuplicateForPIE) { // Reset the StateId on duplication since it needs to be unique for each capture. // PostDuplicate covers direct calls to StaticDuplicateObject, but not actor duplication (see PostEditImport) FPlatformMisc::CreateGuid(StateId); } } void UReflectionCaptureComponent::UpdateDerivedData(FReflectionCaptureFullHDR* NewDerivedData) { #if UE_SERVER delete FullHDRData; #else if (FullHDRData) { // Delete the derived data on the rendering thread, since the rendering thread may be reading from its contents in FScene::UpdateReflectionCaptureContents ENQUEUE_UNIQUE_RENDER_COMMAND_ONEPARAMETER( DeleteCaptureDataCommand, FReflectionCaptureFullHDR*, FullHDRData, FullHDRData, { delete FullHDRData; }); } #endif FullHDRData = NewDerivedData; } FReflectionCaptureProxy* UReflectionCaptureComponent::CreateSceneProxy() { return new FReflectionCaptureProxy(this); } void UReflectionCaptureComponent::UpdatePreviewShape() { if (CaptureOffsetComponent) { CaptureOffsetComponent->RelativeLocation = CaptureOffset / GetComponentTransform().GetScale3D(); } } #if WITH_EDITOR bool UReflectionCaptureComponent::CanEditChange(const UProperty* Property) const { bool bCanEditChange = Super::CanEditChange(Property); if (Property->GetFName() == GET_MEMBER_NAME_CHECKED(UReflectionCaptureComponent, Cubemap) || Property->GetFName() == GET_MEMBER_NAME_CHECKED(UReflectionCaptureComponent, SourceCubemapAngle)) { bCanEditChange &= ReflectionSourceType == EReflectionSourceType::SpecifiedCubemap; } return bCanEditChange; } void UReflectionCaptureComponent::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) { // AActor::PostEditChange will ForceUpdateComponents() Super::PostEditChangeProperty(PropertyChangedEvent); if (PropertyChangedEvent.Property && (PropertyChangedEvent.Property->GetFName() == GET_MEMBER_NAME_CHECKED(UReflectionCaptureComponent, bVisible) || (PropertyChangedEvent.MemberProperty && PropertyChangedEvent.MemberProperty->GetFName() == GET_MEMBER_NAME_CHECKED(UReflectionCaptureComponent, CaptureOffset)))) { SetCaptureIsDirty(); } } void UReflectionCaptureComponent::PostEditImport() { Super::PostEditImport(); // Generate a new StateId. This is needed to cover actor duplication through alt-drag or copy-paste. SetCaptureIsDirty(); } #endif // WITH_EDITOR void UReflectionCaptureComponent::BeginDestroy() { // Deregister the component from the update queue if (bCaptureDirty) { FScopeLock Lock(&ReflectionCapturesToUpdateForLoadLock); ReflectionCapturesToUpdate.Remove(this); ReflectionCapturesToUpdateForLoad.Remove(this); } // Have to do this because we can't use GetWorld in BeginDestroy for (TSet::TConstIterator SceneIt(GetRendererModule().GetAllocatedScenes()); SceneIt; ++SceneIt) { FSceneInterface* Scene = *SceneIt; Scene->ReleaseReflectionCubemap(this); } if (SM4FullHDRCubemapTexture) { BeginReleaseResource(SM4FullHDRCubemapTexture); } if (EncodedHDRCubemapTexture) { BeginReleaseResource(EncodedHDRCubemapTexture); } // Begin a fence to track the progress of the above BeginReleaseResource being completed on the RT ReleaseResourcesFence.BeginFence(); Super::BeginDestroy(); } bool UReflectionCaptureComponent::IsReadyForFinishDestroy() { // Wait until the fence is complete before allowing destruction return Super::IsReadyForFinishDestroy() && ReleaseResourcesFence.IsFenceComplete(); } void UReflectionCaptureComponent::FinishDestroy() { UpdateDerivedData(NULL); if (SM4FullHDRCubemapTexture) { delete SM4FullHDRCubemapTexture; SM4FullHDRCubemapTexture = NULL; } if (EncodedHDRCubemapTexture) { delete EncodedHDRCubemapTexture; EncodedHDRCubemapTexture = NULL; } Super::FinishDestroy(); } void UReflectionCaptureComponent::SetCaptureIsDirty() { if (bVisible) { UpdateDerivedData(NULL); FPlatformMisc::CreateGuid(StateId); bDerivedDataDirty = true; ReflectionCapturesToUpdate.AddUnique(this); bCaptureDirty = true; } } void ReadbackFromSM4Cubemap_RenderingThread(FRHICommandListImmediate& RHICmdList, FReflectionTextureCubeResource* SM4FullHDRCubemapTexture, FReflectionCaptureFullHDR* OutDerivedData, int32 CubemapSize) { const int32 EffectiveTopMipSize = CubemapSize; const int32 NumMips = FMath::CeilLogTwo(EffectiveTopMipSize) + 1; TArray CaptureData; int32 CaptureDataSize = 0; for (int32 MipIndex = 0; MipIndex < NumMips; MipIndex++) { const int32 MipSize = 1 << (NumMips - MipIndex - 1); for (int32 CubeFace = 0; CubeFace < CubeFace_MAX; CubeFace++) { CaptureDataSize += MipSize * MipSize * sizeof(FFloat16Color); } } CaptureData.Empty(CaptureDataSize); CaptureData.AddZeroed(CaptureDataSize); int32 MipBaseIndex = 0; for (int32 MipIndex = 0; MipIndex < NumMips; MipIndex++) { check(SM4FullHDRCubemapTexture->GetTextureRHI()->GetFormat() == PF_FloatRGBA); const int32 MipSize = 1 << (NumMips - MipIndex - 1); const int32 CubeFaceBytes = MipSize * MipSize * sizeof(FFloat16Color); for (int32 CubeFace = 0; CubeFace < CubeFace_MAX; CubeFace++) { TArray SurfaceData; // Read each mip face //@todo - do this without blocking the GPU so many times //@todo - pool the temporary textures in RHIReadSurfaceFloatData instead of always creating new ones RHICmdList.ReadSurfaceFloatData(SM4FullHDRCubemapTexture->GetTextureRHI(), FIntRect(0, 0, MipSize, MipSize), SurfaceData, (ECubeFace)CubeFace, 0, MipIndex); const int32 DestIndex = MipBaseIndex + CubeFace * CubeFaceBytes; uint8* FaceData = &CaptureData[DestIndex]; check(SurfaceData.Num() * SurfaceData.GetTypeSize() == CubeFaceBytes); FMemory::Memcpy(FaceData, SurfaceData.GetData(), CubeFaceBytes); } MipBaseIndex += CubeFaceBytes * CubeFace_MAX; } OutDerivedData->InitializeFromUncompressedData(CaptureData, EffectiveTopMipSize); } void ReadbackFromSM4Cubemap(FReflectionTextureCubeResource* SM4FullHDRCubemapTexture, FReflectionCaptureFullHDR* OutDerivedData, int32 CubemapSize) { ENQUEUE_UNIQUE_RENDER_COMMAND_THREEPARAMETER( ReadbackReflectionData, FReflectionTextureCubeResource*, SM4FullHDRCubemapTexture, SM4FullHDRCubemapTexture, FReflectionCaptureFullHDR*, OutDerivedData, OutDerivedData, int32, CubemapSize, CubemapSize, { ReadbackFromSM4Cubemap_RenderingThread(RHICmdList, SM4FullHDRCubemapTexture, OutDerivedData, CubemapSize); }); FlushRenderingCommands(); } void UReflectionCaptureComponent::ReadbackFromGPU(UWorld* WorldToUpdate) { if (WorldToUpdate == nullptr || WorldToUpdate->Scene == nullptr) { // This can happen during autosave return; } if (bDerivedDataDirty && (!IsRunningCommandlet() || IsAllowCommandletRendering()) && WorldToUpdate && WorldToUpdate->FeatureLevel >= ERHIFeatureLevel::SM4) { FReflectionCaptureFullHDR* NewDerivedData = new FReflectionCaptureFullHDR(); if (WorldToUpdate->FeatureLevel == ERHIFeatureLevel::SM4) { if (SM4FullHDRCubemapTexture) { ensure(SM4FullHDRCubemapTexture->GetSizeX() == SM4FullHDRCubemapTexture->GetSizeY()); ReadbackFromSM4Cubemap(SM4FullHDRCubemapTexture, NewDerivedData, int32(SM4FullHDRCubemapTexture->GetSizeX())); } } else { WorldToUpdate->Scene->GetReflectionCaptureData(this, *NewDerivedData); } if (NewDerivedData->CompressedCapturedData.Num() > 0) { // Update our copy in memory UpdateDerivedData(NewDerivedData); } else { delete NewDerivedData; } } } void UReflectionCaptureComponent::UpdateReflectionCaptureContents(UWorld* WorldToUpdate) { if (WorldToUpdate->Scene // Don't capture and read back capture contents if we are currently doing async shader compiling // This will keep the update requests in the queue until compiling finishes // Note: this will also prevent uploads of cubemaps from DDC, which is unintentional && (GShaderCompilingManager == NULL || !GShaderCompilingManager->IsCompiling())) { TArray WorldCombinedCaptures; for (int32 CaptureIndex = ReflectionCapturesToUpdate.Num() - 1; CaptureIndex >= 0; CaptureIndex--) { UReflectionCaptureComponent* CaptureComponent = ReflectionCapturesToUpdate[CaptureIndex]; if (!CaptureComponent->GetOwner() || WorldToUpdate->ContainsActor(CaptureComponent->GetOwner())) { WorldCombinedCaptures.Add(CaptureComponent); ReflectionCapturesToUpdate.RemoveAt(CaptureIndex); } } TArray WorldCapturesToUpdateForLoad; if (ReflectionCapturesToUpdateForLoad.Num() > 0) { FScopeLock Lock(&ReflectionCapturesToUpdateForLoadLock); for (int32 CaptureIndex = ReflectionCapturesToUpdateForLoad.Num() - 1; CaptureIndex >= 0; CaptureIndex--) { UReflectionCaptureComponent* CaptureComponent = ReflectionCapturesToUpdateForLoad[CaptureIndex]; if (!CaptureComponent->GetOwner() || WorldToUpdate->ContainsActor(CaptureComponent->GetOwner())) { WorldCombinedCaptures.Add(CaptureComponent); WorldCapturesToUpdateForLoad.Add(CaptureComponent); ReflectionCapturesToUpdateForLoad.RemoveAt(CaptureIndex); } } } const auto FeatureLevel = WorldToUpdate->Scene->GetFeatureLevel(); if (FeatureLevel == ERHIFeatureLevel::SM4) { for (int32 CaptureIndex = 0; CaptureIndex < WorldCombinedCaptures.Num(); CaptureIndex++) { UReflectionCaptureComponent* ReflectionComponent = WorldCombinedCaptures[CaptureIndex]; if (!ReflectionComponent->SM4FullHDRCubemapTexture) { const int32 ReflectionCaptureSize = UReflectionCaptureComponent::GetReflectionCaptureSize_GameThread(); // Create the cubemap if it wasn't already - this happens when updating a reflection capture that doesn't have valid DDC ReflectionComponent->SM4FullHDRCubemapTexture = new FReflectionTextureCubeResource(); ReflectionComponent->SM4FullHDRCubemapTexture->SetupParameters(ReflectionCaptureSize, FMath::CeilLogTwo(ReflectionCaptureSize) + 1, PF_FloatRGBA, nullptr); BeginInitResource(ReflectionComponent->SM4FullHDRCubemapTexture); ReflectionComponent->MarkRenderStateDirty(); } } } WorldToUpdate->Scene->AllocateReflectionCaptures(WorldCombinedCaptures); if (FeatureLevel >= ERHIFeatureLevel::SM4 && !FPlatformProperties::RequiresCookedData()) { for (int32 CaptureIndex = 0; CaptureIndex < WorldCapturesToUpdateForLoad.Num(); CaptureIndex++) { // Save the derived data for any captures that were dirty on load // This allows the derived data to get cached without having to resave a map WorldCapturesToUpdateForLoad[CaptureIndex]->ReadbackFromGPU(WorldToUpdate); } } } } #if WITH_EDITOR void UReflectionCaptureComponent::PreFeatureLevelChange(ERHIFeatureLevel::Type PendingFeatureLevel) { if (PendingFeatureLevel == ERHIFeatureLevel::ES2 || PendingFeatureLevel == ERHIFeatureLevel::ES3_1) { // generate encoded hdr data for ES2 preview mode. UWorld* World = GetWorld(); if (World != nullptr) { // Capture full hdr derived data first. ReadbackFromGPU(World); } if (FullHDRData) { EncodedHDRDerivedData = FReflectionCaptureEncodedHDRDerivedData::GenerateEncodedHDRData(*FullHDRData, StateId, Brightness); if (EncodedHDRCubemapTexture == nullptr) { EncodedHDRCubemapTexture = new FReflectionTextureCubeResource(); } int32 EncodedCubemapSize = EncodedHDRDerivedData->CalculateCubemapDimension(); EncodedHDRCubemapTexture->SetupParameters(EncodedCubemapSize, FMath::CeilLogTwo(EncodedCubemapSize) + 1, PF_B8G8R8A8, EncodedHDRDerivedData->CapturedData); BeginInitResource(EncodedHDRCubemapTexture); } } else { EncodedHDRDerivedData = nullptr; if (EncodedHDRCubemapTexture) { BeginReleaseResource(EncodedHDRCubemapTexture); FlushRenderingCommands(); delete EncodedHDRCubemapTexture; EncodedHDRCubemapTexture = nullptr; } // for >= SM4 capture should be updated. SetCaptureIsDirty(); } if (PendingFeatureLevel == ERHIFeatureLevel::SM4) { if (SM4FullHDRCubemapTexture == nullptr) { const int32 ReflectionCaptureSize = UReflectionCaptureComponent::GetReflectionCaptureSize_GameThread(); SM4FullHDRCubemapTexture = new FReflectionTextureCubeResource(); SM4FullHDRCubemapTexture->SetupParameters(ReflectionCaptureSize, FMath::CeilLogTwo(ReflectionCaptureSize) + 1, PF_FloatRGBA, nullptr); BeginInitResource(SM4FullHDRCubemapTexture); } } else { // release SM4 texture if (SM4FullHDRCubemapTexture != nullptr) { BeginReleaseResource(SM4FullHDRCubemapTexture); FlushRenderingCommands(); delete SM4FullHDRCubemapTexture; SM4FullHDRCubemapTexture = nullptr; } } } #endif // WITH_EDITOR USphereReflectionCaptureComponent::USphereReflectionCaptureComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { InfluenceRadius = 3000; } void USphereReflectionCaptureComponent::UpdatePreviewShape() { if (PreviewInfluenceRadius) { PreviewInfluenceRadius->InitSphereRadius(InfluenceRadius); } Super::UpdatePreviewShape(); } #if WITH_EDITOR void USphereReflectionCaptureComponent::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) { // AActor::PostEditChange will ForceUpdateComponents() Super::PostEditChangeProperty(PropertyChangedEvent); if (PropertyChangedEvent.Property && (PropertyChangedEvent.Property->GetFName() == GET_MEMBER_NAME_CHECKED(USphereReflectionCaptureComponent, InfluenceRadius))) { SetCaptureIsDirty(); } } #endif // WITH_EDITOR UBoxReflectionCaptureComponent::UBoxReflectionCaptureComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { BoxTransitionDistance = 100; } void UBoxReflectionCaptureComponent::UpdatePreviewShape() { if (PreviewCaptureBox) { PreviewCaptureBox->InitBoxExtent(((GetComponentTransform().GetScale3D() - FVector(BoxTransitionDistance)) / GetComponentTransform().GetScale3D()).ComponentMax(FVector::ZeroVector)); } Super::UpdatePreviewShape(); } float UBoxReflectionCaptureComponent::GetInfluenceBoundingRadius() const { return (GetComponentTransform().GetScale3D() + FVector(BoxTransitionDistance)).Size(); } #if WITH_EDITOR void UBoxReflectionCaptureComponent::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) { // AActor::PostEditChange will ForceUpdateComponents() Super::PostEditChangeProperty(PropertyChangedEvent); if (PropertyChangedEvent.Property && PropertyChangedEvent.Property->GetFName() == GET_MEMBER_NAME_CHECKED(UBoxReflectionCaptureComponent, BoxTransitionDistance)) { SetCaptureIsDirty(); } } #endif // WITH_EDITOR UPlaneReflectionCaptureComponent::UPlaneReflectionCaptureComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { InfluenceRadiusScale = 2; } void UPlaneReflectionCaptureComponent::UpdatePreviewShape() { if (PreviewInfluenceRadius) { PreviewInfluenceRadius->InitSphereRadius(GetInfluenceBoundingRadius()); } Super::UpdatePreviewShape(); } float UPlaneReflectionCaptureComponent::GetInfluenceBoundingRadius() const { return FVector2D(GetComponentTransform().GetScale3D().Y, GetComponentTransform().GetScale3D().Z).Size() * InfluenceRadiusScale; } FReflectionCaptureProxy::FReflectionCaptureProxy(const UReflectionCaptureComponent* InComponent) { PackedIndex = INDEX_NONE; CaptureOffset = InComponent->CaptureOffset; const USphereReflectionCaptureComponent* SphereComponent = Cast(InComponent); const UBoxReflectionCaptureComponent* BoxComponent = Cast(InComponent); const UPlaneReflectionCaptureComponent* PlaneComponent = Cast(InComponent); // Initialize shape specific settings Shape = EReflectionCaptureShape::Num; BoxTransitionDistance = 0; if (SphereComponent) { Shape = EReflectionCaptureShape::Sphere; } else if (BoxComponent) { Shape = EReflectionCaptureShape::Box; BoxTransitionDistance = BoxComponent->BoxTransitionDistance; } else if (PlaneComponent) { Shape = EReflectionCaptureShape::Plane; } else { check(0); } // Initialize common settings Component = InComponent; SM4FullHDRCubemap = InComponent->SM4FullHDRCubemapTexture; EncodedHDRCubemap = InComponent->EncodedHDRCubemapTexture; SetTransform(InComponent->GetComponentTransform().ToMatrixWithScale()); InfluenceRadius = InComponent->GetInfluenceBoundingRadius(); Brightness = InComponent->Brightness; Guid = GetTypeHash( Component->GetPathName() ); AverageBrightness = 1.0f; ENQUEUE_UNIQUE_RENDER_COMMAND_TWOPARAMETER( FInitReflectionProxy, const float*,AverageBrightness,InComponent->GetAverageBrightnessPtr(), FReflectionCaptureProxy*,ReflectionCaptureProxy,this, { // Only access AverageBrightness on the RT, even though they belong to the UReflectionCaptureComponent, // Because FScene::UpdateReflectionCaptureContents does not block the RT so the writes could still be in flight ReflectionCaptureProxy->InitializeAverageBrightness(*AverageBrightness); }); } void FReflectionCaptureProxy::InitializeAverageBrightness(const float& InAverageBrightness) { AverageBrightness = InAverageBrightness; } void FReflectionCaptureProxy::SetTransform(const FMatrix& InTransform) { Position = InTransform.GetOrigin(); BoxTransform = InTransform.Inverse(); FVector ForwardVector(1.0f,0.0f,0.0f); FVector RightVector(0.0f,-1.0f,0.0f); const FVector4 PlaneNormal = InTransform.TransformVector(ForwardVector); // Normalize the plane ReflectionPlane = FPlane(Position, FVector(PlaneNormal).GetSafeNormal()); const FVector ReflectionXAxis = InTransform.TransformVector(RightVector); const FVector ScaleVector = InTransform.GetScaleVector(); BoxScales = ScaleVector; // Include the owner's draw scale in the axes ReflectionXAxisAndYScale = ReflectionXAxis.GetSafeNormal() * ScaleVector.Y; ReflectionXAxisAndYScale.W = ScaleVector.Y / ScaleVector.Z; } ",16321,True,2776.7646093372487,median "[[netty-component]] = Netty Component //THIS FILE IS COPIED: EDIT THE SOURCE FILE: :page-source: components/camel-netty/src/main/docs/netty-component.adoc :docTitle: Netty :artifactId: camel-netty :description: Socket level networking using TCP or UDP with the Netty 4.x. :since: 2.14 :supportLevel: Stable :component-header: Both producer and consumer are supported include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/netty.adoc[opts=optional] *Since Camel {since}* *{component-header}* The Netty component in Camel is a socket communication component, based on the http://netty.io/[Netty] project version 4. + Netty is a NIO client server framework which enables quick and easy development of networkServerInitializerFactory applications such as protocol servers and clients. + Netty greatly simplifies and streamlines network programming such as TCP and UDP socket server. This camel component supports both producer and consumer endpoints. The Netty component has several options and allows fine-grained control of a number of TCP/UDP communication parameters (buffer sizes, keepAlives, tcpNoDelay, etc) and facilitates both In-Only and In-Out communication on a Camel route. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ---- org.apache.camel camel-netty x.x.x ---- == URI format The URI scheme for a netty component is as follows [source,text] ---- netty:tcp://0.0.0.0:99999[?options] netty:udp://remotehost:99999/[?options] ---- This component supports producer and consumer endpoints for both TCP and UDP. You can append query options to the URI in the following format, `?option=value&option=value&...` == Options // component options: START The Netty component supports 72 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (common) | To use the NettyConfiguration as configuration when creating endpoints. | | NettyConfiguration | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this option to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *executorService* (consumer) | To use the given EventExecutorGroup. | | EventExecutorGroup | *maximumPoolSize* (consumer) | Sets a maximum thread pool size for the netty consumer ordered thread pool. The default size is 2 x cpu_core plus 1. Setting this value to eg 10 will then use 10 threads unless 2 x cpu_core plus 1 is a higher value, which then will override and be used. For example if there are 8 cores, then the consumer thread pool will be 17. This thread pool is used to route messages received from Netty by Camel. We use a separate thread pool to ensure ordering of messages and also in case some messages will block, then nettys worker threads (event loop) wont be affected. | | int | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException{zwsp}CaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictableIdle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *autowiredEnabled* (advanced) | Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty (which is cpu_core_threads x 2). User can use this option to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. There are 2 enums and the value can be one of: LINE, NULL | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP - however only Strings are allowed to be serialized by default. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *useGlobalSslContextParameters* (security) | Enable usage of global SSL context parameters. | false | boolean |=== // component options: END // endpoint options: START The Netty endpoint is configured using URI syntax: ---- netty:protocol:host:port ---- with the following path and query parameters: === Path Parameters (3 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *protocol* | *Required* The protocol to use which can be tcp or udp. There are 2 enums and the value can be one of: tcp, udp | | String | *host* | *Required* The hostname. For the consumer the hostname is localhost or 0.0.0.0. For the producer the hostname is the remote host to connect to | | String | *port* | *Required* The host port number | | int |=== === Query Parameters (70 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this option to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException{zwsp}CaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictableIdle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used | false | boolean | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty (which is cpu_core_threads x 2). User can use this option to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. There are 2 enums and the value can be one of: LINE, NULL | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP - however only Strings are allowed to be serialized by default. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String |=== // endpoint options: END == Registry based Options Codec Handlers and SSL Keystores can be enlisted in the Registry, such as in the Spring XML file. The values that could be passed in, are the following: [width=""100%"",cols=""10%,90%"",options=""header"",] |=== |Name |Description |`passphrase` |password setting to use in order to encrypt/decrypt payloads sent using SSH |`keyStoreFormat` |keystore format to be used for payload encryption. Defaults to ""JKS"" if not set |`securityProvider` |Security provider to be used for payload encryption. Defaults to ""SunX509"" if not set. |`keyStoreFile` |*deprecated:* Client side certificate keystore to be used for encryption |`trustStoreFile` |*deprecated:* Server side certificate keystore to be used for encryption |`keyStoreResource` |Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`trustStoreResource` |Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`sslHandler` |Reference to a class that could be used to return an SSL Handler |`encoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of outbound payloads. Must override io.netty.channel.ChannelInboundHandlerAdapter. |`encoders` |A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |`decoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of inbound payloads. Must override io.netty.channel.ChannelOutboundHandlerAdapter. |`decoders` |A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |=== [NOTE] ==== Read below about using non shareable encoders/decoders. ==== === Using non shareable encoders or decoders If your encoders or decoders are not shareable (e.g. they don't have the @Shareable class annotation), then your encoder/decoder must implement the `org.apache.camel.component.netty.ChannelHandlerFactory` interface, and return a new instance in the `newChannelHandler` method. This is to ensure the encoder/decoder can safely be used. If this is not the case, then the Netty component will log a WARN when an endpoint is created. The Netty component offers a `org.apache.camel.component.netty.ChannelHandlerFactories` factory class, that has a number of commonly used methods. == Sending Messages to/from a Netty endpoint === Netty Producer In Producer mode, the component provides the ability to send payloads to a socket endpoint using either TCP or UDP protocols (with optional SSL support). The producer mode supports both one-way and request-response based operations. === Netty Consumer In Consumer mode, the component provides the ability to: * listen on a specified socket using either TCP or UDP protocols (with optional SSL support), * receive requests on the socket using text/xml, binary and serialized object based payloads and * send them along on a route as message exchanges. The consumer mode supports both one-way and request-response based operations. == Examples === A UDP Netty endpoint using Request-Reply and serialized object payload Note that Object serialization is not allowed by default, and so a decoder must be configured. [source,java] ---- @BindToRegistry(""decoder"") public ChannelHandler getDecoder() throws Exception { return new DefaultChannelHandlerFactory() { @Override public ChannelHandler newChannelHandler() { return new DatagramPacketObjectDecoder(ClassResolvers.weakCachingResolver(null)); } }; } RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:udp://0.0.0.0:5155?sync=true&decoders=#decoder"") .process(new Processor() { public void process(Exchange exchange) throws Exception { Poetry poetry = (Poetry) exchange.getIn().getBody(); // Process poetry in some way exchange.getOut().setBody(""Message received); } } } }; ---- === A TCP based Netty consumer endpoint using One-way communication [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:tcp://0.0.0.0:5150"") .to(""mock:result""); } }; ---- === An SSL/TCP based Netty consumer endpoint using Request-Reply communication [[Netty-UsingtheJSSEConfigurationUtility]] Using the JSSE Configuration Utility The Netty component supports SSL/TLS configuration through the xref:manual::camel-configuration-utilities.adoc[Camel JSSE Configuration Utility]. This utility greatly decreases the amount of component specific code you need to write and is configurable at the endpoint and component levels. The following examples demonstrate how to use the utility with the Netty component. [[Netty-Programmaticconfigurationofthecomponent]] Programmatic configuration of the component [source,java] ---- KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource(""/users/home/server/keystore.jks""); ksp.setPassword(""keystorePassword""); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword(""keyPassword""); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); NettyComponent nettyComponent = getContext().getComponent(""netty"", NettyComponent.class); nettyComponent.setSslContextParameters(scp); ---- [[Netty-SpringDSLbasedconfigurationofendpoint]] Spring DSL based configuration of endpoint [source,xml] ---- ... ... ... ... ---- [[Netty-UsingBasicSSLTLSconfigurationontheJettyComponent]] Using Basic SSL/TLS configuration on the Jetty Component [source,java] ---- Registry registry = context.getRegistry(); registry.bind(""password"", ""changeit""); registry.bind(""ksf"", new File(""src/test/resources/keystore.jks"")); registry.bind(""tsf"", new File(""src/test/resources/keystore.jks"")); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?sync=true&ssl=true&passphrase=#password"" + ""&keyStoreFile=#ksf&trustStoreFile=#tsf""; String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- [[Netty-GettingaccesstoSSLSessionandtheclientcertificate]] Getting access to SSLSession and the client certificate You can get access to the `javax.net.ssl.SSLSession` if you eg need to get details about the client certificate. When `ssl=true` then the xref:netty-component.adoc[Netty] component will store the `SSLSession` as a header on the Camel Message as shown below: [source,java] ---- SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class); // get the first certificate which is client certificate javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0]; Principal principal = cert.getSubjectDN(); ---- Remember to set `needClientAuth=true` to authenticate the client, otherwise `SSLSession` cannot access information about the client certificate, and you may get an exception `javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated`. You may also get this exception if the client certificate is expired or not valid etc. [TIP] ==== The option `sslClientCertHeaders` can be set to `true` which then enriches the Camel Message with headers having details about the client certificate. For example the subject name is readily available in the header `CamelNettySSLClientCertSubjectName`. ==== === Using Multiple Codecs In certain cases it may be necessary to add chains of encoders and decoders to the netty pipeline. To add multpile codecs to a camel netty endpoint the 'encoders' and 'decoders' uri parameters should be used. Like the 'encoder' and 'decoder' parameters they are used to supply references (lists of ChannelUpstreamHandlers and ChannelDownstreamHandlers) that should be added to the pipeline. Note that if encoders is specified then the encoder param will be ignored, similarly for decoders and the decoder param. [NOTE] ==== Read further above about using non shareable encoders/decoders. ==== The lists of codecs need to be added to the Camel's registry so they can be resolved when the endpoint is created. [source,java] ---- ChannelHandlerFactory lengthDecoder = ChannelHandlerFactories.newLengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4); StringDecoder stringDecoder = new StringDecoder(); registry.bind(""length-decoder"", lengthDecoder); registry.bind(""string-decoder"", stringDecoder); LengthFieldPrepender lengthEncoder = new LengthFieldPrepender(4); StringEncoder stringEncoder = new StringEncoder(); registry.bind(""length-encoder"", lengthEncoder); registry.bind(""string-encoder"", stringEncoder); List decoders = new ArrayList(); decoders.add(lengthDecoder); decoders.add(stringDecoder); List encoders = new ArrayList(); encoders.add(lengthEncoder); encoders.add(stringEncoder); registry.bind(""encoders"", encoders); registry.bind(""decoders"", decoders); ---- Spring's native collections support can be used to specify the codec lists in an application context [source,xml] ---- ---- The bean names can then be used in netty endpoint definitions either as a comma separated list or contained in a List e.g. [source,java] ---- from(""direct:multiple-codec"").to(""netty:tcp://0.0.0.0:{{port}}?encoders=#encoders&sync=false""); from(""netty:tcp://0.0.0.0:{{port}}?decoders=#length-decoder,#string-decoder&sync=false"").to(""mock:multiple-codec""); ---- or via XML. [source,xml] ---- ---- == Closing Channel When Complete When acting as a server you sometimes want to close the channel when, for example, a client conversion is finished. + You can do this by simply setting the endpoint option `disconnect=true`. However you can also instruct Camel on a per message basis as follows. + To instruct Camel to close the channel, you should add a header with the key `CamelNettyCloseChannelWhenComplete` set to a boolean `true` value. + For instance, the example below will close the channel after it has written the bye message back to the client: [source,java] ---- from(""netty:tcp://0.0.0.0:8080"").process(new Processor() { public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); exchange.getOut().setBody(""Bye "" + body); // some condition which determines if we should close if (close) { exchange.getOut().setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true); } } }); ---- [[Netty-Addingcustomchannelpipelinefactoriestogaincompletecontroloveracreatedpipeline]] Adding custom channel pipeline factories to gain complete control over a created pipeline == Custom pipeline Custom channel pipelines provide complete control to the user over the handler/interceptor chain by inserting custom handler(s), encoder(s) & decoder(s) without having to specify them in the Netty Endpoint URL in a very simple way. In order to add a custom pipeline, a custom channel pipeline factory must be created and registered with the context via the context registry (Registry, or the camel-spring ApplicationContextRegistry etc). A custom pipeline factory must be constructed as follows * A Producer linked channel pipeline factory must extend the abstract class `ClientPipelineFactory`. * A Consumer linked channel pipeline factory must extend the abstract class `ServerInitializerFactory`. * The classes should override the initChannel() method in order to insert custom handler(s), encoder(s) and decoder(s). Not overriding the `initChannel()` method creates a pipeline with no handlers, encoders or decoders wired to the pipeline. The example below shows how ServerInitializerFactory factory may be created === Using custom pipeline factory [source,java] ---- public class SampleServerInitializerFactory extends ServerInitializerFactory { private int maxLineSize = 1024; protected void initChannel(Channel ch) throws Exception { ChannelPipeline channelPipeline = ch.pipeline(); channelPipeline.addLast(""encoder-SD"", new StringEncoder(CharsetUtil.UTF_8)); channelPipeline.addLast(""decoder-DELIM"", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter())); channelPipeline.addLast(""decoder-SD"", new StringDecoder(CharsetUtil.UTF_8)); // here we add the default Camel ServerChannelHandler for the consumer, to allow Camel to route the message etc. channelPipeline.addLast(""handler"", new ServerChannelHandler(consumer)); } } ---- The custom channel pipeline factory can then be added to the registry and instantiated/utilized on a camel route in the following way [source,java] ---- Registry registry = camelContext.getRegistry(); ServerInitializerFactory factory = new TestServerInitializerFactory(); registry.bind(""spf"", factory); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?serverInitializerFactory=#spf"" String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- == Reusing Netty boss and worker thread pools Netty has two kind of thread pools: boss and worker. By default each Netty consumer and producer has their private thread pools. If you want to reuse these thread pools among multiple consumers or producers then the thread pools must be created and enlisted in the Registry. For example using Spring XML we can create a shared worker thread pool using the `NettyWorkerPoolBuilder` with 2 worker threads as shown below: [source,xml] ---- ---- [TIP] ==== For boss thread pool there is a `org.apache.camel.component.netty.NettyServerBossPoolBuilder` builder for Netty consumers, and a `org.apache.camel.component.netty.NettyClientBossPoolBuilder` for the Netty producers. ==== Then in the Camel routes we can refer to this worker pools by configuring the `workerPool` option in the URI as shown below: [source,xml] ---- ... ---- And if we have another route we can refer to the shared worker pool: [source,xml] ---- ... ---- and so forth. == Multiplexing concurrent messages over a single connection with request/reply When using Netty for request/reply messaging via the netty producer then by default each message is sent via a non-shared connection (pooled). This ensures that replies are automatic being able to map to the correct request thread for further routing in Camel. In other words correlation between request/reply messages happens out-of-the-box because the replies comes back on the same connection that was used for sending the request; and this connection is not shared with others. When the response comes back, the connection is returned back to the connection pool, where it can be reused by others. However if you want to multiplex concurrent request/responses on a single shared connection, then you need to turn off the connection pooling by setting `producerPoolEnabled=false`. Now this means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement `NettyCamelStateCorrelationManager` as correlation manager and configure it via the `correlationManager=#myManager` option. [NOTE] ==== We recommend extending the `TimeoutCorrelationManagerSupport` when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. ==== You can find an example with the Apache Camel source code in the examples directory under the `camel-example-netty-custom-correlation` directory. include::camel-spring-boot::page$netty-starter.adoc[] ",12461,False,2328.3033478087054,median "== Default Parameters These parameters are configured by the ownCloud installer, and are required for your ownCloud server to operate. === instanceid This is a unique identifier for your ownCloud installation, created automatically by the installer. This example is for documentation only, and you should never use it because it will not work. A valid `instanceid` is created when you install ownCloud. Needs to start with a letter. ==== Code Sample [source,php] .... 'instanceid' => 'd3c944a9a', .... === passwordsalt The salt used to hash all passwords, auto-generated by the ownCloud installer. (There are also per-user salts.) If you lose this salt you lose all your passwords. This example is for documentation only, and you should never use it. ==== Code Sample [source,php] .... 'passwordsalt' => 'd3c944a9af095aa08f', .... === trusted_domains Your list of trusted domains that users can log into. Specifying trusted domains prevents host header poisoning. Do not remove this, as it performs necessary security checks. Please consider that for backend processes like background jobs or occ commands, the url parameter in key `overwrite.cli.url` is used. For more details please see that key. ==== Code Sample [source,php] .... 'trusted_domains' => [ 'demo.example.org', 'otherdomain.example.org', ], .... === cors.allowed-domains The global list of CORS domains. All users can use tools running CORS requests from the listed domains. ==== Code Sample [source,php] .... 'cors.allowed-domains' => [ 'https://foo.example.org', ], .... === datadirectory Where user files are stored; this defaults to `data/` in the ownCloud directory. The SQLite database is also stored here, when you use SQLite. (SQLite is not available in ownCloud Enterprise Edition). ==== Code Sample [source,php] .... 'datadirectory' => '/var/www/owncloud/data', .... === version The current version number of your ownCloud installation. This is set up during installation and update, so you shouldn't need to change it. ==== Code Sample [source,php] .... 'version' => '', .... === version.hide While hardening an ownCloud instance hiding the version information in status.php can be a legitimate step. Please consult the documentation before enabling this. ==== Code Sample [source,php] .... 'version.hide' => false, .... === show_server_hostname Optionally, show the hostname of the server in status.php. Defaults to hidden. ==== Code Sample [source,php] .... 'show_server_hostname' => false, .... === dbtype Identifies the database used with this installation. See also config option `supportedDatabases`. Supported databases: - mysql (MySQL/MariaDB) - pgsql (PostgreSQL) - sqlite (SQLite3 - Not in Enterprise Edition) - oci (Oracle - Enterprise Edition Only) ==== Code Sample [source,php] .... 'dbtype' => 'sqlite', .... === dbhost Your host server name, for example `localhost`, `hostname`, `hostname.example.com`, or the IP address. To specify a port use `hostname:####`; to specify a Unix socket use `localhost:/path/to/socket`. ==== Code Sample [source,php] .... 'dbhost' => '', .... === dbname The name of the ownCloud database, which is set during installation. You should not need to change this. ==== Code Sample [source,php] .... 'dbname' => 'owncloud', .... === dbuser The user that ownCloud uses to write to the database. This must be unique across ownCloud instances using the same SQL database. This is set up during installation, so you shouldn't need to change it. ==== Code Sample [source,php] .... 'dbuser' => '', .... === dbpassword The password for the database user. This is set up during installation, so you shouldn't need to change it. ==== Code Sample [source,php] .... 'dbpassword' => '', .... === dbtableprefix Prefix for the ownCloud tables in the database. ==== Code Sample [source,php] .... 'dbtableprefix' => '', .... === installed Indicates whether the ownCloud instance was installed successfully; `true` indicates a successful installation, and `false` indicates an unsuccessful installation. ==== Code Sample [source,php] .... 'installed' => false, .... == User Experience These optional parameters control some aspects of the user interface. Default values, where present, are shown. === default_language This sets the default language on your ownCloud server, using ISO_639-1 language codes such as `en` for English, `de` for German, and `fr` for French. It overrides automatic language detection on public pages like login or shared items. User's language preferences configured under ""personal -> language"" override this setting after they have logged in. ==== Code Sample [source,php] .... 'default_language' => 'en_GB', .... === defaultapp Set the default app to open on login. Use the app names as they appear in the URL after clicking them in the Apps menu, such as documents, calendar, and gallery. You can use a comma-separated list of app names, so if the first app is not enabled for a user then ownCloud will try the second one, and so on. If no enabled apps are found it defaults to the Files app. ==== Code Sample [source,php] .... 'defaultapp' => 'files', .... === knowledgebaseenabled `true` enables the Help menu item in the user menu (top right of the ownCloud Web interface). `false` removes the Help item. ==== Code Sample [source,php] .... 'knowledgebaseenabled' => true, .... === enable_avatars `true` enables avatars, or user profile photos. These appear on the User page, on user's Personal pages and are used by some apps (contacts, mail, etc). `false` disables them. ==== Code Sample [source,php] .... 'enable_avatars' => true, .... === allow_user_to_change_display_name `true` allows users to change their display names (on their Personal pages), and `false` prevents them from changing their display names. ==== Code Sample [source,php] .... 'allow_user_to_change_display_name' => true, .... === remember_login_cookie_lifetime Lifetime of the remember login cookie, which is set when the user clicks the `remember` checkbox on the login screen. The default is 15 days, expressed in seconds. ==== Code Sample [source,php] .... 'remember_login_cookie_lifetime' => 60*60*24*15, .... === session_lifetime The lifetime of a session after inactivity; the default is 24 hours, expressed in seconds. ==== Code Sample [source,php] .... 'session_lifetime' => 60 * 60 * 24, .... === session_keepalive Enable or disable session keep-alive when a user is logged in to the Web UI. Enabling this sends a ""heartbeat"" to the server to keep it from timing out. ==== Code Sample [source,php] .... 'session_keepalive' => true, .... === token_auth_enforced Enforces token only authentication for apps and clients connecting to ownCloud. If enabled, all access requests using the users password are blocked for enhanced security. Users have to generate special app-passwords (tokens) for their apps or clients in their personal settings which are further used for app or client authentication. Browser logon is not affected. ==== Code Sample [source,php] .... 'token_auth_enforced' => false, .... === login.alternatives Allows to specify additional login buttons on the logon screen for e.g., SSO integration. ==== Code Sample [source,php] .... 'login.alternatives' => [ [ 'href' => 'https://www.testshib.org/Shibboleth.sso/ProtectNetwork?target=https%3A%2F%2Fmy.owncloud.tld%2Flogin%2Fsso-saml%2F', 'name' => 'ProtectNetwork', 'img' => '/img/PN_sign-in.gif' ], [ 'href' => 'https://www.testshib.org/Shibboleth.sso/OpenIdP.org?target=https%3A%2F%2Fmy.owncloud.tld%2Flogin%2Fsso-saml%2F', 'name' => 'OpenIdP.org', 'img' => '/img/openidp.png' ], ], .... === csrf.disabled Disable ownCloud's built-in CSRF protection mechanism. In some specific setups CSRF protection is handled in the environment, e.g., running F5 ASM. In these cases the built-in mechanism is not needed and can be disabled. Generally speaking, however, this config switch should be left unchanged. WARNING: Leave this as is if you're not sure what it does. ==== Code Sample [source,php] .... 'csrf.disabled' => false, .... === skeletondirectory The directory where the skeleton files are located. These files will be copied to the data directory of new users. Leave empty to not copy any skeleton files. ==== Code Sample [source,php] .... 'skeletondirectory' => '/path/to/owncloud/core/skeleton', .... === user_backends The `user_backends` app (which needs to be enabled first) allows you to configure alternate authentication backends. Supported backends are: - IMAP (OC_User_IMAP) - SMB (OC_User_SMB) - FTP (OC_User_FTP) ==== Code Sample [source,php] .... 'user_backends' => [ [ 'class' => 'OC_User_IMAP', 'arguments' => [ '{imap.gmail.com:993/imap/ssl}INBOX' ] ] ], .... === lost_password_link If your user backend does not allow password resets (e.g., when it's a read-only user backend like LDAP), you can specify a custom link, where the user is redirected to, when clicking the ""reset password"" link after a failed login-attempt. In case you do not want to provide any link, replace the url with 'disabled'. ==== Code Sample [source,php] .... 'lost_password_link' => 'https://example.org/link/to/password/reset', .... === accounts.enable_medial_search Allow medial search on account properties like display name, user id, email, and other search terms. Allows finding 'Alice' when searching for 'lic'. May slow down user search. Disable this if you encounter slow username search in the sharing dialog. ==== Code Sample [source,php] .... 'accounts.enable_medial_search' => true, .... === user.search_min_length Defines the minimum characters entered before a search returns results for users or groups in the share auto-complete form. Lower values increase search time especially for large backends. Any exact matches to a user or group will be returned, even though less than the minimum characters have been entered. The search is case insensitive. e.g., entering ""tom"" will always return ""Tom"" if there is an exact match. ==== Code Sample [source,php] .... 'user.search_min_length' => 2, .... == Mail Parameters These configure the email settings for ownCloud notifications and password resets. === mail_domain The return address that you want to appear on emails sent by the ownCloud server, for example `oc-admin@example.com`, substituting your own domain, of course. ==== Code Sample [source,php] .... 'mail_domain' => 'example.com', .... === mail_from_address FROM address that overrides the built-in `sharing-noreply` and `lostpassword-noreply` FROM addresses. ==== Code Sample [source,php] .... 'mail_from_address' => 'owncloud', .... === mail_smtpdebug Enable SMTP class debugging. ==== Code Sample [source,php] .... 'mail_smtpdebug' => false, .... === mail_smtpmode Which mode to use for sending mail: `sendmail`, `smtp`, `qmail` or `php`. If you are using local or remote SMTP, set this to `smtp`. If you are using PHP mail you must have an installed and working email system on the server. The program used to send email is defined in the `php.ini` file. For the `sendmail` option you need an installed and working email system on the server, with `/usr/sbin/sendmail` installed on your Unix system. For `qmail` the binary is /var/qmail/bin/sendmail, and it must be installed on your Unix system. ==== Code Sample [source,php] .... 'mail_smtpmode' => 'sendmail', .... === mail_smtphost This depends on `mail_smtpmode`. Specify the IP address of your mail server host. This may contain multiple hosts separated by a semi-colon. If you need to specify the port number append it to the IP address separated by a colon, like this: `127.0.0.1:24`. ==== Code Sample [source,php] .... 'mail_smtphost' => '127.0.0.1', .... === mail_smtpport This depends on `mail_smtpmode`. Specify the port for sending mail. ==== Code Sample [source,php] .... 'mail_smtpport' => 25, .... === mail_smtptimeout This depends on `mail_smtpmode`. This sets the SMTP server timeout, in seconds. You may need to increase this if you are running an anti-malware or spam scanner. ==== Code Sample [source,php] .... 'mail_smtptimeout' => 10, .... === mail_smtpsecure This depends on `mail_smtpmode`. Specify when you are using `ssl` or `tls`, or leave empty for no encryption. ==== Code Sample [source,php] .... 'mail_smtpsecure' => '', .... === mail_smtpauth This depends on `mail_smtpmode`. Change this to `true` if your mail server requires authentication. ==== Code Sample [source,php] .... 'mail_smtpauth' => false, .... === mail_smtpauthtype This depends on `mail_smtpmode`. If SMTP authentication is required, choose the authentication type as `LOGIN` (default) or `PLAIN`. ==== Code Sample [source,php] .... 'mail_smtpauthtype' => 'LOGIN', .... === mail_smtpname This depends on `mail_smtpauth`. Specify the username for authenticating to the SMTP server. ==== Code Sample [source,php] .... 'mail_smtpname' => '', .... === mail_smtppassword This depends on `mail_smtpauth`. Specify the password for authenticating to the SMTP server. ==== Code Sample [source,php] .... 'mail_smtppassword' => '', .... == Proxy Configurations === overwritehost The automatic hostname detection of ownCloud can fail in certain reverse proxy and CLI/cron situations. This option allows you to manually override the automatic detection; for example `www.example.com`, or specify the port `www.example.com:8080`. ==== Code Sample [source,php] .... 'overwritehost' => '', .... === overwriteprotocol When generating URLs, ownCloud attempts to detect whether the server is accessed via `https` or `http`. However, if ownCloud is behind a proxy and the proxy handles the `https` calls, ownCloud would not know that `ssl` is in use, which would result in incorrect URLs being generated. Valid values are `http` and `https`. ==== Code Sample [source,php] .... 'overwriteprotocol' => '', .... === overwritewebroot ownCloud attempts to detect the webroot for generating URLs automatically. For example, if `www.example.com/owncloud` is the URL pointing to the ownCloud instance, the webroot is `/owncloud`. When proxies are in use, it may be difficult for ownCloud to detect this parameter, resulting in invalid URLs. ==== Code Sample [source,php] .... 'overwritewebroot' => '', .... === overwritecondaddr This option allows you to define a manual override condition as a regular expression for the remote IP address. The keys `overwritewebroot`, `overwriteprotocol`, and `overwritehost` are subject to this condition. For example, defining a range of IP addresses starting with `10.0.0.` and ending with 1 to 3: * `^10\\.0\\.0\\.[1-3]$`. ==== Code Sample [source,php] .... 'overwritecondaddr' => '', .... === overwrite.cli.url Use this configuration parameter to specify the base URL for any URLs which are generated within ownCloud using any kind of command line tools (cron or occ). The value should contain the full base URL: `https://www.example.com/owncloud`. As an example, alerts shown in the browser to upgrade an app are triggered by a cron background process and therefore uses the url of this key, even if the user has logged on via a different domain defined in key `trusted_domains`. When the user clicks an alert like this, he will be redirected to that URL and must logon again. ==== Code Sample [source,php] .... 'overwrite.cli.url' => '', .... === htaccess.RewriteBase To have clean URLs without `/index.php` this parameter needs to be configured. This parameter will be written as ""RewriteBase"" on update and installation of ownCloud to your `.htaccess` file. While this value is often simply the URL path of the ownCloud installation it cannot be set automatically properly in every scenario and needs thus some manual configuration. In a standard Apache setup this usually equals the folder that ownCloud is accessible at. So if ownCloud is accessible via ""https://mycloud.org/owncloud"" the correct value would most likely be ""/owncloud"". If ownCloud is running under ""https://mycloud.org/"" then it would be ""/"". Note that the above rule is not valid in every case, as there are some rare setup cases where this may not apply. However, to avoid any update problems this configuration value is explicitly opt-in. After setting this value run `occ maintenance:update:htaccess`. Now, when the following conditions are met ownCloud URLs won't contain `index.php`: - `mod_rewrite` is installed - `mod_env` is installed ==== Code Sample [source,php] .... 'htaccess.RewriteBase' => '/', .... === proxy The URL of your proxy server, for example `proxy.example.com:8081`. ==== Code Sample [source,php] .... 'proxy' => '', .... === proxyuserpwd The optional authentication for the proxy to use to connect to the internet. The format is: `username:password`. ==== Code Sample [source,php] .... 'proxyuserpwd' => '', .... == Deleted Items (trash bin) These parameters control the Deleted files app. === trashbin_retention_obligation If the trash bin app is enabled (default), this setting defines the policy for when files and folders in the trash bin will be permanently deleted. The app allows for two settings, a minimum time for trash bin retention, and a maximum time for trash bin retention. Minimum time is the number of days a file will be kept, after which it may be deleted. Maximum time is the number of days at which it is guaranteed to be deleted. Both minimum and maximum times can be set together to explicitly define file and folder deletion. For migration purposes, this setting is installed initially set to ""auto"", which is equivalent to the default setting in ownCloud 8.1 and before. Available values: - `auto` default setting. Keeps files and folders in the deleted files for up to 30 days, automatically deleting them (at any time) if space is needed. Note: files may not be removed if space is not required. - `D, auto` keeps files and folders in the trash bin for D+ days, delete anytime if space needed (note: files may not be deleted if space is not needed) - `auto, D` delete all files in the trash bin that are older than D days automatically, delete other files anytime if space needed - `D1, D2` keep files and folders in the trash bin for at least D1 days and delete when exceeds D2 days - `disabled` trash bin auto clean disabled, files and folders will be kept forever ==== Code Sample [source,php] .... 'trashbin_retention_obligation' => 'auto', .... === trashbin_purge_limit This setting defines percentage of free space occupied by deleted files that triggers auto purging of deleted files for this user. ==== Code Sample [source,php] .... 'trashbin_purge_limit' => 50, .... == File versions These parameters control the Versions app. === versions_retention_obligation If the versions app is enabled (default), this setting defines the policy for when versions will be permanently deleted. The app allows for two settings, a minimum time for version retention, and a maximum time for version retention. Minimum time is the number of days a version will be kept, after which it may be deleted. Maximum time is the number of days at which it is guaranteed to be deleted. Both minimum and maximum times can be set together to explicitly define version deletion. For migration purposes, this setting is installed initially set to ""auto"", which is equivalent to the default setting in ownCloud 8.1 and before. Available values: - `auto` default setting. Automatically expire versions according to expire rules. Please refer to :doc:`../configuration/files/file_versioning` for more information. - `D, auto` keep versions at least for D days, apply expire rules to all versions that are older than D days. - `auto, D` delete all versions that are older than D days automatically, delete other versions according to expire rules. - `D1, D2` keep versions for at least D1 days and delete when exceeds D2 days. - `disabled` versions auto clean disabled, versions will be kept forever. ==== Code Sample [source,php] .... 'versions_retention_obligation' => 'auto', .... == ownCloud Verifications ownCloud performs several verification checks. There are two options, `true` and `false`. === updatechecker Check if ownCloud is up-to-date and shows a notification if a new version is available. This option is only applicable to ownCloud core. It is not applicable to app updates. ==== Code Sample [source,php] .... 'updatechecker' => true, .... === updater.server.url URL that ownCloud should use to look for updates ==== Code Sample [source,php] .... 'updater.server.url' => 'https://updates.owncloud.com/server/', .... === has_internet_connection Is ownCloud connected to the Internet or running in a closed network? ==== Code Sample [source,php] .... 'has_internet_connection' => true, .... === check_for_working_wellknown_setup Allows ownCloud to verify a working .well-known URL redirects. This is done by attempting to make a request from JS to https://your-domain.com/.well-known/caldav/. ==== Code Sample [source,php] .... 'check_for_working_wellknown_setup' => true, .... === config_is_read_only In certain environments it is desired to have a read-only configuration file. When this switch is set to `true` ownCloud will not verify whether the configuration is writable. However, it will not be possible to configure all options via the Web interface. Furthermore, when updating ownCloud it is required to make the configuration file writable again for the update process. ==== Code Sample [source,php] .... 'config_is_read_only' => false, .... === operation.mode This defines the mode of operations. The default value is 'single-instance' which means that ownCloud is running on a single node, which might be the most common operations mode. The only other possible value for now is 'clustered-instance' which means that ownCloud is running on at least 2 nodes. The mode of operations has various impact on the behavior of ownCloud. ==== Code Sample [source,php] .... 'operation.mode' => 'single-instance', .... == Logging These parameters configure the logging options. For additional information or advanced configuration, please see the logging section in the documentation. === log_type By default the ownCloud logs are sent to the `owncloud.log` file in the default ownCloud data directory. If syslogging is desired, set this parameter to `syslog`. Setting this parameter to `errorlog` will use the PHP error_log function for logging. ==== Code Sample [source,php] .... 'log_type' => 'owncloud', .... === logfile Log file path for the ownCloud logging type. Defaults to `[datadirectory]/owncloud.log`. ==== Code Sample [source,php] .... 'logfile' => '/var/log/owncloud.log', .... === loglevel Loglevel to start logging at. Valid values are: 0 = Debug, 1 = Info, 2 = Warning, 3 = Error, and 4 = Fatal. The default value is Warning. ==== Code Sample [source,php] .... 'loglevel' => 2, .... === syslog_tag If you maintain different instances and aggregate the logs, you may want to distinguish between them. `syslog_tag` can be set per instance with a unique id. Only available if `log_type` is set to `syslog`. The default value is `ownCloud`. ==== Code Sample [source,php] .... 'syslog_tag' => 'ownCloud', .... === log.syslog.format The syslog format can be changed to remove or add information. In addition to the %replacements% below %level% can be used, but it is used as a dedicated parameter to the syslog logging facility anyway. ==== Code Sample [source,php] .... 'log.syslog.format' => '[%reqId%][%remoteAddr%][%user%][%app%][%method%][%url%] %message%', .... === log.conditions Log condition for log level increase based on conditions. Once one of these conditions is met, the required log level is set to debug. This allows to debug specific requests, users or apps. Supported conditions: - `shared_secret`: if a request parameter with the name `log_secret` is set to this value the condition is met - `users`: if the current request is done by one of the specified users, this condition is met - `apps`: if the log message is invoked by one of the specified apps, this condition is met - `logfile`: the log message invoked by the specified apps get redirected to this logfile, this condition is met Note: Not applicable when using syslog. Defaults to an empty array. ==== Code Sample [source,php] .... 'log.conditions' => [ [ 'shared_secret' => '57b58edb6637fe3059b3595cf9c41b9', 'users' => [ 'user1' ], 'apps' => [ 'files_texteditor' ], 'logfile' => '/tmp/test.log' ], [ 'shared_secret' => '57b58edb6637fe3059b3595cf9c41b9', 'users' => [ 'user1' ], 'apps' => [ 'gallery' ], 'logfile' => '/tmp/gallery.log' ], ], .... === logdateformat This uses PHP.date formatting; see http://php.net/manual/en/function.date.php. ==== Code Sample [source,php] .... 'logdateformat' => 'F d, Y H:i:s', .... === logtimezone The default timezone for log files is UTC. You may change this; see http://php.net/manual/en/timezones.php. ==== Code Sample [source,php] .... 'logtimezone' => 'Europe/Berlin', .... === cron_log Log successful cron runs. ==== Code Sample [source,php] .... 'cron_log' => true, .... === log_rotate_size Enables log rotation and limits the total size of the log files. The default is 0 or false which disables log rotation. Specify a size in bytes, for example 104857600 (100 megabytes = 100 * 1024 * 1024 bytes). A new logfile is created with a new name when the old logfile reaches the defined limit. If a rotated log file is already present, it will be overwritten. If enabled, only the active log file and one rotated file are stored. ==== Code Sample [source,php] .... 'log_rotate_size' => false, .... == Alternate Code Locations Some of the ownCloud code may be stored in alternate locations. === customclient_desktop, customclient_android, and customclient_ios This section is for configuring the download links for ownCloud clients, as seen in the first-run wizard and on Personal pages. ==== Code Sample [source,php] .... 'customclient_desktop' => 'https://owncloud.org/install/#install-clients', 'customclient_android' => 'https://play.google.com/store/apps/details?id=com.owncloud.android', 'customclient_ios' => 'https://itunes.apple.com/us/app/owncloud/id543672169?mt=8', .... === apps_paths If you want to store apps in a custom directory instead of ownCloud’s default `/app`, you need to modify the `apps_paths` key. There, you need to add a new associative array that contains three elements. These are: - `path` The absolute file system path to the custom app folder. - `url` The request path to that folder relative to the ownCloud web root, prefixed with /. - `writable` Whether users can install apps in that folder. After the configuration is added, new apps will only install in a directory where writable is set to true. The configuration example shows how to add a second directory, called `/apps-external`. Here, new apps and updates are only written to the `/apps-external` directory. This eases upgrade procedures of ownCloud where shipped apps are delivered to apps/ by default. `OC::$SERVERROOT` points to the web root of your instance. Please see the Apps Management description on how to move custom apps properly. ==== Code Sample [source,php] .... 'apps_paths' => [ [ 'path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => false, ], [ 'path' => OC::$SERVERROOT . '/apps-external', 'url' => '/apps-external', 'writable' => true, ], ], .... == Previews ownCloud supports previews of image files, the covers of MP3 files, and text files. These options control enabling and disabling previews, and thumbnail size. === enable_previews By default, ownCloud can generate previews for the following file types: - Image files - Covers of MP3 files - Text documents Valid values are `true`, to enable previews, or `false`, to disable previews. ==== Code Sample [source,php] .... 'enable_previews' => true, .... === preview_max_x The maximum width, in pixels, of a preview. A value of `null` means there is no limit. ==== Code Sample [source,php] .... 'preview_max_x' => 2048, .... === preview_max_y The maximum height, in pixels, of a preview. A value of `null` means there is no limit. ==== Code Sample [source,php] .... 'preview_max_y' => 2048, .... === preview_max_scale_factor If a lot of small pictures are stored on the ownCloud instance and the preview system generates blurry previews, you might want to consider setting a maximum scale factor. By default, pictures are upscaled to 10 times the original size. A value of `1` or `null` disables scaling. ==== Code Sample [source,php] .... 'preview_max_scale_factor' => 10, .... === preview_max_filesize_image max file size for generating image previews with imagegd (default behaviour) If the image is bigger, it'll try other preview generators, but will most likely show the default mimetype icon. Value represents the maximum file size in megabytes. Default is 50. Set to -1 for no limit. ==== Code Sample [source,php] .... 'preview_max_filesize_image' => 50, .... === preview_libreoffice_path custom path for LibreOffice/OpenOffice binary. ==== Code Sample [source,php] .... 'preview_libreoffice_path' => '/usr/bin/libreoffice', .... === preview_office_cl_parameters Use this if LibreOffice/OpenOffice requires additional arguments. ==== Code Sample [source,php] .... 'preview_office_cl_parameters' => ' --headless --nologo --nofirststartwizard --invisible --norestore '. '--convert-to pdf --outdir ', .... === enabledPreviewProviders Only register providers that have been explicitly enabled. The following providers are enabled by default: - OC\\Preview\\PNG - OC\\Preview\\JPEG - OC\\Preview\\GIF - OC\\Preview\\BMP - OC\\Preview\\XBitmap - OC\\Preview\\MarkDown - OC\\Preview\\MP3 - OC\\Preview\\TXT The following providers are disabled by default due to performance or privacy concerns: - OC\\Preview\\Illustrator - OC\\Preview\\Movie - OC\\Preview\\MSOffice2003 - OC\\Preview\\MSOffice2007 - OC\\Preview\\MSOfficeDoc - OC\\Preview\\OpenDocument - OC\\Preview\\PDF - OC\\Preview\\Photoshop - OC\\Preview\\Postscript - OC\\Preview\\StarOffice - OC\\Preview\\SVG - OC\\Preview\\TIFF - OC\\Preview\\Font .. note:: Troubleshooting steps for the MS Word previews are available at the :doc:`../configuration/files/collaborative_documents_configuration` section of the Administrators Manual. The following providers are not available in Microsoft Windows: - OC\\Preview\\Movie - OC\\Preview\\MSOfficeDoc - OC\\Preview\\MSOffice2003 - OC\\Preview\\MSOffice2007 - OC\\Preview\\OpenDocument - OC\\Preview\\StarOffice ==== Code Sample [source,php] .... 'enabledPreviewProviders' => [ 'OC\\Preview\\PNG', 'OC\\Preview\\JPEG', 'OC\\Preview\\GIF', 'OC\\Preview\\BMP', 'OC\\Preview\\XBitmap', 'OC\\Preview\\MP3', 'OC\\Preview\\TXT', 'OC\\Preview\\MarkDown' ], .... == Comments Global settings for the Comments infrastructure. === comments.managerFactory Replaces the default Comments Manager Factory. This can be utilized if an own or 3rdParty CommentsManager should be used that – for instance – uses the filesystem instead of the database to keep the comments. ==== Code Sample [source,php] .... 'comments.managerFactory' => '\\OC\\Comments\\ManagerFactory', .... === systemtags.managerFactory Replaces the default System Tags Manager Factory. This can be utilized if an own or 3rdParty SystemTagsManager should be used that – for instance – uses the filesystem instead of the database to keep the tags. ==== Code Sample [source,php] .... 'systemtags.managerFactory' => '\\OC\\SystemTag\\ManagerFactory', .... == Maintenance These options are for halting user activity when you are performing server maintenance. === maintenance Enable maintenance mode to disable ownCloud. If you want to prevent users from logging in to ownCloud before you start doing some maintenance work, you need to set the value of the maintenance parameter to true. Please keep in mind that users who are already logged-in are kicked out of ownCloud instantly. ==== Code Sample [source,php] .... 'maintenance' => false, .... === singleuser When set to `true`, the ownCloud instance will be unavailable for all users who are not in the `admin` group. ==== Code Sample [source,php] .... 'singleuser' => false, .... == SSL === openssl Extra SSL options to be used for configuration. ==== Code Sample [source,php] .... 'openssl' => [ 'config' => '/absolute/location/of/openssl.cnf', ], .... === enable_certificate_management Allow the configuration of system wide trusted certificates. ==== Code Sample [source,php] .... 'enable_certificate_management' => false, .... == Memory caching backend configuration Available cache backends: * `\\OC\\Memcache\\APC` Alternative PHP Cache backend * `\\OC\\Memcache\\APCu` APC user backend * `\\OC\\Memcache\\ArrayCache` In-memory array-based backend (not recommended) * `\\OC\\Memcache\\Memcached` Memcached backend * `\\OC\\Memcache\\Redis` Redis backend * `\\OC\\Memcache\\XCache` XCache backend Advice on choosing between the various backends: * APCu should be easiest to install. Almost all distributions have packages. Use this for single user environment for all caches. * Use Redis or Memcached for distributed environments. For the local cache (you can configure two) take APCu. === memcache.local Memory caching backend for locally stored data. Used for host-specific data, e.g., file paths. ==== Code Sample [source,php] .... 'memcache.local' => '\\OC\\Memcache\\APCu', .... === memcache.distributed Memory caching backend for distributed data. Used for installation-specific data, e.g., database caching If unset, defaults to the value of memcache.local. ==== Code Sample [source,php] .... 'memcache.distributed' => '\\OC\\Memcache\\Memcached', .... === redis Connection details for redis to use for memory caching in a single server configuration. For enhanced security it is recommended to configure Redis to require a password. See http://redis.io/topics/security for more information. ==== Code Sample [source,php] .... 'redis' => [ 'host' => 'localhost', // Can also be a unix domain socket: '/tmp/redis.sock'. 'port' => 6379, 'timeout' => 0.0, 'password' => '', // Optional, if not defined no password will be used. 'dbindex' => 0, // Optional, if undefined SELECT will not run and will use Redis Server's default DB Index. ], .... === redis.cluster Connection details for a Redis Cluster Only for use with Redis Clustering, for Sentinel-based setups use the single server configuration above, and perform HA on the hostname. Redis Cluster support requires the php module phpredis in version 3.0.0 or higher. Available failover modes: - \\RedisCluster::FAILOVER_NONE - only send commands to master nodes (default) - \\RedisCluster::FAILOVER_ERROR - failover to slaves for read commands if master is unavailable - \\RedisCluster::FAILOVER_DISTRIBUTE - randomly distribute read commands across master and slaves ==== Code Sample [source,php] .... 'redis.cluster' => [ 'seeds' => [ // provide some/all of the cluster servers to bootstrap discovery, port required 'localhost:7000', 'localhost:7001' ], 'timeout' => 0.0, 'read_timeout' => 0.0, 'failover_mode' => \\RedisCluster::FAILOVER_DISTRIBUTE ], .... === memcached_servers Server details for one or more memcached servers to use for memory caching. ==== Code Sample [source,php] .... 'memcached_servers' => [ // hostname, port and optional weight. Also see: // http://www.php.net/manual/en/memcached.addservers.php // http://www.php.net/manual/en/memcached.addserver.php [ 'localhost', 11211 ], //['other.host.local', 11211], ], .... === memcached_options Connection options for memcached. ==== Code Sample [source,php] .... 'memcached_options' => [ // Set timeouts to 50ms \\Memcached::OPT_CONNECT_TIMEOUT => 50, \\Memcached::OPT_RETRY_TIMEOUT => 50, \\Memcached::OPT_SEND_TIMEOUT => 50, \\Memcached::OPT_RECV_TIMEOUT => 50, \\Memcached::OPT_POLL_TIMEOUT => 50, // Enable compression \\Memcached::OPT_COMPRESSION => true, // Turn on consistent hashing \\Memcached::OPT_LIBKETAMA_COMPATIBLE => true, // Enable Binary Protocol \\Memcached::OPT_BINARY_PROTOCOL => true, // Binary serializer will be enabled if the igbinary PECL module is available //\\Memcached::OPT_SERIALIZER => \\Memcached::SERIALIZER_IGBINARY, ], .... === cache_path Location of the cache folder, defaults to `data/$user/cache` where `$user` is the current user. When specified, the format will change to `$cache_path/$user` where `$cache_path` is the configured cache directory and `$user` is the user. ==== Code Sample [source,php] .... 'cache_path' => '', .... === cache_chunk_gc_ttl TTL of chunks located in the cache folder before they're removed by garbage collection (in seconds). Increase this value if users have issues uploading very large files via the ownCloud Client as upload isn't completed within one day. ==== Code Sample [source,php] .... 'cache_chunk_gc_ttl' => 86400, // 60 * 60 * 24 = 1 day .... === dav.chunk_base_dir Location of the chunk folder, defaults to `data/$user/uploads` where `$user` is the current user. When specified, the format will change to `$dav.chunk_base_dir/$user` where `$dav.chunk_base_dir` is the configured cache directory and `$user` is the user. ==== Code Sample [source,php] .... 'dav.chunk_base_dir' => '', .... == Sharing Global settings for Sharing === sharing.managerFactory Replaces the default Share Provider Factory. This can be utilized if own or 3rdParty Share Providers are used that – for instance – use the filesystem instead of the database to keep the share information. ==== Code Sample [source,php] .... 'sharing.managerFactory' => '\\OC\\Share20\\ProviderFactory', .... === sharing.federation.allowHttpFallback When talking with federated sharing server, allow falling back to HTTP instead of hard forcing HTTPS. ==== Code Sample [source,php] .... 'sharing.federation.allowHttpFallback' => false, .... == All other configuration options === dbdriveroptions Additional driver options for the database connection, eg. to enable SSL encryption in MySQL or specify a custom wait timeout on a cheap hoster. ==== Code Sample [source,php] .... 'dbdriveroptions' => [ PDO::MYSQL_ATTR_SSL_CA => '/file/path/to/ca_cert.pem', PDO::MYSQL_ATTR_INIT_COMMAND => 'SET wait_timeout = 28800' ], .... === sqlite.journal_mode sqlite3 journal mode can be specified using this configuration parameter - can be 'WAL' or 'DELETE'. See for more details https://www.sqlite.org/wal.html ==== Code Sample [source,php] .... 'sqlite.journal_mode' => 'DELETE', .... === mysql.utf8mb4 During setup, if requirements are met (see below), this setting is set to true and MySQL can handle 4 byte characters instead of 3 byte characters. If you want to convert an existing 3-byte setup into a 4-byte setup please set the parameters in MySQL as mentioned below and run the migration command: ./occ db:convert-mysql-charset The config setting will be set automatically after a successful run. Consult the documentation for more details. MySQL requires a special setup for longer indexes (> 767 bytes) which are needed: [mysqld] innodb_large_prefix=ON innodb_file_format=Barracuda innodb_file_per_table=ON Tables will be created with * character set: utf8mb4 * collation: utf8mb4_bin * row_format: compressed See: - https://dev.mysql.com/doc/refman/5.7/en/charset-unicode-utf8mb4.html - https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html#sysvar_innodb_large_prefix - https://mariadb.com/kb/en/mariadb/xtradbinnodb-server-system-variables/#innodb_large_prefix - http://www.tocker.ca/2013/10/31/benchmarking-innodb-page-compression-performance.html - http://mechanics.flite.com/blog/2014/07/29/using-innodb-large-prefix-to-avoid-error-1071/ ==== Code Sample [source,php] .... 'mysql.utf8mb4' => false, .... === supportedDatabases Database types that are supported for installation. Available: - sqlite (SQLite3 - Not in Enterprise Edition) - mysql (MySQL) - pgsql (PostgreSQL) - oci (Oracle - Enterprise Edition Only) ==== Code Sample [source,php] .... 'supportedDatabases' => [ 'sqlite', 'mysql', 'pgsql', 'oci', ], .... === tempdirectory Override where ownCloud stores temporary files. Useful in situations where the system temporary directory is on a limited space ramdisk or is otherwise restricted, or if external storages which do not support streaming are in use. The Web server user must have write access to this directory. ==== Code Sample [source,php] .... 'tempdirectory' => '/tmp/owncloudtemp', .... === hashingCost The hashing cost used by hashes generated by ownCloud. Using a higher value requires more time and CPU power to calculate the hashes. As this number grows, the amount of work (typically CPU time or memory) necessary to compute the hash increases exponentially. ==== Code Sample [source,php] .... 'hashingCost' => 10, .... === blacklisted_files Blacklist a specific file or files and disallow the upload of files with this name. `.htaccess` is blocked by default. WARNING: Use this only if you know what you are doing! ==== Code Sample [source,php] .... 'blacklisted_files' => [ '.htaccess' ], .... === excluded_directories Exclude specific directory names and disallow scanning, creating and renaming using these names. Case insensitive. Excluded directory names are queried at any path part like at the beginning, in the middle or at the end and will not be further processed if found. Please see the documentation for details and examples. Use when the storage backend supports eg snapshot directories to be excluded. WARNING: Use this only if you know what you are doing. ==== Code Sample [source,php] .... 'excluded_directories' => [ '.snapshot', '~snapshot', ], .... === integrity.excluded.files Exclude files from the integrity checker command. ==== Code Sample [source,php] .... 'integrity.excluded.files' => [ '.DS_Store', 'Thumbs.db', '.directory', '.webapp', '.htaccess', '.user.ini', ], .... === integrity.ignore.missing.app.signature The list of apps that are allowed to have no signature.json. Besides ownCloud apps, this is particularly useful when creating ownCloud themes, because themes are treated as apps. The app is identified with it´s app-id. The following example allows app-1 and theme-2 to have no signature. ==== Code Sample [source,php] .... 'integrity.ignore.missing.app.signature' => [ 'app-id of app-1', 'app-id of theme-2', ], .... === share_folder Define a default folder for shared files and folders other than root. ==== Code Sample [source,php] .... 'share_folder' => '/', .... === cipher The default cipher for encrypting files. Currently AES-128-CFB and AES-256-CFB are supported. ==== Code Sample [source,php] .... 'cipher' => 'AES-256-CFB', .... === minimum.supported.desktop.version The minimum ownCloud desktop client version that will be allowed to sync with this server instance. All connections made from earlier clients will be denied by the server. Defaults to the minimum officially supported ownCloud version at the time of release of this server version. When changing this, note that older unsupported versions of the ownCloud desktop client may not function as expected, and could lead to permanent data loss for clients or other unexpected results. ==== Code Sample [source,php] .... 'minimum.supported.desktop.version' => '2.2.4', .... === quota_include_external_storage EXPERIMENTAL: option whether to include external storage in quota calculation, defaults to false. ==== Code Sample [source,php] .... 'quota_include_external_storage' => false, .... === filesystem_check_changes Specifies how often the local filesystem (the ownCloud data/ directory, and NFS mounts in data/) is checked for changes made outside ownCloud. This does not apply to external storages. `0`: Never check the filesystem for outside changes, provides a performance increase when it's certain that no changes are made directly to the filesystem. `1`: Check each file or folder at most once per request, recommended for general use if outside changes might happen. ==== Code Sample [source,php] .... 'filesystem_check_changes' => 0, .... === part_file_in_storage By default ownCloud will store the part files created during upload in the same storage as the upload target. Setting this to false will store the part files in the root of the users folder which might be required to work with certain external storage setups that have limited rename capabilities. ==== Code Sample [source,php] .... 'part_file_in_storage' => true, .... === mount_file Where `mount.json` file should be stored, defaults to `data/mount.json` in the ownCloud directory. ==== Code Sample [source,php] .... 'mount_file' => '/var/www/owncloud/data/mount.json', .... === filesystem_cache_readonly When `true`, prevent ownCloud from changing the cache due to changes in the filesystem for all storage. ==== Code Sample [source,php] .... 'filesystem_cache_readonly' => false, .... === secret Secret used by ownCloud for various purposes, e.g., to encrypt data. If you lose this string there will be data corruption. ==== Code Sample [source,php] .... 'secret' => '', .... === trusted_proxies List of trusted proxy servers If you configure these also consider setting `forwarded_for_headers` which otherwise defaults to `HTTP_X_FORWARDED_FOR` (the `X-Forwarded-For` header). ==== Code Sample [source,php] .... 'trusted_proxies' => [ '203.0.113.45', '198.51.100.128' ], .... === forwarded_for_headers Headers that should be trusted as client IP address in combination with `trusted_proxies`. If the HTTP header looks like `X-Forwarded-For`, then use `HTTP_X_FORWARDED_FOR` here. If set incorrectly, a client can spoof their IP address as visible to ownCloud, bypassing access controls and making logs useless! Defaults to `HTTP_X_FORWARDED_FOR` if unset ==== Code Sample [source,php] .... 'forwarded_for_headers' => [ 'HTTP_X_FORWARDED', 'HTTP_FORWARDED_FOR' ], .... === max_filesize_animated_gifs_public_sharing max file size for animating gifs on public-sharing-site. If the gif is bigger, it'll show a static preview. Value represents the maximum file size in megabytes. Default is `10`. Set to `-1` for no limit. ==== Code Sample [source,php] .... 'max_filesize_animated_gifs_public_sharing' => 10, .... === filelocking.enabled Enables transactional file locking. This is enabled by default. Prevents concurrent processes from accessing the same files at the same time. Can help prevent side effects that would be caused by concurrent operations. Mainly relevant for very large installations with many users working with shared files. ==== Code Sample [source,php] .... 'filelocking.enabled' => true, .... === filelocking.ttl Set the lock's time-to-live in seconds. Any lock older than this will be automatically cleaned up. If not set this defaults to either 1 hour or the php max_execution_time, whichever is higher. ==== Code Sample [source,php] .... 'filelocking.ttl' => 3600, .... === memcache.locking Memory caching backend for file locking. Because most memcache backends can clean values without warning using Redis is highly recommended to *avoid data loss*. ==== Code Sample [source,php] .... 'memcache.locking' => '\\\\OC\\\\Memcache\\\\Redis', .... === upgrade.disable-web Disable the web based updater. ==== Code Sample [source,php] .... 'upgrade.disable-web' => false, .... === upgrade.automatic-app-update Automatic update of market apps, set to `false` to disable. ==== Code Sample [source,php] .... 'upgrade.automatic-app-update' => true, .... === debug Set this ownCloud instance to debugging mode Only enable this for local development and not in production environments. This will disable the minifier and outputs some additional debug information. WARNING: Be warned that, if you set this to `true`, exceptions display stack traces on the web interface, *including passwords*, — **in plain text!**. We strongly encourage you never to use it in production. ==== Code Sample [source,php] .... 'debug' => false, .... === data-fingerprint Sets the data-fingerprint of the current data served. This is a property used by the clients to find out if a backup has been restored on the server. Once a backup is restored run `./occ maintenance:data-fingerprint` to set this to a new value. Updating/Deleting this value can make connected clients stall until the user has resolved conflicts. ==== Code Sample [source,php] .... 'data-fingerprint' => '', .... === copied_sample_config This entry is just here to show a warning in case somebody copied the sample configuration. DO NOT ADD THIS SWITCH TO YOUR CONFIGURATION! If you, brave person, have read until here be aware that you should not modify *ANY* settings in this file without reading the documentation. ==== Code Sample [source,php] .... 'copied_sample_config' => true, .... === files_external_allow_create_new_local Set this property to true if you want to enable the files_external local mount Option. Default: false. ==== Code Sample [source,php] .... 'files_external_allow_create_new_local' => false, .... === smb.logging.enable Set this property to true if you want to enable debug logging for SMB access. ==== Code Sample [source,php] .... 'smb.logging.enable' => false, .... ",12032,False,2246.08366607196,median "// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include ""src/compiler/verifier.h"" #include #include #include #include #include #include ""src/bit-vector.h"" #include ""src/compiler/all-nodes.h"" #include ""src/compiler/common-operator.h"" #include ""src/compiler/graph.h"" #include ""src/compiler/js-operator.h"" #include ""src/compiler/node-properties.h"" #include ""src/compiler/node.h"" #include ""src/compiler/opcodes.h"" #include ""src/compiler/operator-properties.h"" #include ""src/compiler/operator.h"" #include ""src/compiler/schedule.h"" #include ""src/compiler/simplified-operator.h"" #include ""src/ostreams.h"" namespace v8 { namespace internal { namespace compiler { class Verifier::Visitor { public: Visitor(Zone* z, Typing typed, CheckInputs check_inputs) : zone(z), typing(typed), check_inputs(check_inputs) {} void Check(Node* node); Zone* zone; Typing typing; CheckInputs check_inputs; private: void CheckNotTyped(Node* node) { if (NodeProperties::IsTyped(node)) { std::ostringstream str; str << ""TypeError: node #"" << node->id() << "":"" << *node->op() << "" should never have a type""; FATAL(str.str().c_str()); } } void CheckTypeIs(Node* node, Type* type) { if (typing == TYPED && !NodeProperties::GetType(node)->Is(type)) { std::ostringstream str; str << ""TypeError: node #"" << node->id() << "":"" << *node->op() << "" type ""; NodeProperties::GetType(node)->PrintTo(str); str << "" is not ""; type->PrintTo(str); FATAL(str.str().c_str()); } } void CheckTypeMaybe(Node* node, Type* type) { if (typing == TYPED && !NodeProperties::GetType(node)->Maybe(type)) { std::ostringstream str; str << ""TypeError: node #"" << node->id() << "":"" << *node->op() << "" type ""; NodeProperties::GetType(node)->PrintTo(str); str << "" must intersect ""; type->PrintTo(str); FATAL(str.str().c_str()); } } void CheckValueInputIs(Node* node, int i, Type* type) { Node* input = NodeProperties::GetValueInput(node, i); if (typing == TYPED && !NodeProperties::GetType(input)->Is(type)) { std::ostringstream str; str << ""TypeError: node #"" << node->id() << "":"" << *node->op() << ""(input @"" << i << "" = "" << input->opcode() << "":"" << input->op()->mnemonic() << "") type ""; NodeProperties::GetType(input)->PrintTo(str); str << "" is not ""; type->PrintTo(str); FATAL(str.str().c_str()); } } void CheckOutput(Node* node, Node* use, int count, const char* kind) { if (count <= 0) { std::ostringstream str; str << ""GraphError: node #"" << node->id() << "":"" << *node->op() << "" does not produce "" << kind << "" output used by node #"" << use->id() << "":"" << *use->op(); FATAL(str.str().c_str()); } } }; void Verifier::Visitor::Check(Node* node) { int value_count = node->op()->ValueInputCount(); int context_count = OperatorProperties::GetContextInputCount(node->op()); int frame_state_count = OperatorProperties::GetFrameStateInputCount(node->op()); int effect_count = node->op()->EffectInputCount(); int control_count = node->op()->ControlInputCount(); // Verify number of inputs matches up. int input_count = value_count + context_count + frame_state_count; if (check_inputs == kAll) { input_count += effect_count + control_count; } CHECK_EQ(input_count, node->InputCount()); // Verify that frame state has been inserted for the nodes that need it. for (int i = 0; i < frame_state_count; i++) { Node* frame_state = NodeProperties::GetFrameStateInput(node); CHECK(frame_state->opcode() == IrOpcode::kFrameState || // kFrameState uses Start as a sentinel. (node->opcode() == IrOpcode::kFrameState && frame_state->opcode() == IrOpcode::kStart)); } // Verify all value inputs actually produce a value. for (int i = 0; i < value_count; ++i) { Node* value = NodeProperties::GetValueInput(node, i); CheckOutput(value, node, value->op()->ValueOutputCount(), ""value""); // Verify that only parameters and projections can have input nodes with // multiple outputs. CHECK(node->opcode() == IrOpcode::kParameter || node->opcode() == IrOpcode::kProjection || value->op()->ValueOutputCount() <= 1); } // Verify all context inputs are value nodes. for (int i = 0; i < context_count; ++i) { Node* context = NodeProperties::GetContextInput(node); CheckOutput(context, node, context->op()->ValueOutputCount(), ""context""); } if (check_inputs == kAll) { // Verify all effect inputs actually have an effect. for (int i = 0; i < effect_count; ++i) { Node* effect = NodeProperties::GetEffectInput(node); CheckOutput(effect, node, effect->op()->EffectOutputCount(), ""effect""); } // Verify all control inputs are control nodes. for (int i = 0; i < control_count; ++i) { Node* control = NodeProperties::GetControlInput(node, i); CheckOutput(control, node, control->op()->ControlOutputCount(), ""control""); } // Verify that no-no-throw nodes only have IfSuccess/IfException control // uses. if (!node->op()->HasProperty(Operator::kNoThrow)) { int count_success = 0, count_exception = 0; for (Edge edge : node->use_edges()) { if (!NodeProperties::IsControlEdge(edge)) { continue; } Node* control_use = edge.from(); if (control_use->opcode() != IrOpcode::kIfSuccess && control_use->opcode() != IrOpcode::kIfException) { V8_Fatal(__FILE__, __LINE__, ""#%d:%s should be followed by IfSuccess/IfException, but is "" ""followed by #%d:%s"", node->id(), node->op()->mnemonic(), control_use->id(), control_use->op()->mnemonic()); } if (control_use->opcode() == IrOpcode::kIfSuccess) ++count_success; if (control_use->opcode() == IrOpcode::kIfException) ++count_exception; CHECK_LE(count_success, 1); CHECK_LE(count_exception, 1); } } } switch (node->opcode()) { case IrOpcode::kStart: // Start has no inputs. CHECK_EQ(0, input_count); // Type is a tuple. // TODO(rossberg): Multiple outputs are currently typed as Internal. CheckTypeIs(node, Type::Internal()); break; case IrOpcode::kEnd: // End has no outputs. CHECK(node->op()->ValueOutputCount() == 0); CHECK(node->op()->EffectOutputCount() == 0); CHECK(node->op()->ControlOutputCount() == 0); // Type is empty. CheckNotTyped(node); break; case IrOpcode::kDead: // Dead is never connected to the graph. UNREACHABLE(); break; case IrOpcode::kBranch: { // Branch uses are IfTrue and IfFalse. int count_true = 0, count_false = 0; for (const Node* use : node->uses()) { CHECK(use->opcode() == IrOpcode::kIfTrue || use->opcode() == IrOpcode::kIfFalse); if (use->opcode() == IrOpcode::kIfTrue) ++count_true; if (use->opcode() == IrOpcode::kIfFalse) ++count_false; } CHECK_EQ(1, count_true); CHECK_EQ(1, count_false); // Type is empty. CheckNotTyped(node); break; } case IrOpcode::kIfTrue: case IrOpcode::kIfFalse: CHECK_EQ(IrOpcode::kBranch, NodeProperties::GetControlInput(node, 0)->opcode()); // Type is empty. CheckNotTyped(node); break; case IrOpcode::kIfSuccess: { // IfSuccess and IfException continuation only on throwing nodes. Node* input = NodeProperties::GetControlInput(node, 0); CHECK(!input->op()->HasProperty(Operator::kNoThrow)); // Type is empty. CheckNotTyped(node); break; } case IrOpcode::kIfException: { // IfSuccess and IfException continuation only on throwing nodes. Node* input = NodeProperties::GetControlInput(node, 0); CHECK(!input->op()->HasProperty(Operator::kNoThrow)); // Type can be anything. CheckTypeIs(node, Type::Any()); break; } case IrOpcode::kSwitch: { // Switch uses are Case and Default. int count_case = 0, count_default = 0; for (const Node* use : node->uses()) { switch (use->opcode()) { case IrOpcode::kIfValue: { for (const Node* user : node->uses()) { if (user != use && user->opcode() == IrOpcode::kIfValue) { CHECK_NE(OpParameter(use->op()), OpParameter(user->op())); } } ++count_case; break; } case IrOpcode::kIfDefault: { ++count_default; break; } default: { V8_Fatal(__FILE__, __LINE__, ""Switch #%d illegally used by #%d:%s"", node->id(), use->id(), use->op()->mnemonic()); break; } } } CHECK_EQ(1, count_default); CHECK_EQ(node->op()->ControlOutputCount(), count_case + count_default); // Type is empty. CheckNotTyped(node); break; } case IrOpcode::kIfValue: case IrOpcode::kIfDefault: CHECK_EQ(IrOpcode::kSwitch, NodeProperties::GetControlInput(node)->opcode()); // Type is empty. CheckNotTyped(node); break; case IrOpcode::kLoop: case IrOpcode::kMerge: CHECK_EQ(control_count, input_count); // Type is empty. CheckNotTyped(node); break; case IrOpcode::kDeoptimizeIf: case IrOpcode::kDeoptimizeUnless: // Type is empty. CheckNotTyped(node); break; case IrOpcode::kDeoptimize: case IrOpcode::kReturn: case IrOpcode::kThrow: // Deoptimize, Return and Throw uses are End. for (const Node* use : node->uses()) { CHECK_EQ(IrOpcode::kEnd, use->opcode()); } // Type is empty. CheckNotTyped(node); break; case IrOpcode::kTerminate: // Terminates take one loop and effect. CHECK_EQ(1, control_count); CHECK_EQ(1, effect_count); CHECK_EQ(2, input_count); CHECK_EQ(IrOpcode::kLoop, NodeProperties::GetControlInput(node)->opcode()); // Terminate uses are End. for (const Node* use : node->uses()) { CHECK_EQ(IrOpcode::kEnd, use->opcode()); } // Type is empty. CheckNotTyped(node); break; case IrOpcode::kOsrNormalEntry: case IrOpcode::kOsrLoopEntry: // Osr entries take one control and effect. CHECK_EQ(1, control_count); CHECK_EQ(1, effect_count); CHECK_EQ(2, input_count); // Type is empty. CheckNotTyped(node); break; // Common operators // ---------------- case IrOpcode::kParameter: { // Parameters have the start node as inputs. CHECK_EQ(1, input_count); // Parameter has an input that produces enough values. int const index = ParameterIndexOf(node->op()); Node* const start = NodeProperties::GetValueInput(node, 0); CHECK_EQ(IrOpcode::kStart, start->opcode()); // Currently, parameter indices start at -1 instead of 0. CHECK_LE(-1, index); CHECK_LT(index + 1, start->op()->ValueOutputCount()); // Type can be anything. CheckTypeIs(node, Type::Any()); break; } case IrOpcode::kInt32Constant: // TODO(turbofan): rename Word32Constant? case IrOpcode::kInt64Constant: // TODO(turbofan): rename Word64Constant? case IrOpcode::kFloat32Constant: case IrOpcode::kFloat64Constant: case IrOpcode::kRelocatableInt32Constant: case IrOpcode::kRelocatableInt64Constant: // Constants have no inputs. CHECK_EQ(0, input_count); // Type is empty. CheckNotTyped(node); break; case IrOpcode::kNumberConstant: // Constants have no inputs. CHECK_EQ(0, input_count); // Type is a number. CheckTypeIs(node, Type::Number()); break; case IrOpcode::kHeapConstant: // Constants have no inputs. CHECK_EQ(0, input_count); // Type is anything. CheckTypeIs(node, Type::Any()); break; case IrOpcode::kExternalConstant: case IrOpcode::kPointerConstant: // Constants have no inputs. CHECK_EQ(0, input_count); // Type is an external pointer. CheckTypeIs(node, Type::ExternalPointer()); break; case IrOpcode::kOsrValue: // OSR values have a value and a control input. CHECK_EQ(1, control_count); CHECK_EQ(1, input_count); // Type is merged from other values in the graph and could be any. CheckTypeIs(node, Type::Any()); break; case IrOpcode::kOsrGuard: // OSR values have a value and a control input. CHECK_EQ(1, value_count); CHECK_EQ(1, effect_count); CHECK_EQ(1, control_count); switch (OsrGuardTypeOf(node->op())) { case OsrGuardType::kUninitialized: CheckTypeIs(node, Type::None()); break; case OsrGuardType::kSignedSmall: CheckTypeIs(node, Type::SignedSmall()); break; case OsrGuardType::kAny: CheckTypeIs(node, Type::Any()); break; } break; case IrOpcode::kProjection: { // Projection has an input that produces enough values. int index = static_cast(ProjectionIndexOf(node->op())); Node* input = NodeProperties::GetValueInput(node, 0); CHECK_GT(input->op()->ValueOutputCount(), index); // Type can be anything. // TODO(rossberg): Introduce tuple types for this. // TODO(titzer): Convince rossberg not to. CheckTypeIs(node, Type::Any()); break; } case IrOpcode::kSelect: { CHECK_EQ(0, effect_count); CHECK_EQ(0, control_count); CHECK_EQ(3, value_count); break; } case IrOpcode::kPhi: { // Phi input count matches parent control node. CHECK_EQ(0, effect_count); CHECK_EQ(1, control_count); Node* control = NodeProperties::GetControlInput(node, 0); CHECK_EQ(value_count, control->op()->ControlInputCount()); CHECK_EQ(input_count, 1 + value_count); // Type must be subsumed by all input types. // TODO(rossberg): for now at least, narrowing does not really hold. /* for (int i = 0; i < value_count; ++i) { CHECK(type_of(ValueInput(node, i))->Is(type_of(node))); } */ break; } case IrOpcode::kInductionVariablePhi: { // This is only a temporary node for the typer. UNREACHABLE(); break; } case IrOpcode::kEffectPhi: { // EffectPhi input count matches parent control node. CHECK_EQ(0, value_count); CHECK_EQ(1, control_count); Node* control = NodeProperties::GetControlInput(node, 0); CHECK_EQ(effect_count, control->op()->ControlInputCount()); CHECK_EQ(input_count, 1 + effect_count); break; } case IrOpcode::kLoopExit: { CHECK_EQ(2, control_count); Node* loop = NodeProperties::GetControlInput(node, 1); CHECK_EQ(IrOpcode::kLoop, loop->opcode()); break; } case IrOpcode::kLoopExitValue: { CHECK_EQ(1, control_count); Node* loop_exit = NodeProperties::GetControlInput(node, 0); CHECK_EQ(IrOpcode::kLoopExit, loop_exit->opcode()); break; } case IrOpcode::kLoopExitEffect: { CHECK_EQ(1, control_count); Node* loop_exit = NodeProperties::GetControlInput(node, 0); CHECK_EQ(IrOpcode::kLoopExit, loop_exit->opcode()); break; } case IrOpcode::kCheckpoint: // Type is empty. CheckNotTyped(node); break; case IrOpcode::kBeginRegion: // TODO(rossberg): what are the constraints on these? break; case IrOpcode::kFinishRegion: { // TODO(rossberg): what are the constraints on these? // Type must be subsumed by input type. if (typing == TYPED) { Node* val = NodeProperties::GetValueInput(node, 0); CHECK(NodeProperties::GetType(val)->Is(NodeProperties::GetType(node))); } break; } case IrOpcode::kFrameState: { // TODO(jarin): what are the constraints on these? CHECK_EQ(5, value_count); CHECK_EQ(0, control_count); CHECK_EQ(0, effect_count); CHECK_EQ(6, input_count); for (int i = 0; i < 3; ++i) { CHECK(NodeProperties::GetValueInput(node, i)->opcode() == IrOpcode::kStateValues || NodeProperties::GetValueInput(node, i)->opcode() == IrOpcode::kTypedStateValues); } break; } case IrOpcode::kStateValues: case IrOpcode::kTypedStateValues: case IrOpcode::kObjectState: case IrOpcode::kTypedObjectState: // TODO(jarin): what are the constraints on these? break; case IrOpcode::kCall: // TODO(rossberg): what are the constraints on these? break; case IrOpcode::kTailCall: // TODO(bmeurer): what are the constraints on these? break; // JavaScript operators // -------------------- case IrOpcode::kJSEqual: case IrOpcode::kJSNotEqual: case IrOpcode::kJSStrictEqual: case IrOpcode::kJSStrictNotEqual: case IrOpcode::kJSLessThan: case IrOpcode::kJSGreaterThan: case IrOpcode::kJSLessThanOrEqual: case IrOpcode::kJSGreaterThanOrEqual: // Type is Boolean. CheckTypeIs(node, Type::Boolean()); break; case IrOpcode::kJSBitwiseOr: case IrOpcode::kJSBitwiseXor: case IrOpcode::kJSBitwiseAnd: case IrOpcode::kJSShiftLeft: case IrOpcode::kJSShiftRight: case IrOpcode::kJSShiftRightLogical: // Type is 32 bit integral. CheckTypeIs(node, Type::Integral32()); break; case IrOpcode::kJSAdd: // Type is Number or String. CheckTypeIs(node, Type::NumberOrString()); break; case IrOpcode::kJSSubtract: case IrOpcode::kJSMultiply: case IrOpcode::kJSDivide: case IrOpcode::kJSModulus: // Type is Number. CheckTypeIs(node, Type::Number()); break; case IrOpcode::kJSToBoolean: // Type is Boolean. CheckTypeIs(node, Type::Boolean()); break; case IrOpcode::kJSToInteger: // Type is OrderedNumber. CheckTypeIs(node, Type::OrderedNumber()); break; case IrOpcode::kJSToLength: // Type is OrderedNumber. CheckTypeIs(node, Type::OrderedNumber()); break; case IrOpcode::kJSToName: // Type is Name. CheckTypeIs(node, Type::Name()); break; case IrOpcode::kJSToNumber: // Type is Number. CheckTypeIs(node, Type::Number()); break; case IrOpcode::kJSToString: // Type is String. CheckTypeIs(node, Type::String()); break; case IrOpcode::kJSToObject: // Type is Receiver. CheckTypeIs(node, Type::Receiver()); break; case IrOpcode::kJSCreate: // Type is Object. CheckTypeIs(node, Type::Object()); break; case IrOpcode::kJSCreateArguments: // Type is OtherObject. CheckTypeIs(node, Type::OtherObject()); break; case IrOpcode::kJSCreateArray: // Type is OtherObject. CheckTypeIs(node, Type::OtherObject()); break; case IrOpcode::kJSCreateClosure: // Type is Function. CheckTypeIs(node, Type::Function()); break; case IrOpcode::kJSCreateIterResultObject: // Type is OtherObject. CheckTypeIs(node, Type::OtherObject()); break; case IrOpcode::kJSCreateKeyValueArray: // Type is OtherObject. CheckTypeIs(node, Type::OtherObject()); break; case IrOpcode::kJSCreateLiteralArray: case IrOpcode::kJSCreateLiteralObject: case IrOpcode::kJSCreateLiteralRegExp: // Type is OtherObject. CheckTypeIs(node, Type::OtherObject()); break; case IrOpcode::kJSLoadProperty: // Type can be anything. CheckTypeIs(node, Type::Any()); CHECK(PropertyAccessOf(node->op()).feedback().IsValid()); break; case IrOpcode::kJSLoadNamed: // Type can be anything. CheckTypeIs(node, Type::Any()); CHECK(NamedAccessOf(node->op()).feedback().IsValid()); break; case IrOpcode::kJSLoadGlobal: // Type can be anything. CheckTypeIs(node, Type::Any()); CHECK(LoadGlobalParametersOf(node->op()).feedback().IsValid()); break; case IrOpcode::kJSStoreProperty: // Type is empty. CheckNotTyped(node); CHECK(PropertyAccessOf(node->op()).feedback().IsValid()); break; case IrOpcode::kJSStoreNamed: // Type is empty. CheckNotTyped(node); CHECK(NamedAccessOf(node->op()).feedback().IsValid()); break; case IrOpcode::kJSStoreGlobal: // Type is empty. CheckNotTyped(node); CHECK(StoreGlobalParametersOf(node->op()).feedback().IsValid()); break; case IrOpcode::kJSStoreDataPropertyInLiteral: // Type is empty. CheckNotTyped(node); break; case IrOpcode::kJSDeleteProperty: case IrOpcode::kJSHasProperty: case IrOpcode::kJSInstanceOf: case IrOpcode::kJSOrdinaryHasInstance: // Type is Boolean. CheckTypeIs(node, Type::Boolean()); break; case IrOpcode::kJSTypeOf: // Type is String. CheckTypeIs(node, Type::String()); break; case IrOpcode::kJSLoadContext: // Type can be anything. CheckTypeIs(node, Type::Any()); break; case IrOpcode::kJSStoreContext: // Type is empty. CheckNotTyped(node); break; case IrOpcode::kJSCreateFunctionContext: case IrOpcode::kJSCreateCatchContext: case IrOpcode::kJSCreateWithContext: case IrOpcode::kJSCreateBlockContext: case IrOpcode::kJSCreateScriptContext: { // Type is Context, and operand is Internal. Node* context = NodeProperties::GetContextInput(node); // TODO(bmeurer): This should say CheckTypeIs, but we don't have type // OtherInternal on certain contexts, i.e. those from OsrValue inputs. CheckTypeMaybe(context, Type::OtherInternal()); CheckTypeIs(node, Type::OtherInternal()); break; } case IrOpcode::kJSCallConstruct: case IrOpcode::kJSCallConstructWithSpread: case IrOpcode::kJSConvertReceiver: // Type is Receiver. CheckTypeIs(node, Type::Receiver()); break; case IrOpcode::kJSCallFunction: case IrOpcode::kJSCallRuntime: // Type can be anything. CheckTypeIs(node, Type::Any()); break; case IrOpcode::kJSForInPrepare: { // TODO(bmeurer): What are the constraints on thse? CheckTypeIs(node, Type::Any()); break; } case IrOpcode::kJSForInNext: { CheckTypeIs(node, Type::Union(Type::Name(), Type::Undefined(), zone)); break; } case IrOpcode::kJSLoadMessage: case IrOpcode::kJSStoreMessage: break; case IrOpcode::kJSLoadModule: CheckTypeIs(node, Type::Any()); break; case IrOpcode::kJSStoreModule: CheckNotTyped(node); break; case IrOpcode::kJSGeneratorStore: CheckNotTyped(node); break; case IrOpcode::kJSGeneratorRestoreContinuation: CheckTypeIs(node, Type::SignedSmall()); break; case IrOpcode::kJSGeneratorRestoreRegister: CheckTypeIs(node, Type::Any()); break; case IrOpcode::kJSStackCheck: // Type is empty. CheckNotTyped(node); break; case IrOpcode::kComment: case IrOpcode::kDebugBreak: case IrOpcode::kRetain: case IrOpcode::kUnsafePointerAdd: CheckNotTyped(node); break; // Simplified operators // ------------------------------- case IrOpcode::kBooleanNot: // Boolean -> Boolean CheckValueInputIs(node, 0, Type::Boolean()); CheckTypeIs(node, Type::Boolean()); break; case IrOpcode::kNumberEqual: // (Number, Number) -> Boolean CheckValueInputIs(node, 0, Type::Number()); CheckValueInputIs(node, 1, Type::Number()); CheckTypeIs(node, Type::Boolean()); break; case IrOpcode::kNumberLessThan: case IrOpcode::kNumberLessThanOrEqual: // (Number, Number) -> Boolean CheckValueInputIs(node, 0, Type::Number()); CheckValueInputIs(node, 1, Type::Number()); CheckTypeIs(node, Type::Boolean()); break; case IrOpcode::kSpeculativeNumberAdd: case IrOpcode::kSpeculativeNumberSubtract: case IrOpcode::kSpeculativeNumberMultiply: case IrOpcode::kSpeculativeNumberDivide: case IrOpcode::kSpeculativeNumberModulus: CheckTypeIs(node, Type::Number()); break; case IrOpcode::kSpeculativeNumberEqual: case IrOpcode::kSpeculativeNumberLessThan: case IrOpcode::kSpeculativeNumberLessThanOrEqual: CheckTypeIs(node, Type::Boolean()); break; case IrOpcode::kNumberAdd: case IrOpcode::kNumberSubtract: case IrOpcode::kNumberMultiply: case IrOpcode::kNumberDivide: // (Number, Number) -> Number CheckValueInputIs(node, 0, Type::Number()); CheckValueInputIs(node, 1, Type::Number()); CheckTypeIs(node, Type::Number()); break; case IrOpcode::kNumberModulus: // (Number, Number) -> Number CheckValueInputIs(node, 0, Type::Number()); CheckValueInputIs(node, 1, Type::Number()); CheckTypeIs(node, Type::Number()); break; case IrOpcode::kNumberBitwiseOr: case IrOpcode::kNumberBitwiseXor: case IrOpcode::kNumberBitwiseAnd: // (Signed32, Signed32) -> Signed32 CheckValueInputIs(node, 0, Type::Signed32()); CheckValueInputIs(node, 1, Type::Signed32()); CheckTypeIs(node, Type::Signed32()); break; case IrOpcode::kSpeculativeNumberBitwiseOr: case IrOpcode::kSpeculativeNumberBitwiseXor: case IrOpcode::kSpeculativeNumberBitwiseAnd: CheckTypeIs(node, Type::Signed32()); break; case IrOpcode::kNumberShiftLeft: case IrOpcode::kNumberShiftRight: // (Signed32, Unsigned32) -> Signed32 CheckValueInputIs(node, 0, Type::Signed32()); CheckValueInputIs(node, 1, Type::Unsigned32()); CheckTypeIs(node, Type::Signed32()); break; case IrOpcode::kSpeculativeNumberShiftLeft: case IrOpcode::kSpeculativeNumberShiftRight: CheckTypeIs(node, Type::Signed32()); break; case IrOpcode::kNumberShiftRightLogical: // (Unsigned32, Unsigned32) -> Unsigned32 CheckValueInputIs(node, 0, Type::Unsigned32()); CheckValueInputIs(node, 1, Type::Unsigned32()); CheckTypeIs(node, Type::Unsigned32()); break; case IrOpcode::kSpeculativeNumberShiftRightLogical: CheckTypeIs(node, Type::Unsigned32()); break; case IrOpcode::kNumberImul: // (Unsigned32, Unsigned32) -> Signed32 CheckValueInputIs(node, 0, Type::Unsigned32()); CheckValueInputIs(node, 1, Type::Unsigned32()); CheckTypeIs(node, Type::Signed32()); break; case IrOpcode::kNumberClz32: // Unsigned32 -> Unsigned32 CheckValueInputIs(node, 0, Type::Unsigned32()); CheckTypeIs(node, Type::Unsigned32()); break; case IrOpcode::kNumberAtan2: case IrOpcode::kNumberMax: case IrOpcode::kNumberMin: case IrOpcode::kNumberPow: // (Number, Number) -> Number CheckValueInputIs(node, 0, Type::Number()); CheckValueInputIs(node, 1, Type::Number()); CheckTypeIs(node, Type::Number()); break; case IrOpcode::kNumberAbs: case IrOpcode::kNumberCeil: case IrOpcode::kNumberFloor: case IrOpcode::kNumberFround: case IrOpcode::kNumberAcos: case IrOpcode::kNumberAcosh: case IrOpcode::kNumberAsin: case IrOpcode::kNumberAsinh: case IrOpcode::kNumberAtan: case IrOpcode::kNumberAtanh: case IrOpcode::kNumberCos: case IrOpcode::kNumberCosh: case IrOpcode::kNumberExp: case IrOpcode::kNumberExpm1: case IrOpcode::kNumberLog: case IrOpcode::kNumberLog1p: case IrOpcode::kNumberLog2: case IrOpcode::kNumberLog10: case IrOpcode::kNumberCbrt: case IrOpcode::kNumberRound: case IrOpcode::kNumberSign: case IrOpcode::kNumberSin: case IrOpcode::kNumberSinh: case IrOpcode::kNumberSqrt: case IrOpcode::kNumberTan: case IrOpcode::kNumberTanh: case IrOpcode::kNumberTrunc: // Number -> Number CheckValueInputIs(node, 0, Type::Number()); CheckTypeIs(node, Type::Number()); break; case IrOpcode::kNumberToBoolean: // Number -> Boolean CheckValueInputIs(node, 0, Type::Number()); CheckTypeIs(node, Type::Boolean()); break; case IrOpcode::kNumberToInt32: // Number -> Signed32 CheckValueInputIs(node, 0, Type::Number()); CheckTypeIs(node, Type::Signed32()); break; case IrOpcode::kNumberToUint32: case IrOpcode::kNumberToUint8Clamped: // Number -> Unsigned32 CheckValueInputIs(node, 0, Type::Number()); CheckTypeIs(node, Type::Unsigned32()); break; case IrOpcode::kPlainPrimitiveToNumber: // PlainPrimitive -> Number CheckValueInputIs(node, 0, Type::PlainPrimitive()); CheckTypeIs(node, Type::Number()); break; case IrOpcode::kPlainPrimitiveToWord32: // PlainPrimitive -> Integral32 CheckValueInputIs(node, 0, Type::PlainPrimitive()); CheckTypeIs(node, Type::Integral32()); break; case IrOpcode::kPlainPrimitiveToFloat64: // PlainPrimitive -> Number CheckValueInputIs(node, 0, Type::PlainPrimitive()); CheckTypeIs(node, Type::Number()); break; case IrOpcode::kStringEqual: case IrOpcode::kStringLessThan: case IrOpcode::kStringLessThanOrEqual: // (String, String) -> Boolean CheckValueInputIs(node, 0, Type::String()); CheckValueInputIs(node, 1, Type::String()); CheckTypeIs(node, Type::Boolean()); break; case IrOpcode::kStringCharCodeAt: // (String, Unsigned32) -> UnsignedSmall CheckValueInputIs(node, 0, Type::String()); CheckValueInputIs(node, 1, Type::Unsigned32()); CheckTypeIs(node, Type::UnsignedSmall()); break; case IrOpcode::kStringFromCharCode: // Number -> String CheckValueInputIs(node, 0, Type::Number()); CheckTypeIs(node, Type::String()); break; case IrOpcode::kStringFromCodePoint: // (Unsigned32) -> String CheckValueInputIs(node, 0, Type::Number()); CheckTypeIs(node, Type::String()); break; case IrOpcode::kReferenceEqual: { // (Unique, Any) -> Boolean and // (Any, Unique) -> Boolean CheckTypeIs(node, Type::Boolean()); break; } case IrOpcode::kObjectIsCallable: case IrOpcode::kObjectIsNumber: case IrOpcode::kObjectIsReceiver: case IrOpcode::kObjectIsSmi: case IrOpcode::kObjectIsString: case IrOpcode::kObjectIsUndetectable: case IrOpcode::kArrayBufferWasNeutered: CheckValueInputIs(node, 0, Type::Any()); CheckTypeIs(node, Type::Boolean()); break; case IrOpcode::kNewRestParameterElements: case IrOpcode::kNewUnmappedArgumentsElements: CheckTypeIs(node, Type::OtherInternal()); break; case IrOpcode::kAllocate: CheckValueInputIs(node, 0, Type::PlainNumber()); break; case IrOpcode::kEnsureWritableFastElements: CheckValueInputIs(node, 0, Type::Any()); CheckValueInputIs(node, 1, Type::Internal()); CheckTypeIs(node, Type::Internal()); break; case IrOpcode::kMaybeGrowFastElements: CheckValueInputIs(node, 0, Type::Any()); CheckValueInputIs(node, 1, Type::Internal()); CheckValueInputIs(node, 2, Type::Unsigned31()); CheckValueInputIs(node, 3, Type::Unsigned31()); CheckTypeIs(node, Type::Internal()); break; case IrOpcode::kTransitionElementsKind: CheckValueInputIs(node, 0, Type::Any()); CheckValueInputIs(node, 1, Type::Internal()); CheckValueInputIs(node, 2, Type::Internal()); CheckNotTyped(node); break; case IrOpcode::kChangeTaggedSignedToInt32: { // Signed32 /\\ Tagged -> Signed32 /\\ UntaggedInt32 // TODO(neis): Activate once ChangeRepresentation works in typer. // Type* from = Type::Intersect(Type::Signed32(), Type::Tagged()); // Type* to = Type::Intersect(Type::Signed32(), Type::UntaggedInt32()); // CheckValueInputIs(node, 0, from)); // CheckTypeIs(node, to)); break; } case IrOpcode::kChangeTaggedToInt32: { // Signed32 /\\ Tagged -> Signed32 /\\ UntaggedInt32 // TODO(neis): Activate once ChangeRepresentation works in typer. // Type* from = Type::Intersect(Type::Signed32(), Type::Tagged()); // Type* to = Type::Intersect(Type::Signed32(), Type::UntaggedInt32()); // CheckValueInputIs(node, 0, from)); // CheckTypeIs(node, to)); break; } case IrOpcode::kChangeTaggedToUint32: { // Unsigned32 /\\ Tagged -> Unsigned32 /\\ UntaggedInt32 // TODO(neis): Activate once ChangeRepresentation works in typer. // Type* from = Type::Intersect(Type::Unsigned32(), Type::Tagged()); // Type* to =Type::Intersect(Type::Unsigned32(), Type::UntaggedInt32()); // CheckValueInputIs(node, 0, from)); // CheckTypeIs(node, to)); break; } case IrOpcode::kChangeTaggedToFloat64: { // NumberOrUndefined /\\ Tagged -> Number /\\ UntaggedFloat64 // TODO(neis): Activate once ChangeRepresentation works in typer. // Type* from = Type::Intersect(Type::Number(), Type::Tagged()); // Type* to = Type::Intersect(Type::Number(), Type::UntaggedFloat64()); // CheckValueInputIs(node, 0, from)); // CheckTypeIs(node, to)); break; } case IrOpcode::kTruncateTaggedToFloat64: { // NumberOrUndefined /\\ Tagged -> Number /\\ UntaggedFloat64 // TODO(neis): Activate once ChangeRepresentation works in typer. // Type* from = Type::Intersect(Type::NumberOrUndefined(), // Type::Tagged()); // Type* to = Type::Intersect(Type::Number(), Type::UntaggedFloat64()); // CheckValueInputIs(node, 0, from)); // CheckTypeIs(node, to)); break; } case IrOpcode::kChangeInt31ToTaggedSigned: { // Signed31 /\\ UntaggedInt32 -> Signed31 /\\ Tagged // TODO(neis): Activate once ChangeRepresentation works in typer. // Type* from =Type::Intersect(Type::Signed31(), Type::UntaggedInt32()); // Type* to = Type::Intersect(Type::Signed31(), Type::Tagged()); // CheckValueInputIs(node, 0, from)); // CheckTypeIs(node, to)); break; } case IrOpcode::kChangeInt32ToTagged: { // Signed32 /\\ UntaggedInt32 -> Signed32 /\\ Tagged // TODO(neis): Activate once ChangeRepresentation works in typer. // Type* from =Type::Intersect(Type::Signed32(), Type::UntaggedInt32()); // Type* to = Type::Intersect(Type::Signed32(), Type::Tagged()); // CheckValueInputIs(node, 0, from)); // CheckTypeIs(node, to)); break; } case IrOpcode::kChangeUint32ToTagged: { // Unsigned32 /\\ UntaggedInt32 -> Unsigned32 /\\ Tagged // TODO(neis): Activate once ChangeRepresentation works in typer. // Type* from=Type::Intersect(Type::Unsigned32(),Type::UntaggedInt32()); // Type* to = Type::Intersect(Type::Unsigned32(), Type::Tagged()); // CheckValueInputIs(node, 0, from)); // CheckTypeIs(node, to)); break; } case IrOpcode::kChangeFloat64ToTagged: { // Number /\\ UntaggedFloat64 -> Number /\\ Tagged // TODO(neis): Activate once ChangeRepresentation works in typer. // Type* from =Type::Intersect(Type::Number(), Type::UntaggedFloat64()); // Type* to = Type::Intersect(Type::Number(), Type::Tagged()); // CheckValueInputIs(node, 0, from)); // CheckTypeIs(node, to)); break; } case IrOpcode::kChangeFloat64ToTaggedPointer: break; case IrOpcode::kChangeTaggedToBit: { // Boolean /\\ TaggedPtr -> Boolean /\\ UntaggedInt1 // TODO(neis): Activate once ChangeRepresentation works in typer. // Type* from = Type::Intersect(Type::Boolean(), Type::TaggedPtr()); // Type* to = Type::Intersect(Type::Boolean(), Type::UntaggedInt1()); // CheckValueInputIs(node, 0, from)); // CheckTypeIs(node, to)); break; } case IrOpcode::kChangeBitToTagged: { // Boolean /\\ UntaggedInt1 -> Boolean /\\ TaggedPtr // TODO(neis): Activate once ChangeRepresentation works in typer. // Type* from = Type::Intersect(Type::Boolean(), Type::UntaggedInt1()); // Type* to = Type::Intersect(Type::Boolean(), Type::TaggedPtr()); // CheckValueInputIs(node, 0, from)); // CheckTypeIs(node, to)); break; } case IrOpcode::kTruncateTaggedToWord32: { // Number /\\ Tagged -> Signed32 /\\ UntaggedInt32 // TODO(neis): Activate once ChangeRepresentation works in typer. // Type* from = Type::Intersect(Type::Number(), Type::Tagged()); // Type* to = Type::Intersect(Type::Number(), Type::UntaggedInt32()); // CheckValueInputIs(node, 0, from)); // CheckTypeIs(node, to)); break; } case IrOpcode::kTruncateTaggedToBit: break; case IrOpcode::kCheckBounds: CheckValueInputIs(node, 0, Type::Any()); CheckValueInputIs(node, 1, Type::Unsigned31()); CheckTypeIs(node, Type::Unsigned31()); break; case IrOpcode::kCheckHeapObject: CheckValueInputIs(node, 0, Type::Any()); break; case IrOpcode::kCheckIf: CheckValueInputIs(node, 0, Type::Boolean()); CheckNotTyped(node); break; case IrOpcode::kCheckMaps: // (Any, Internal, ..., Internal) -> Any CheckValueInputIs(node, 0, Type::Any()); for (int i = 1; i < node->op()->ValueInputCount(); ++i) { CheckValueInputIs(node, i, Type::Internal()); } CheckNotTyped(node); break; case IrOpcode::kCheckNumber: CheckValueInputIs(node, 0, Type::Any()); CheckTypeIs(node, Type::Number()); break; case IrOpcode::kCheckSmi: CheckValueInputIs(node, 0, Type::Any()); break; case IrOpcode::kCheckString: CheckValueInputIs(node, 0, Type::Any()); CheckTypeIs(node, Type::String()); break; case IrOpcode::kCheckedInt32Add: case IrOpcode::kCheckedInt32Sub: case IrOpcode::kCheckedInt32Div: case IrOpcode::kCheckedInt32Mod: case IrOpcode::kCheckedUint32Div: case IrOpcode::kCheckedUint32Mod: case IrOpcode::kCheckedInt32Mul: case IrOpcode::kCheckedInt32ToTaggedSigned: case IrOpcode::kCheckedUint32ToInt32: case IrOpcode::kCheckedUint32ToTaggedSigned: case IrOpcode::kCheckedFloat64ToInt32: case IrOpcode::kCheckedTaggedSignedToInt32: case IrOpcode::kCheckedTaggedToInt32: case IrOpcode::kCheckedTaggedToFloat64: case IrOpcode::kCheckedTaggedToTaggedSigned: case IrOpcode::kCheckedTaggedToTaggedPointer: case IrOpcode::kCheckedTruncateTaggedToWord32: break; case IrOpcode::kCheckFloat64Hole: CheckValueInputIs(node, 0, Type::Number()); CheckTypeIs(node, Type::Number()); break; case IrOpcode::kCheckTaggedHole: CheckValueInputIs(node, 0, Type::Any()); CheckTypeIs(node, Type::NonInternal()); break; case IrOpcode::kConvertTaggedHoleToUndefined: CheckValueInputIs(node, 0, Type::Any()); CheckTypeIs(node, Type::NonInternal()); break; case IrOpcode::kLoadField: // Object -> fieldtype // TODO(rossberg): activate once machine ops are typed. // CheckValueInputIs(node, 0, Type::Object()); // CheckTypeIs(node, FieldAccessOf(node->op()).type)); break; case IrOpcode::kLoadBuffer: break; case IrOpcode::kLoadElement: // Object -> elementtype // TODO(rossberg): activate once machine ops are typed. // CheckValueInputIs(node, 0, Type::Object()); // CheckTypeIs(node, ElementAccessOf(node->op()).type)); break; case IrOpcode::kLoadTypedElement: break; case IrOpcode::kStoreField: // (Object, fieldtype) -> _|_ // TODO(rossberg): activate once machine ops are typed. // CheckValueInputIs(node, 0, Type::Object()); // CheckValueInputIs(node, 1, FieldAccessOf(node->op()).type)); CheckNotTyped(node); break; case IrOpcode::kStoreBuffer: break; case IrOpcode::kStoreElement: // (Object, elementtype) -> _|_ // TODO(rossberg): activate once machine ops are typed. // CheckValueInputIs(node, 0, Type::Object()); // CheckValueInputIs(node, 1, ElementAccessOf(node->op()).type)); CheckNotTyped(node); break; case IrOpcode::kStoreTypedElement: CheckNotTyped(node); break; case IrOpcode::kNumberSilenceNaN: CheckValueInputIs(node, 0, Type::Number()); CheckTypeIs(node, Type::Number()); break; case IrOpcode::kTypeGuard: CheckTypeIs(node, TypeGuardTypeOf(node->op())); break; // Machine operators // ----------------------- case IrOpcode::kLoad: case IrOpcode::kProtectedLoad: case IrOpcode::kProtectedStore: case IrOpcode::kStore: case IrOpcode::kStackSlot: case IrOpcode::kWord32And: case IrOpcode::kWord32Or: case IrOpcode::kWord32Xor: case IrOpcode::kWord32Shl: case IrOpcode::kWord32Shr: case IrOpcode::kWord32Sar: case IrOpcode::kWord32Ror: case IrOpcode::kWord32Equal: case IrOpcode::kWord32Clz: case IrOpcode::kWord32Ctz: case IrOpcode::kWord32ReverseBits: case IrOpcode::kWord32ReverseBytes: case IrOpcode::kWord32Popcnt: case IrOpcode::kWord64And: case IrOpcode::kWord64Or: case IrOpcode::kWord64Xor: case IrOpcode::kWord64Shl: case IrOpcode::kWord64Shr: case IrOpcode::kWord64Sar: case IrOpcode::kWord64Ror: case IrOpcode::kWord64Clz: case IrOpcode::kWord64Popcnt: case IrOpcode::kWord64Ctz: case IrOpcode::kWord64ReverseBits: case IrOpcode::kWord64ReverseBytes: case IrOpcode::kWord64Equal: case IrOpcode::kInt32Add: case IrOpcode::kInt32AddWithOverflow: case IrOpcode::kInt32Sub: case IrOpcode::kInt32SubWithOverflow: case IrOpcode::kInt32Mul: case IrOpcode::kInt32MulWithOverflow: case IrOpcode::kInt32MulHigh: case IrOpcode::kInt32Div: case IrOpcode::kInt32Mod: case IrOpcode::kInt32LessThan: case IrOpcode::kInt32LessThanOrEqual: case IrOpcode::kUint32Div: case IrOpcode::kUint32Mod: case IrOpcode::kUint32MulHigh: case IrOpcode::kUint32LessThan: case IrOpcode::kUint32LessThanOrEqual: case IrOpcode::kInt64Add: case IrOpcode::kInt64AddWithOverflow: case IrOpcode::kInt64Sub: case IrOpcode::kInt64SubWithOverflow: case IrOpcode::kInt64Mul: case IrOpcode::kInt64Div: case IrOpcode::kInt64Mod: case IrOpcode::kInt64LessThan: case IrOpcode::kInt64LessThanOrEqual: case IrOpcode::kUint64Div: case IrOpcode::kUint64Mod: case IrOpcode::kUint64LessThan: case IrOpcode::kUint64LessThanOrEqual: case IrOpcode::kFloat32Add: case IrOpcode::kFloat32Sub: case IrOpcode::kFloat32Neg: case IrOpcode::kFloat32Mul: case IrOpcode::kFloat32Div: case IrOpcode::kFloat32Abs: case IrOpcode::kFloat32Sqrt: case IrOpcode::kFloat32Equal: case IrOpcode::kFloat32LessThan: case IrOpcode::kFloat32LessThanOrEqual: case IrOpcode::kFloat32Max: case IrOpcode::kFloat32Min: case IrOpcode::kFloat64Add: case IrOpcode::kFloat64Sub: case IrOpcode::kFloat64Neg: case IrOpcode::kFloat64Mul: case IrOpcode::kFloat64Div: case IrOpcode::kFloat64Mod: case IrOpcode::kFloat64Max: case IrOpcode::kFloat64Min: case IrOpcode::kFloat64Abs: case IrOpcode::kFloat64Acos: case IrOpcode::kFloat64Acosh: case IrOpcode::kFloat64Asin: case IrOpcode::kFloat64Asinh: case IrOpcode::kFloat64Atan: case IrOpcode::kFloat64Atan2: case IrOpcode::kFloat64Atanh: case IrOpcode::kFloat64Cbrt: case IrOpcode::kFloat64Cos: case IrOpcode::kFloat64Cosh: case IrOpcode::kFloat64Exp: case IrOpcode::kFloat64Expm1: case IrOpcode::kFloat64Log: case IrOpcode::kFloat64Log1p: case IrOpcode::kFloat64Log10: case IrOpcode::kFloat64Log2: case IrOpcode::kFloat64Pow: case IrOpcode::kFloat64Sin: case IrOpcode::kFloat64Sinh: case IrOpcode::kFloat64Sqrt: case IrOpcode::kFloat64Tan: case IrOpcode::kFloat64Tanh: case IrOpcode::kFloat32RoundDown: case IrOpcode::kFloat64RoundDown: case IrOpcode::kFloat32RoundUp: case IrOpcode::kFloat64RoundUp: case IrOpcode::kFloat32RoundTruncate: case IrOpcode::kFloat64RoundTruncate: case IrOpcode::kFloat64RoundTiesAway: case IrOpcode::kFloat32RoundTiesEven: case IrOpcode::kFloat64RoundTiesEven: case IrOpcode::kFloat64Equal: case IrOpcode::kFloat64LessThan: case IrOpcode::kFloat64LessThanOrEqual: case IrOpcode::kTruncateInt64ToInt32: case IrOpcode::kRoundFloat64ToInt32: case IrOpcode::kRoundInt32ToFloat32: case IrOpcode::kRoundInt64ToFloat32: case IrOpcode::kRoundInt64ToFloat64: case IrOpcode::kRoundUint32ToFloat32: case IrOpcode::kRoundUint64ToFloat64: case IrOpcode::kRoundUint64ToFloat32: case IrOpcode::kTruncateFloat64ToFloat32: case IrOpcode::kTruncateFloat64ToWord32: case IrOpcode::kBitcastFloat32ToInt32: case IrOpcode::kBitcastFloat64ToInt64: case IrOpcode::kBitcastInt32ToFloat32: case IrOpcode::kBitcastInt64ToFloat64: case IrOpcode::kBitcastTaggedToWord: case IrOpcode::kBitcastWordToTagged: case IrOpcode::kBitcastWordToTaggedSigned: case IrOpcode::kChangeInt32ToInt64: case IrOpcode::kChangeUint32ToUint64: case IrOpcode::kChangeInt32ToFloat64: case IrOpcode::kChangeUint32ToFloat64: case IrOpcode::kChangeFloat32ToFloat64: case IrOpcode::kChangeFloat64ToInt32: case IrOpcode::kChangeFloat64ToUint32: case IrOpcode::kFloat64SilenceNaN: case IrOpcode::kTruncateFloat64ToUint32: case IrOpcode::kTruncateFloat32ToInt32: case IrOpcode::kTruncateFloat32ToUint32: case IrOpcode::kTryTruncateFloat32ToInt64: case IrOpcode::kTryTruncateFloat64ToInt64: case IrOpcode::kTryTruncateFloat32ToUint64: case IrOpcode::kTryTruncateFloat64ToUint64: case IrOpcode::kFloat64ExtractLowWord32: case IrOpcode::kFloat64ExtractHighWord32: case IrOpcode::kFloat64InsertLowWord32: case IrOpcode::kFloat64InsertHighWord32: case IrOpcode::kInt32PairAdd: case IrOpcode::kInt32PairSub: case IrOpcode::kInt32PairMul: case IrOpcode::kWord32PairShl: case IrOpcode::kWord32PairShr: case IrOpcode::kWord32PairSar: case IrOpcode::kLoadStackPointer: case IrOpcode::kLoadFramePointer: case IrOpcode::kLoadParentFramePointer: case IrOpcode::kUnalignedLoad: case IrOpcode::kUnalignedStore: case IrOpcode::kCheckedLoad: case IrOpcode::kCheckedStore: case IrOpcode::kAtomicLoad: case IrOpcode::kAtomicStore: #define SIMD_MACHINE_OP_CASE(Name) case IrOpcode::k##Name: MACHINE_SIMD_OP_LIST(SIMD_MACHINE_OP_CASE) #undef SIMD_MACHINE_OP_CASE // TODO(rossberg): Check. break; } } // NOLINT(readability/fn_size) void Verifier::Run(Graph* graph, Typing typing, CheckInputs check_inputs) { CHECK_NOT_NULL(graph->start()); CHECK_NOT_NULL(graph->end()); Zone zone(graph->zone()->allocator(), ZONE_NAME); Visitor visitor(&zone, typing, check_inputs); AllNodes all(&zone, graph); for (Node* node : all.reachable) visitor.Check(node); // Check the uniqueness of projections. for (Node* proj : all.reachable) { if (proj->opcode() != IrOpcode::kProjection) continue; Node* node = proj->InputAt(0); for (Node* other : node->uses()) { if (all.IsLive(other) && other != proj && other->opcode() == IrOpcode::kProjection && ProjectionIndexOf(other->op()) == ProjectionIndexOf(proj->op())) { V8_Fatal(__FILE__, __LINE__, ""Node #%d:%s has duplicate projections #%d and #%d"", node->id(), node->op()->mnemonic(), proj->id(), other->id()); } } } } // ----------------------------------------------------------------------------- static bool HasDominatingDef(Schedule* schedule, Node* node, BasicBlock* container, BasicBlock* use_block, int use_pos) { BasicBlock* block = use_block; while (true) { while (use_pos >= 0) { if (block->NodeAt(use_pos) == node) return true; use_pos--; } block = block->dominator(); if (block == nullptr) break; use_pos = static_cast(block->NodeCount()) - 1; if (node == block->control_input()) return true; } return false; } static bool Dominates(Schedule* schedule, Node* dominator, Node* dominatee) { BasicBlock* dom = schedule->block(dominator); BasicBlock* sub = schedule->block(dominatee); while (sub != nullptr) { if (sub == dom) { return true; } sub = sub->dominator(); } return false; } static void CheckInputsDominate(Schedule* schedule, BasicBlock* block, Node* node, int use_pos) { for (int j = node->op()->ValueInputCount() - 1; j >= 0; j--) { BasicBlock* use_block = block; if (node->opcode() == IrOpcode::kPhi) { use_block = use_block->PredecessorAt(j); use_pos = static_cast(use_block->NodeCount()) - 1; } Node* input = node->InputAt(j); if (!HasDominatingDef(schedule, node->InputAt(j), block, use_block, use_pos)) { V8_Fatal(__FILE__, __LINE__, ""Node #%d:%s in B%d is not dominated by input@%d #%d:%s"", node->id(), node->op()->mnemonic(), block->rpo_number(), j, input->id(), input->op()->mnemonic()); } } // Ensure that nodes are dominated by their control inputs; // kEnd is an exception, as unreachable blocks resulting from kMerge // are not in the RPO. if (node->op()->ControlInputCount() == 1 && node->opcode() != IrOpcode::kEnd) { Node* ctl = NodeProperties::GetControlInput(node); if (!Dominates(schedule, ctl, node)) { V8_Fatal(__FILE__, __LINE__, ""Node #%d:%s in B%d is not dominated by control input #%d:%s"", node->id(), node->op()->mnemonic(), block->rpo_number(), ctl->id(), ctl->op()->mnemonic()); } } } void ScheduleVerifier::Run(Schedule* schedule) { const size_t count = schedule->BasicBlockCount(); Zone tmp_zone(schedule->zone()->allocator(), ZONE_NAME); Zone* zone = &tmp_zone; BasicBlock* start = schedule->start(); BasicBlockVector* rpo_order = schedule->rpo_order(); // Verify the RPO order contains only blocks from this schedule. CHECK_GE(count, rpo_order->size()); for (BasicBlockVector::iterator b = rpo_order->begin(); b != rpo_order->end(); ++b) { CHECK_EQ((*b), schedule->GetBlockById((*b)->id())); // All predecessors and successors should be in rpo and in this schedule. for (BasicBlock const* predecessor : (*b)->predecessors()) { CHECK_GE(predecessor->rpo_number(), 0); CHECK_EQ(predecessor, schedule->GetBlockById(predecessor->id())); } for (BasicBlock const* successor : (*b)->successors()) { CHECK_GE(successor->rpo_number(), 0); CHECK_EQ(successor, schedule->GetBlockById(successor->id())); } } // Verify RPO numbers of blocks. CHECK_EQ(start, rpo_order->at(0)); // Start should be first. for (size_t b = 0; b < rpo_order->size(); b++) { BasicBlock* block = rpo_order->at(b); CHECK_EQ(static_cast(b), block->rpo_number()); BasicBlock* dom = block->dominator(); if (b == 0) { // All blocks except start should have a dominator. CHECK_NULL(dom); } else { // Check that the immediate dominator appears somewhere before the block. CHECK_NOT_NULL(dom); CHECK_LT(dom->rpo_number(), block->rpo_number()); } } // Verify that all blocks reachable from start are in the RPO. BoolVector marked(static_cast(count), false, zone); { ZoneQueue queue(zone); queue.push(start); marked[start->id().ToSize()] = true; while (!queue.empty()) { BasicBlock* block = queue.front(); queue.pop(); for (size_t s = 0; s < block->SuccessorCount(); s++) { BasicBlock* succ = block->SuccessorAt(s); if (!marked[succ->id().ToSize()]) { marked[succ->id().ToSize()] = true; queue.push(succ); } } } } // Verify marked blocks are in the RPO. for (size_t i = 0; i < count; i++) { BasicBlock* block = schedule->GetBlockById(BasicBlock::Id::FromSize(i)); if (marked[i]) { CHECK_GE(block->rpo_number(), 0); CHECK_EQ(block, rpo_order->at(block->rpo_number())); } } // Verify RPO blocks are marked. for (size_t b = 0; b < rpo_order->size(); b++) { CHECK(marked[rpo_order->at(b)->id().ToSize()]); } { // Verify the dominance relation. ZoneVector dominators(zone); dominators.resize(count, nullptr); // Compute a set of all the nodes that dominate a given node by using // a forward fixpoint. O(n^2). ZoneQueue queue(zone); queue.push(start); dominators[start->id().ToSize()] = new (zone) BitVector(static_cast(count), zone); while (!queue.empty()) { BasicBlock* block = queue.front(); queue.pop(); BitVector* block_doms = dominators[block->id().ToSize()]; BasicBlock* idom = block->dominator(); if (idom != nullptr && !block_doms->Contains(idom->id().ToInt())) { V8_Fatal(__FILE__, __LINE__, ""Block B%d is not dominated by B%d"", block->rpo_number(), idom->rpo_number()); } for (size_t s = 0; s < block->SuccessorCount(); s++) { BasicBlock* succ = block->SuccessorAt(s); BitVector* succ_doms = dominators[succ->id().ToSize()]; if (succ_doms == nullptr) { // First time visiting the node. S.doms = B U B.doms succ_doms = new (zone) BitVector(static_cast(count), zone); succ_doms->CopyFrom(*block_doms); succ_doms->Add(block->id().ToInt()); dominators[succ->id().ToSize()] = succ_doms; queue.push(succ); } else { // Nth time visiting the successor. S.doms = S.doms ^ (B U B.doms) bool had = succ_doms->Contains(block->id().ToInt()); if (had) succ_doms->Remove(block->id().ToInt()); if (succ_doms->IntersectIsChanged(*block_doms)) queue.push(succ); if (had) succ_doms->Add(block->id().ToInt()); } } } // Verify the immediateness of dominators. for (BasicBlockVector::iterator b = rpo_order->begin(); b != rpo_order->end(); ++b) { BasicBlock* block = *b; BasicBlock* idom = block->dominator(); if (idom == nullptr) continue; BitVector* block_doms = dominators[block->id().ToSize()]; for (BitVector::Iterator it(block_doms); !it.Done(); it.Advance()) { BasicBlock* dom = schedule->GetBlockById(BasicBlock::Id::FromInt(it.Current())); if (dom != idom && !dominators[idom->id().ToSize()]->Contains(dom->id().ToInt())) { V8_Fatal(__FILE__, __LINE__, ""Block B%d is not immediately dominated by B%d"", block->rpo_number(), idom->rpo_number()); } } } } // Verify phis are placed in the block of their control input. for (BasicBlockVector::iterator b = rpo_order->begin(); b != rpo_order->end(); ++b) { for (BasicBlock::const_iterator i = (*b)->begin(); i != (*b)->end(); ++i) { Node* phi = *i; if (phi->opcode() != IrOpcode::kPhi) continue; // TODO(titzer): Nasty special case. Phis from RawMachineAssembler // schedules don't have control inputs. if (phi->InputCount() > phi->op()->ValueInputCount()) { Node* control = NodeProperties::GetControlInput(phi); CHECK(control->opcode() == IrOpcode::kMerge || control->opcode() == IrOpcode::kLoop); CHECK_EQ((*b), schedule->block(control)); } } } // Verify that all uses are dominated by their definitions. for (BasicBlockVector::iterator b = rpo_order->begin(); b != rpo_order->end(); ++b) { BasicBlock* block = *b; // Check inputs to control for this block. Node* control = block->control_input(); if (control != nullptr) { CHECK_EQ(block, schedule->block(control)); CheckInputsDominate(schedule, block, control, static_cast(block->NodeCount()) - 1); } // Check inputs for all nodes in the block. for (size_t i = 0; i < block->NodeCount(); i++) { Node* node = block->NodeAt(i); CheckInputsDominate(schedule, block, node, static_cast(i) - 1); } } } #ifdef DEBUG // static void Verifier::VerifyNode(Node* node) { CHECK_EQ(OperatorProperties::GetTotalInputCount(node->op()), node->InputCount()); // If this node has no effect or no control outputs, // we check that no its uses are effect or control inputs. bool check_no_control = node->op()->ControlOutputCount() == 0; bool check_no_effect = node->op()->EffectOutputCount() == 0; bool check_no_frame_state = node->opcode() != IrOpcode::kFrameState; if (check_no_effect || check_no_control) { for (Edge edge : node->use_edges()) { Node* const user = edge.from(); CHECK(!user->IsDead()); if (NodeProperties::IsControlEdge(edge)) { CHECK(!check_no_control); } else if (NodeProperties::IsEffectEdge(edge)) { CHECK(!check_no_effect); } else if (NodeProperties::IsFrameStateEdge(edge)) { CHECK(!check_no_frame_state); } } } // Frame state input should be a frame state (or sentinel). if (OperatorProperties::GetFrameStateInputCount(node->op()) > 0) { Node* input = NodeProperties::GetFrameStateInput(node); CHECK(input->opcode() == IrOpcode::kFrameState || input->opcode() == IrOpcode::kStart || input->opcode() == IrOpcode::kDead); } // Effect inputs should be effect-producing nodes (or sentinels). for (int i = 0; i < node->op()->EffectInputCount(); i++) { Node* input = NodeProperties::GetEffectInput(node, i); CHECK(input->op()->EffectOutputCount() > 0 || input->opcode() == IrOpcode::kDead); } // Control inputs should be control-producing nodes (or sentinels). for (int i = 0; i < node->op()->ControlInputCount(); i++) { Node* input = NodeProperties::GetControlInput(node, i); CHECK(input->op()->ControlOutputCount() > 0 || input->opcode() == IrOpcode::kDead); } } void Verifier::VerifyEdgeInputReplacement(const Edge& edge, const Node* replacement) { // Check that the user does not misuse the replacement. DCHECK(!NodeProperties::IsControlEdge(edge) || replacement->op()->ControlOutputCount() > 0); DCHECK(!NodeProperties::IsEffectEdge(edge) || replacement->op()->EffectOutputCount() > 0); DCHECK(!NodeProperties::IsFrameStateEdge(edge) || replacement->opcode() == IrOpcode::kFrameState); } #endif // DEBUG } // namespace compiler } // namespace internal } // namespace v8 ",16134,True,3143.690964137281,median "//// This guide is maintained in the main Quarkus repository and pull requests should be submitted there: https://github.com/quarkusio/quarkus/tree/main/docs/src/main/asciidoc //// = Kubernetes extension include::./attributes.adoc[] Quarkus offers the ability to automatically generate Kubernetes resources based on sane defaults and user-supplied configuration using https://github.com/dekorateio/dekorate/[dekorate]. It currently supports generating resources for vanilla <<#kubernetes,Kubernetes>>, <<#openshift,OpenShift>> and <<#knative,Knative>>. Furthermore, Quarkus can deploy the application to a target Kubernetes cluster by applying the generated manifests to the target cluster's API Server. Finally, when either one of container image extensions is present (see the xref:container-imag.adoc[container image guide] for more details), Quarkus has the ability to create a container image and push it to a registry *before* deploying the application to the target platform. == Prerequisites To complete this guide, you need: * roughly 10 minutes * an IDE * JDK 11+ installed with `JAVA_HOME` configured appropriately * Apache Maven {maven-version} * access to a Kubernetes cluster (Minikube is a viable option) [#kubernetes] == Kubernetes Let's create a new project that contains both the Kubernetes and Jib extensions: [source,bash,subs=attributes+] ---- mvn io.quarkus.platform:quarkus-maven-plugin:{quarkus-version}:create \\ -DprojectGroupId=org.acme \\ -DprojectArtifactId=kubernetes-quickstart \\ -DclassName=""org.acme.rest.GreetingResource"" \\ -Dpath=""/greeting"" \\ -Dextensions=""resteasy,kubernetes,jib"" cd kubernetes-quickstart ---- This added the following dependencies to the `pom.xml` [source,xml] ---- io.quarkus quarkus-kubernetes io.quarkus quarkus-container-image-jib ---- By adding these dependencies, we enable the generation of Kubernetes manifests each time we perform a build while also enabling the build of a container image using Jib. For example, following the execution of `./mvnw package`, you will notice amongst the other files that are created, two files named `kubernetes.json` and `kubernetes.yml` in the `target/kubernetes/` directory. If you look at either file you will see that it contains both a Kubernetes `Deployment` and a `Service`. The full source of the `kubernetes.json` file looks something like this: [source,json] ---- { { ""apiVersion"" : ""apps/v1"", ""kind"" : ""Deployment"", ""metadata"" : { ""annotations"": { ""app.quarkus.io/vcs-url"" : """", ""app.quarkus.io/commit-id"" : """", }, ""labels"" : { ""app.kubernetes.io/name"" : ""test-quarkus-app"", ""app.kubernetes.io/version"" : ""1.0.0-SNAPSHOT"", }, ""name"" : ""test-quarkus-app"" }, ""spec"" : { ""replicas"" : 1, ""selector"" : { ""matchLabels"" : { ""app.kubernetes.io/name"" : ""test-quarkus-app"", ""app.kubernetes.io/version"" : ""1.0.0-SNAPSHOT"", } }, ""template"" : { ""metadata"" : { ""labels"" : { ""app.kubernetes.io/name"" : ""test-quarkus-app"", ""app.kubernetes.io/version"" : ""1.0.0-SNAPSHOT"" } }, ""spec"" : { ""containers"" : [ { ""env"" : [ { ""name"" : ""KUBERNETES_NAMESPACE"", ""valueFrom"" : { ""fieldRef"" : { ""fieldPath"" : ""metadata.namespace"" } } } ], ""image"" : ""yourDockerUsername/test-quarkus-app:1.0.0-SNAPSHOT"", ""imagePullPolicy"" : ""Always"", ""name"" : ""test-quarkus-app"" } ] } } } }, { ""apiVersion"" : ""v1"", ""kind"" : ""Service"", ""metadata"" : { ""annotations"": { ""app.quarkus.io/vcs-url"" : """", ""app.quarkus.io/commit-id"" : """", }, ""labels"" : { ""app.kubernetes.io/name"" : ""test-quarkus-app"", ""app.kubernetes.io/version"" : ""1.0.0-SNAPSHOT"", }, ""name"" : ""test-quarkus-app"" }, ""spec"" : { ""ports"" : [ { ""name"" : ""http"", ""port"" : 8080, ""targetPort"" : 8080 } ], ""selector"" : { ""app.kubernetes.io/name"" : ""test-quarkus-app"", ""app.kubernetes.io/version"" : ""1.0.0-SNAPSHOT"" }, ""type"" : ""ClusterIP"" } } } ---- Beside generating a `Deployment` resource, you can also choose to get a `StatefulSet` instead via `application.properties`: [source,properties] ---- quarkus.kubernetes.deployment-kind=StatefulSet ---- The generated manifest can be applied to the cluster from the project root using `kubectl`: [source,bash] ---- kubectl apply -f target/kubernetes/kubernetes.json ---- An important thing to note about the `Deployment` (or `StatefulSet`) is that is uses `yourDockerUsername/test-quarkus-app:1.0.0-SNAPSHOT` as the container image of the `Pod`. The name of the image is controlled by the Jib extension and can be customized using the usual `application.properties`. For example with a configuration like: [source,properties] ---- quarkus.container-image.group=quarkus #optional, default to the system user name quarkus.container-image.name=demo-app #optional, defaults to the application name quarkus.container-image.tag=1.0 #optional, defaults to the application version ---- The image that will be used in the generated manifests will be `quarkus/demo-app:1.0` === Namespace By default Quarkus omits the namespace in the generated manifests, rather than enforce the `default` namespace. That means that you can apply the manifest to your chosen namespace when using `kubctl`, which in the example below is `test`: [source,bash] ---- kubectl apply -f target/kubernetes/kubernetes.json -n=test ---- To specify the namespace in your manifest customize with the following property in your `application.properties`: [source,properties] ---- quarkus.kubernetes.namespace=mynamespace ---- === Defining a Docker registry The Docker registry can be specified with the following property: [source,properties] ---- quarkus.container-image.registry=my.docker-registry.net ---- By adding this property along with the rest of the container image properties of the previous section, the generated manifests will use the image `my.docker-registry.net/quarkus/demo-app:1.0`. The image is not the only thing that can be customized in the generated manifests, as will become evident in the following sections. === Labels and Annotations ==== Labels The generated manifests use the Kubernetes link:https://kubernetes.io/docs/concepts/overview/working-with-objects/common-labels[recommended labels]. These labels can be customized using `quarkus.kubernetes.name`, `quarkus.kubernetes.version` and `quarkus.kubernetes.part-of`. For example by adding the following configuration to your `application.properties`: [source,properties] ---- quarkus.kubernetes.part-of=todo-app quarkus.kubernetes.name=todo-rest quarkus.kubernetes.version=1.0-rc.1 ---- [NOTE] ==== As is described in detail in the <<#openshift, OpenShift>> section, customizing OpenShift (or Knative) properties is done in the same way, but replacing `kubernetes` with `openshift` (or `knative`). The previous example for OpenShift would look like this: [source,properties] ---- quarkus.openshift.part-of=todo-app quarkus.openshift.name=todo-rest quarkus.openshift.version=1.0-rc.1 ---- ==== The labels in generated resources will look like: [source, json] ---- ""labels"" : { ""app.kubernetes.io/part-of"" : ""todo-app"", ""app.kubernetes.io/name"" : ""todo-rest"", ""app.kubernetes.io/version"" : ""1.0-rc.1"" } ---- ==== Custom Labels To add additional custom labels, for example `foo=bar` just apply the following configuration: [source,properties] ---- quarkus.kubernetes.labels.foo=bar ---- NOTE: When using the `quarkus-container-image-jib` extension to build a container image, then any label added via the aforementioned property will also be added to the generated container image. ==== Annotations Out of the box, the generated resources will be annotated with version control related information that can be used either by tooling, or by the user for troubleshooting purposes. [source,json] ---- ""annotations"": { ""app.quarkus.io/vcs-url"" : """", ""app.quarkus.io/commit-id"" : """", } ---- ==== Custom Annotations Custom annotations can be added in a way similar to labels.For example to add the annotation `foo=bar` and `app.quarkus/id=42` just apply the following configuration: [source,properties] ---- quarkus.kubernetes.annotations.foo=bar quarkus.kubernetes.annotations.""app.quarkus/id""=42 ---- [#env-vars] ==== Environment variables Kubernetes provides multiple ways of defining environment variables: - key/value pairs - import all values from a Secret or ConfigMap - interpolate a single value identified by a given field in a Secret or ConfigMap - interpolate a value from a field within the same resource ===== Environment variables from key/value pairs To add a key/value pair as an environment variable in the generated resources: [source,properties] ---- quarkus.kubernetes.env.vars.my-env-var=foobar ---- The command above will add `MY_ENV_VAR=foobar` as an environment variable. Please note that the key `my-env-var` will be converted to uppercase and dashes will be replaced by underscores resulting in `MY_ENV_VAR`. [[secret-mapping]] ===== Environment variables from Secret To add all key/value pairs of `Secret` as environment variables just apply the following configuration, separating each `Secret` to be used as source by a comma (`,`): [source,properties] ---- quarkus.kubernetes.env.secrets=my-secret,my-other-secret ---- which would generate the following in the container definition: [source,yaml] ---- envFrom: - secretRef: name: my-secret optional: false - secretRef: name: my-other-secret optional: false ---- The following extracts a value identified by the `keyName` field from the `my-secret` Secret into a `foo` environment variable: [source,properties] ---- quarkus.kubernetes.env.mapping.foo.from-secret=my-secret quarkus.kubernetes.env.mapping.foo.with-key=keyName ---- This would generate the following in the `env` section of your container: [source,yaml] ---- - env: - name: FOO valueFrom: secretKeyRef: key: keyName name: my-secret optional: false ---- ===== Environment variables from ConfigMap To add all key/value pairs from `ConfigMap` as environment variables just apply the following configuration, separating each `ConfigMap` to be used as source by a comma (`,`): [source,properties] ---- quarkus.kubernetes.env.configmaps=my-config-map,another-config-map ---- which would generate the following in the container definition: [source,yaml] ---- envFrom: - configMapRef: name: my-config-map optional: false - configMapRef: name: another-config-map optional: false ---- The following extracts a value identified by the `keyName` field from the `my-config-map` ConfigMap into a `foo` environment variable: [source,properties] ---- quarkus.kubernetes.env.mapping.foo.from-configmap=my-configmap quarkus.kubernetes.env.mapping.foo.with-key=keyName ---- This would generate the following in the `env` section of your container: [source,yaml] ---- - env: - name: FOO valueFrom: configMapRefKey: key: keyName name: my-configmap optional: false ---- ===== Environment variables from fields It's also possible to use the value from another field to add a new environment variable by specifying the path of the field to be used as a source, as follows: [source,properties] ---- quarkus.kubernetes.env.fields.foo=metadata.name ---- [NOTE] ==== As is described in detail in the <<#openshift, OpenShift>> section, customizing OpenShift properties is done in the same way, but replacing `kubernetes` with `openshift`. The previous example for OpenShift would look like this: [source,properties] ---- quarkus.openshift.env.fields.foo=metadata.name ---- ==== ===== Validation A conflict between two definitions, e.g. mistakenly assigning both a value and specifying that a variable is derived from a field, will result in an error being thrown at build time so that you get the opportunity to fix the issue before you deploy your application to your cluster where it might be more difficult to diagnose the source of the issue. Similarly, two redundant definitions, e.g. defining an injection from the same secret twice, will not cause an issue but will indeed report a warning to let you know that you might not have intended to duplicate that definition. [#env-vars-backwards] ===== Backwards compatibility Previous versions of the Kubernetes extension supported a different syntax to add environment variables.The older syntax is still supported but is deprecated and it's advised that you migrate to the new syntax. .Old vs. new syntax |==== | |Old | New | | Plain variable |`quarkus.kubernetes.env-vars.my-env-var.value=foobar` | `quarkus.kubernetes.env.vars.my-env-var=foobar` | | From field |`quarkus.kubernetes.env-vars.my-env-var.field=foobar` | `quarkus.kubernetes.env.fields.my-env-var=foobar` | | All from `ConfigMap` |`quarkus.kubernetes.env-vars.xxx.configmap=foobar` | `quarkus.kubernetes.env.configmaps=foobar` | | All from `Secret` |`quarkus.kubernetes.env-vars.xxx.secret=foobar` | `quarkus.kubernetes.env.secrets=foobar` | | From one `Secret` field |`quarkus.kubernetes.env-vars.foo.secret=foobar` | `quarkus.kubernetes.env.mapping.foo.from-secret=foobar` | | |`quarkus.kubernetes.env-vars.foo.value=field` | `quarkus.kubernetes.env.mapping.foo.with-key=field` | | From one `ConfigMap` field |`quarkus.kubernetes.env-vars.foo.configmap=foobar` | `quarkus.kubernetes.env.mapping.foo.from-configmap=foobar` | | |`quarkus.kubernetes.env-vars.foo.value=field` | `quarkus.kubernetes.env.mapping.foo.with-key=field` | |==== NOTE: If you redefine the same variable using the new syntax while keeping the old syntax, **ONLY** the new version will be kept and a warning will be issued to alert you of the problem.For example, if you define both `quarkus.kubernetes.env-vars.my-env-var.value=foobar` and `quarkus.kubernetes.env.vars.my-env-var=newValue`, the extension will only generate an environment variable `MY_ENV_VAR=newValue` and issue a warning. ==== Mounting volumes The Kubernetes extension allows the user to configure both volumes and mounts for the application. Any volume can be mounted with a simple configuration: [source,properties] ---- quarkus.kubernetes.mounts.my-volume.path=/where/to/mount ---- This will add a mount to the pod for volume `my-volume` to path `/where/to/mount`. The volumes themselves can be configured as shown in the sections below. ===== Secret volumes [source,properties] ---- quarkus.kubernetes.secret-volumes.my-volume.secret-name=my-secret ---- ===== ConfigMap volumes [source,properties] ---- quarkus.kubernetes.config-map-volumes.my-volume.config-map-name=my-secret ---- ==== Passing application configuration Quarkus supports passing configuration from external locations (via Smallrye Config). This usually requires setting an additional environment variable or system propertiy. When you need to use a secret or a config map for the purpose of application configuration, you need to: - define a volume - mount the volume - create an environment variable for `SMALLRYE_CONFIG_LOCATIONS` To simplify things, quarkus provides single step alternative: [source,properties] ---- quarkus.kubernetes.app-secret= ---- or [source,properties] ---- quarkus.kubernetes.app-config-map= ---- When these properties are used, the generated manifests will contain everything required. The application config volumes will be created using path: `/mnt/app-secret` and `/mnt/app-config-map` for secrets and configmaps respectively. Note: Users may use both properties at the same time. === Changing the number of replicas: To change the number of replicas from 1 to 3: [source,properties] ---- quarkus.kubernetes.replicas=3 ---- === Add readiness and liveness probes By default, the Kubernetes resources do not contain readiness and liveness probes in the generated `Deployment`. Adding them however is just a matter of adding the SmallRye Health extension like so: [source,xml] ---- io.quarkus quarkus-smallrye-health ---- The values of the generated probes will be determined by the configured health properties: `quarkus.smallrye-health.root-path`, `quarkus.smallrye-health.liveness-path` and `quarkus.smallrye-health.readiness-path`. More information about the health extension can be found in the relevant xref:microprofile-health.adoc[guide]. === Customizing the readiness probe: To set the initial delay of the probe to 20 seconds and the period to 45: [source,properties] ---- quarkus.kubernetes.readiness-probe.initial-delay=20s quarkus.kubernetes.readiness-probe.period=45s ---- === Add hostAliases To add entries to a Pod's `/etc/hosts` file (more information can be found in https://kubernetes.io/docs/concepts/services-networking/add-entries-to-pod-etc-hosts-with-host-aliases/[Kubernetes documentation]), just apply the following configuration: [source,properties] ---- quarkus.kubernetes.hostaliases.""10.0.0.0"".hostnames=foo.com,bar.org ---- This would generate the following `hostAliases` section in the `deployment` definition: [source,yaml] ---- kind: Deployment spec: template: spec: hostAliases: - hostnames: - foo.com - bar.org ip: 10.0.0.0 ---- === Container Resources Management CPU & Memory limits and requests can be applied to a `Container` (more info in https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/[Kubernetes documentation]) using the following configuration: [source] ---- quarkus.kubernetes.resources.requests.memory=64Mi quarkus.kubernetes.resources.requests.cpu=250m quarkus.kubernetes.resources.limits.memory=512Mi quarkus.kubernetes.resources.limits.cpu=1000m ---- This would generate the following entry in the `container` section: [source, yaml] ---- containers: resources: limits: cpu: 1000m memory: 512Mi requests: cpu: 250m memory: 64Mi ---- === Using the Kubernetes client Applications that are deployed to Kubernetes and need to access the API server will usually make use of the `kubernetes-client` extension: [source,xml] ---- io.quarkus quarkus-kubernetes-client ---- To access the API server from within a Kubernetes cluster, some RBAC related resources are required (e.g. a ServiceAccount, a RoleBinding etc.). So, when the `kubernetes-client` extension is present, the `kubernetes` extension is going to create those resources automatically, so that application will be granted the `view` role. If more roles are required, they will have to be added manually. === Deploying to Minikube https://github.com/kubernetes/minikube[Minikube] is quite popular when a Kubernetes cluster is needed for development purposes. To make the deployment to Minikube experience as frictionless as possible, Quarkus provides the `quarkus-minikube` extension. This extension can be added to a project like so: [source,xml] ---- io.quarkus quarkus-minikube ---- The purpose of this extension is to generate Kubernetes manifests (`minikube.yaml` and `minikube.json`) that are tailored to Minikube. This extension assumes a couple things: * Users won't be using an image registry and will instead make their container image accessible to the Kubernetes cluster by building it directly into Minikube's Docker daemon. To use Minikube's Docker daemon you must first execute: + [source,bash] ---- eval $(minikube -p minikube docker-env) ---- * Applications deployed to Kubernetes won't be accessed via a Kubernetes `Ingress`, but rather as a `NodePort` `Service`. The advantage of doing this is that the URL of an application can be retrieved trivially by executing: + [source,bash] ---- minikube service list ---- To control the https://kubernetes.io/docs/concepts/services-networking/service/#nodeport[nodePort] that is used in this case, users can set `quarkus.kubernetes.node-port`. Note however that this configuration is entirely optional because Quarkus will automatically use a proper (and non-changing) value if none is set. WARNING: It is highly discouraged to use the manifests generated by the Minikube extension when deploying to production as these manifests are intended for development purposes only. When deploying to production, consider using the vanilla Kubernetes manifests (or the OpenShift ones when targeting OpenShift). NOTE: If the assumptions the Minikube extension makes don't fit your workflow, nothing prevents you from using the regular Kubernetes extension to generate Kubernetes manifests and apply those to your Minikube cluster. == Tuning the generated resources using application.properties The Kubernetes extension allows tuning the generated manifest, using the `application.properties` file. Here are some examples: === Configuration options The table below describe all the available configuration options. .Kubernetes |==== | Property | Type | Description | Default Value | quarkus.kubernetes.name | String | | ${quarkus.container-image.name} | quarkus.kubernetes.version | String | | ${quarkus.container-image.tag} | quarkus.kubernetes.deployment-kind | String | | Deployment | quarkus.kubernetes.part-of | String | | | quarkus.kubernetes.init-containers | Map | | | quarkus.kubernetes.namespace | String | | | quarkus.kubernetes.labels | Map | | | quarkus.kubernetes.annotations | Map | | | quarkus.kubernetes.app-secret | String | | | quarkus.kubernetes.app-config-map | String | | | quarkus.kubernetes.env-vars | Map | | | quarkus.kubernetes.working-dir | String | | | quarkus.kubernetes.command | String[] | | | quarkus.kubernetes.arguments | String[] | | | quarkus.kubernetes.replicas | int | | 1 | quarkus.kubernetes.service-account | String | | | quarkus.kubernetes.ports | Map | | | quarkus.kubernetes.service-type | ServiceType | | ClusterIP | quarkus.kubernetes.pvc-volumes | Map | | | quarkus.kubernetes.secret-volumes | Map | | | quarkus.kubernetes.config-map-volumes | Map | | | quarkus.kubernetes.git-repo-volumes | Map | | | quarkus.kubernetes.aws-elastic-block-store-volumes | Map | | | quarkus.kubernetes.azure-disk-volumes | Map | | | quarkus.kubernetes.azure-file-volumes | Map | | | quarkus.kubernetes.mounts | Map | | | quarkus.kubernetes.image-pull-policy | ImagePullPolicy | | Always | quarkus.kubernetes.image-pull-secrets | String[] | | | quarkus.kubernetes.liveness-probe | Probe | | ( see Probe ) | quarkus.kubernetes.readiness-probe | Probe | | ( see Probe ) | quarkus.kubernetes.sidecars | Map | | | quarkus.kubernetes.ingress.expose | boolean | | false | quarkus.kubernetes.ingress.host | String | | | quarkus.kubernetes.ingress.annotations | Map | | | quarkus.kubernetes.headless | boolean | | false | quarkus.kubernetes.hostaliases | Map | | | quarkus.kubernetes.resources.requests.cpu | String | | | quarkus.kubernetes.resources.requests.memory | String | | | quarkus.kubernetes.resources.limits.cpu | String | | | quarkus.kubernetes.resources.limits.memory | String | | |==== Properties that use non-standard types, can be referenced by expanding the property. For example to define a `kubernetes-readiness-probe` which is of type `Probe`: [source,properties] ---- quarkus.kubernetes.readiness-probe.initial-delay=20s quarkus.kubernetes.readiness-probe.period=45s ---- In this example `initial-delay` and `period` are fields of the type `Probe`. Below you will find tables describing all available types. ==== Client Connection Configuration You may need to configure the connection to your Kubernetes cluster. By default, it automatically uses the active _context_ used by `kubectl`. For instance, if your cluster API endpoint uses a self-signed SSL Certificate you need to explicitly configure the client to trust it. You can achieve this by defining the following property: [source,properties] ---- quarkus.kubernetes-client.trust-certs=true ---- The full list of the Kuberneters client configuration properties is provided below. include::{generated-dir}/config/quarkus-kubernetes-client.adoc[opts=optional, leveloffset=+1] ==== Basic Types .ServiceType Allowed values: `cluster-ip`, `node-port`, `load-balancer`, `external-name` .Env |==== | Property | Type | Description | Default Value | value | String | | | secret | String | | | configmap | String | | | field | String | | |==== .Probe |==== | Property | Type | Description | Default Value | http-action-path | String | | | exec-action | String | | | tcp-socket-action | String | | | initial-delay | Duration | | 0 | period | Duration | | 30s | timeout | Duration | | 10s |==== .Port |==== | Property | Type | Description | Default Value | container-port | int | | | host-port | int | | 0 | path | String | | / | protocol | Protocol | | TCP |==== .Container |==== | Property | Type | Description | Default Value | image | String | | | env-vars | Env[] | | | working-dir | String | | | command | String[] | | | arguments | String[] | | | ports | Port[] | | | mounts | Mount[] | | | image-pull-policy | ImagePullPolicy | | Always | liveness-probe | Probe | | | readiness-probe | Probe | | |==== .HostAlias |==== | Property | Type | Description | Default Value | hostnames | String[] | list of hostnames | |==== ==== Mounts and Volumes .Mount |==== | Property | Type | Description | Default Value | path | String | | | sub-path | String | | | read-only | boolean | | false |==== .ConfigMapVolume |==== | Property | Type | Description | Default Value | config-map-name | String | | | default-mode | int | | 0600 | optional | boolean | | false |==== .SecretVolume |==== | Property | Type | Description | Default Value | secret-name | String | | | default-mode | int | | 0600 | optional | boolean | | false |==== .AzureDiskVolume |==== | Property | Type | Description | Default Value | disk-name | String | | | disk-uri | String | | | kind | String | | Managed | caching-mode | String | | ReadWrite | fs-type | String | | ext4 | read-only | boolean | | false |==== .AwsElasticBlockStoreVolume |==== | Property | Type | Description | Default Value | volume-id | String | | | partition | int | | | fs-type | String | | ext4 | read-only | boolean | | false |==== .GitRepoVolume |==== | Property | Type | Description | Default Value | repository | String | | | directory | String | | | revision | String | | |==== .PersistentVolumeClaimVolume |==== | Property | Type | Description | Default Value | claim-name | String | | | read-only | boolean | | false |==== .AzureFileVolume |==== | Property | Type | Description | Default Value | share-name | String | | | secret-name | String | | | read-only | boolean | | false |==== [#openshift] === OpenShift One way to deploy an application to OpenShift is to use s2i (source to image) to create an image stream from the source and then deploy the image stream: [source,bash] ---- ./mvnw quarkus:remove-extension -Dextensions=""kubernetes, jib"" ./mvnw quarkus:add-extension -Dextensions=""openshift"" oc new-project quarkus-project ./mvnw clean package -Dquarkus.container-image.build=true oc new-app --name=greeting quarkus-project/kubernetes-quickstart:1.0.0-SNAPSHOT oc expose svc/greeting oc get route curl /greeting ---- See further information in xref:deploying-to-openshift.adoc[Deploying to OpenShift]. A description of OpenShift resources and customisable properties is given below alongside Kubernetes resources to show similarities where applicable. This includes an alternative to `oc new-app ...` above, i.e. `oc apply -f target/kubernetes/openshift.json` . To enable the generation of OpenShift resources, you need to include OpenShift in the target platforms: [source,properties] ---- quarkus.kubernetes.deployment-target=openshift ---- If you need to generate resources for both platforms (vanilla Kubernetes and OpenShift), then you need to include both (comma separated). [source,properties] ---- quarkus.kubernetes.deployment-target=kubernetes,openshift ---- Following the execution of `./mvnw package -Dquarkus.container-image.build=true ` you will notice amongst the other files that are created, two files named `openshift.json` and `openshift.yml` in the `target/kubernetes/` directory. These manifests can be deployed as is to a running cluster, using `kubectl`: [source,bash] ---- kubectl apply -f target/kubernetes/openshift.json ---- OpenShift users might want to use `oc` instead of `kubectl`: [source,bash] ---- oc apply -f target/kubernetes/openshift.json ---- NOTE: Quarkus also provides the xref:deploying-to-openshift.adoc[OpenShift] extension. This extension is basically a wrapper around the Kubernetes extension and relieves OpenShift users of the necessity of setting the `deployment-target` property to `openshift` The OpenShift resources can be customized in a similar approach with Kubernetes. .OpenShift |==== | Property | Type | Description | Default Value | quarkus.openshift.name | String | | ${quarkus.container-image.name} | quarkus.openshift.version | String | | ${quarkus.container-image.tag} | quarkus.openshift.deployment-kind | String | | DeploymentConfig | quarkus.openshift.part-of | String | | | quarkus.openshift.init-containers | Map | | | quarkus.openshift.labels | Map | | | quarkus.openshift.annotations | Map | | | quarkus.openshift.app-secret | String | | | quarkus.openshift.app-config-map | String | | | quarkus.openshift.env-vars | Map | | | quarkus.openshift.working-dir | String | | | quarkus.openshift.command | String[] | | | quarkus.openshift.arguments | String[] | | | quarkus.openshift.replicas | int | | 1 | quarkus.openshift.service-account | String | | | quarkus.openshift.ports | Map | | | quarkus.openshift.service-type | ServiceType | | ClusterIP | quarkus.openshift.pvc-volumes | Map | | | quarkus.openshift.secret-volumes | Map | | | quarkus.openshift.config-map-volumes | Map | | | quarkus.openshift.git-repo-volumes | Map | | | quarkus.openshift.aws-elastic-block-store-volumes | Map | | | quarkus.openshift.azure-disk-volumes | Map | | | quarkus.openshift.azure-file-volumes | Map | | | quarkus.openshift.mounts | Map | | | quarkus.openshift.image-pull-policy | ImagePullPolicy | | Always | quarkus.openshift.image-pull-secrets | String[] | | | quarkus.openshift.liveness-probe | Probe | | ( see Probe ) | quarkus.openshift.readiness-probe | Probe | | ( see Probe ) | quarkus.openshift.sidecars | Map | | | quarkus.openshift.route.expose | boolean | | false | quarkus.openshift.route.host | String | | | quarkus.openshift.route.annotations | Map | | | quarkus.openshift.headless | boolean | | false |==== [#knative] === Knative To enable the generation of Knative resources, you need to include Knative in the target platforms: [source,properties] ---- quarkus.kubernetes.deployment-target=knative ---- Following the execution of `./mvnw package` you will notice amongst the other files that are created, two files named `knative.json` and `knative.yml` in the `target/kubernetes/` directory. If you look at either file you will see that it contains a Knative `Service`. The full source of the `knative.json` file looks something like this: [source,json] ---- { { ""apiVersion"" : ""serving.quarkus.knative.dev/v1alpha1"", ""kind"" : ""Service"", ""metadata"" : { ""annotations"": { ""app.quarkus.io/vcs-url"" : """", ""app.quarkus.io/commit-id"" : """" }, ""labels"" : { ""app.kubernetes.io/name"" : ""test-quarkus-app"", ""app.kubernetes.io/version"" : ""1.0.0-SNAPSHOT"" }, ""name"" : ""knative. }, ""spec"" : { ""runLatest"" : { ""configuration"" : { ""revisionTemplate"" : { ""spec"" : { ""container"" : { ""image"" : ""dev.local/yourDockerUsername/test-quarkus-app:1.0.0-SNAPSHOT"", ""imagePullPolicy"" : ""Always"" } } } } } } } } ---- The generated manifest can be deployed as is to a running cluster, using `kubectl`: [source,bash] ---- kubectl apply -f target/kubernetes/knative.json ---- The generated service can be customized using the following properties: .Knative |==== | Property | Type | Description | Default Value | quarkus.knative.name | String | | ${quarkus.container-image.name} | quarkus.knative.version | String | | ${quarkus.container-image.tag} | quarkus.knative.part-of | String | | | quarkus.knative.init-containers | Map | | | quarkus.knative.labels | Map | | | quarkus.knative.annotations | Map | | | quarkus.knative.app-secret | String | | | quarkus.knative.app-config-map | String | | | quarkus.knative.env-vars | Map | | | quarkus.knative.working-dir | String | | | quarkus.knative.command | String[] | | | quarkus.knative.arguments | String[] | | | quarkus.knative.replicas | int | | 1 | quarkus.knative.service-account | String | | | quarkus.knative.host | String | | | quarkus.knative.ports | Map | | | quarkus.knative.service-type | ServiceType | | ClusterIP | quarkus.knative.pvc-volumes | Map | | | quarkus.knative.secret-volumes | Map | | | quarkus.knative.config-map-volumes | Map | | | quarkus.knative.git-repo-volumes | Map | | | quarkus.knative.aws-elastic-block-store-volumes | Map | | | quarkus.knative.azure-disk-volumes | Map | | | quarkus.knative.azure-file-volumes | Map | | | quarkus.knative.mounts | Map | | | quarkus.knative.image-pull-policy | ImagePullPolicy | | Always | quarkus.knative.image-pull-secrets | String[] | | | quarkus.knative.liveness-probe | Probe | | ( see Probe ) | quarkus.knative.readiness-probe | Probe | | ( see Probe ) | quarkus.knative.sidecars | Map | | | quarkus.knative.revision-name | String | | | quarkus.knative.traffic | Traffic[] | | ( see Traffic) |==== .Traffic |==== | Property | Type | Description | Default Value | revision-name | String | A specific revision to which to send this portion of traffic | | tag | String | Expose a dedicated url for referncing this target | | latest-revision | Boolean | Optionally provided to indicate that the latest revision should be used for this traffic target | false | percent | Logn | Indicates the percent of traffic that is be routed to this revision | 100 |==== === Deployment targets Mentioned in the previous sections was the concept of `deployment-target`. This concept allows users to control which Kubernetes manifests will be generated and deployed to a cluster (if `quarkus.kubernetes.deploy` has been set to `true`). By default, when no `deployment-target` is set, then only vanilla Kubernetes resources are generated and deployed. When multiple values are set (for example `quarkus.kubernetes.deployment-target=kubernetes,openshift`) then the resources for all targets are generated, but only the resources that correspond to the *first* target are applied to the cluster (if deployment is enabled). In the case of wrapper extensions like OpenShift and Minikube, when these extensions have been explicitly added to the project, the default `deployment-target` is set by those extensions. For example if `quarkus-minikube` has been added to a project, then `minikube` becomes the default deployment target and its resources will be applied to the Kubernetes cluster when deployment via `quarkus.kubernetes.deploy` has been set. Users can still override the deployment-targets manually using `quarkus.kubernetes.deployment-target`. === Deprecated configuration The following categories of configuration properties have been deprecated. ==== Properties without the quarkus prefix In earlier versions of the extension, the `quarkus.` was missing from those properties. These properties are now deprecated. ==== Docker and S2i properties The properties for configuring `docker` and `s2i` are also deprecated in favor of the new container-image extensions. ==== Config group arrays Properties referring to config group arrays (e.g. `kubernetes.labels[0]`, `kubernetes.env-vars[0]` etc) have been converted to maps, to align with the rest of the Quarkus ecosystem. The code below demonstrates the change in `labels` config: [source,properties] ---- # Old labels config: kubernetes.labels[0].name=foo kubernetes.labels[0].value=bar # New labels quarkus.kubernetes.labels.foo=bar ---- The code below demonstrates the change in `env-vars` config: [source,properties] ---- # Old env-vars config: kubernetes.env-vars[0].name=foo kubernetes.env-vars[0].configmap=my-configmap # New env-vars quarkus.kubernetes.env-vars.foo.configmap=myconfigmap ---- ==== `env-vars` properties `quarkus.kubernetes.env-vars` are deprecated (though still currently supported as of this writing) and the new declaration style should be used instead. See <<#env-vars>> and more specifically <> for more details. == Deployment To trigger building and deploying a container image you need to enable the `quarkus.kubernetes.deploy` flag (the flag is disabled by default - furthermore it has no effect during test runs or dev mode). This can be easily done with the command line: [source,bash,subs=attributes+] ---- ./mvnw clean package -Dquarkus.kubernetes.deploy=true ---- === Building a container image Building a container image is possible, using any of the 3 available `container-image` extensions: - xref:container-image.adoc#docker[Docker] - xref:container-image.adoc#jib[Jib] - xref:container-image.adoc#s2i[s2i] Each time deployment is requested, a container image build will be implicitly triggered (no additional properties are required when the Kubernetes deployment has been enabled). === Deploying When deployment is enabled, the Kubernetes extension will select the resources specified by `quarkus.kubernetes.deployment-target` and deploy them. This assumes that a `.kube/config` is available in your user directory that points to the target Kubernetes cluster. In other words the extension will use whatever cluster `kubectl` uses. The same applies to credentials. At the moment no additional options are provided for further customization. == Using existing resources Sometimes it's desirable to either provide additional resources (e.g. a ConfigMap, a Secret, a Deployment for a database etc) or provide custom ones that will be used as a `base` for the generation process. Those resources can be added under `src/main/kubernetes` directory and can be named after the target environment (e.g. kubernetes.json, openshift.json, knative.json, or the yml equivalents). Each of these files may contain one or more Kubernetes resources. Any resource found will be added in the generated manifests. Global modifications (e.g. labels, annotations etc) will also be applied to those resources. If one of the provided resources has the same name as one of the generated ones, then the generated resource will be created on top of the provided resource, respecting existing content when possible (e.g. existing labels, annotations, environment variables, mounts, replicas etc). The name of the resource is determined by the application name and may be overridden by `quarkus.kubernetes.name`, `quarkus.openshift.name` and `quarkus.knative.name`. For example, in the `kubernetes-quickstart` application, we can add a `kubernetes.yml` file in the `src/main/kubernetes` that looks like: [source,yaml] ---- apiVersion: apps/v1 kind: Deployment metadata: name: kubernetes-quickstart labels: app: quickstart spec: replicas: 3 selector: matchLabels: app: quickstart template: metadata: labels: app: quickstart spec: containers: - name: kubernetes-quickstart image: someimage:latest ports: - containerPort: 80 env: - name: FOO value: BAR ---- The generated `kubernetes.yml` will look like: [source,yaml] ---- apiVersion: ""apps/v1"" kind: ""Deployment"" metadata: annotations: app.quarkus.io/build-timestamp: ""2020-04-10 - 12:54:37 +0000"" labels: app: ""quickstart"" name: ""kubernetes-quickstart"" spec: replicas: 3 <1> selector: matchLabels: app.kubernetes.io/name: ""kubernetes-quickstart"" app.kubernetes.io/version: ""1.0.0-SNAPSHOT"" template: metadata: annotations: app.quarkus.io/build-timestamp: ""2020-04-10 - 12:54:37 +0000"" labels: app: ""quickstart"" <2> spec: containers: - env: - name: ""FOO"" <3> value: ""BAR"" image: ""<>/kubernetes-quickstart:1.0.0-SNAPSHOT"" <4> imagePullPolicy: ""Always"" name: ""kubernetes-quickstart"" ports: - containerPort: 8080 <5> name: ""http"" protocol: ""TCP"" serviceAccount: ""kubernetes-quickstart"" ---- The provided replicas <1>, labels <2> and environment variables <3> were retained. However, the image <4> and container port <5> were modified. Moreover, the default annotations have been added. [NOTE] ==== If the resource name does not match the application name (or the overridden name) instead of reusing the resource a new one will be added. Same goes for the container. If the name of the container does not match the application name (or the overridden name), container specific configuration will be ignored. ==== == Service Binding [[service_binding]] Quarkus supports binding services to applications via the link:https://github.com/k8s-service-bindings/spec[Service Binding Specification for Kubernetes]. Specifically Quarkus implements the link:https://github.com/k8s-service-bindings/spec#workload-projection[Workload Projection] part of the specification, thus allowing applications running in appropriately configured Kubernetes clusters to consume services (such as a Database or a Broker) without the need for user configuration. Currently, the following Quarkus extensions (and extensions that depend on these) support this feature: * quarkus-jdbc-mariadb * quarkus-jdbc-mssql * quarkus-jdbc-mysql * quarkus-jdbc-postgresql * quarkus-kafka-client * quarkus-smallrye-reactive-messaging-kafka * quarkus-mongo-client This list of extensions will grow as more services with supported bindings become available on Kubernetes. To enable Service Binding support, in addition to one of the currently supported extensions, the `quarkus-kubernetes-service-binding` extension needs to be added to the application dependencies. === Example using PostgreSQL If the Kubernetes cluster in which your Quarkus application runs supports provisioning a PostgreSQL database, one could use the following dependencies to take advantage of the Service Binding feature: [source,xml] ---- io.quarkus quarkus-jdbc-postgresql io.quarkus quarkus-kubernetes-service-binding io.quarkus quarkus-hibernate-orm ---- The configuration of the application could be as simple as: [source,properties] ---- quarkus.hibernate-orm.database.generation=validate ---- You'll notice that all the configuration for the datasource is absent, as it will be auto-discovered by Quarkus when the application is deployed to Kubernetes. === How does it work? When the application is deployed to an appropriately configured Kubernetes cluster, Kubernetes will create on the filesystem a set of files containing the runtime configuration (for example a file containing the URL of the database, another for the username). Quarkus knows where in the file system to look for these files (as it consults the `SERVICE_BINDING_ROOT` environment variable which is set by Kubernetes) and if they exist, Quarkus knows how to map the values of these files to the appropriate extension configuration properties. An example of what the file system looks like can be seen link:https://github.com/quarkusio/quarkus/tree/e7efe6b3efba91b9c4ae26f9318f8397e23e7505/integration-tests/kubernetes-service-binding-jdbc/src/test/resources/k8s-sb[here]. In that example, the `k8s-sb` directory is meant to be the root of all service bindings. Only one binding which exists in that case and it is named `fruit-db`. This binding has a `type` file indicating that it is a `postgresql` database while the other files provide the necessary connection information. === Generating ServiceBinding resources The <> covers, how the application will consume the bound service. However, we still haven't touched on how the actual binding happens. The binding is the responsibility of the Service Binding Operator. The user provides a `ServiceBinding` resource which expresses which application will bound to which services and the operator is responsible for mounting the required files to container. A `ServiceBinding` looks like: [source,yaml] ---- apiVersion: binding.operators.coreos.com/v1alpha1 kind: ServiceBinding metadata: name: binding-request namespace: service-binding-demo spec: application: name: java-app group: apps version: v1 resource: deployments services: - group: postgresql.baiju.dev version: v1alpha1 kind: Database name: db-demo id: postgresDB ---- The `quarkus-kubernetes-service-binding` extension provides a more compact way of expressing this information: [source,properties] ---- quarkus.kubernetes-service-binding.services.db-demo.api-version=postgresql.baiju.dev/v1alpha1 quarkus.kubernetes-service-binding.services.db-demo.kind=Database ---- By adding the above configuration properties inside your `application.properties` the `quarkus-kubernetes` in cooperation with the `quarkus-kubernetes-service-binding` extension will generate the `ServiceBinding` for you. And this is something that is meant to work regardles of the kubernets flavour you are using, so it's expected to also work for Openshift and Knative, without any additional action from the user. In the configuration above `db-demo` has a double role. It is used to correlate / group `api-version` and `kind` together, but it's also used as the `name` of the custom resource. The later can be overriden if needed. For example: [source,properties] ---- quarkus.kubernetes-service-binding.services.db-demo.api-version=postgresql.baiju.dev/v1alpha1 quarkus.kubernetes-service-binding.services.db-demo.kind=Database quarkus.kubernetes-service-binding.services.db-demo.name=my-db ---- NOTE: Advanced, features (e.g. `ServiceBiniding` mappings) are not yet supported. Here is the list of: link:https://github.com/redhat-developer/service-binding-operator#known-bindable-operators[Known bindable Operators]. [TIP] ==== For more details on how the discovery of the available properties works, please read the link:https://github.com/k8s-service-bindings/spec#workload-projection[Workload Projection] part of the Service Binding specification. ==== ",12218,False,2234.7101100463346,median "// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // FLUTTER_NOLINT // FLUTTER_NOLINT #define FML_USED_ON_EMBEDDER #define RAPIDJSON_HAS_STDSTRING 1 #include #include #include #include #include #include #include ""flutter/fml/build_config.h"" #include ""flutter/fml/closure.h"" #include ""flutter/fml/make_copyable.h"" #include ""flutter/fml/native_library.h"" #include ""third_party/dart/runtime/bin/elf_loader.h"" #include ""third_party/dart/runtime/include/dart_native_api.h"" #if !defined(FLUTTER_NO_EXPORT) #if OS_WIN #define FLUTTER_EXPORT __declspec(dllexport) #else // OS_WIN #define FLUTTER_EXPORT __attribute__((visibility(""default""))) #endif // OS_WIN #endif // !FLUTTER_NO_EXPORT extern ""C"" { #if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG // Used for debugging dart:* sources. extern const uint8_t kPlatformStrongDill[]; extern const intptr_t kPlatformStrongDillSize; #endif // FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG } #include ""flutter/assets/directory_asset_bundle.h"" #include ""flutter/common/task_runners.h"" #include ""flutter/fml/command_line.h"" #include ""flutter/fml/file.h"" #include ""flutter/fml/make_copyable.h"" #include ""flutter/fml/message_loop.h"" #include ""flutter/fml/paths.h"" #include ""flutter/fml/trace_event.h"" #include ""flutter/shell/common/persistent_cache.h"" #include ""flutter/shell/common/rasterizer.h"" #include ""flutter/shell/common/switches.h"" #include ""flutter/shell/platform/embedder/embedder.h"" #include ""flutter/shell/platform/embedder/embedder_engine.h"" #include ""flutter/shell/platform/embedder/embedder_platform_message_response.h"" #include ""flutter/shell/platform/embedder/embedder_render_target.h"" #include ""flutter/shell/platform/embedder/embedder_safe_access.h"" #include ""flutter/shell/platform/embedder/embedder_task_runner.h"" #include ""flutter/shell/platform/embedder/embedder_thread_host.h"" #include ""flutter/shell/platform/embedder/platform_view_embedder.h"" #include ""rapidjson/rapidjson.h"" #include ""rapidjson/writer.h"" const int32_t kFlutterSemanticsNodeIdBatchEnd = -1; const int32_t kFlutterSemanticsCustomActionIdBatchEnd = -1; static FlutterEngineResult LogEmbedderError(FlutterEngineResult code, const char* reason, const char* code_name, const char* function, const char* file, int line) { #if OS_WIN constexpr char kSeparator = '\\\\'; #else constexpr char kSeparator = '/'; #endif const auto file_base = (::strrchr(file, kSeparator) ? strrchr(file, kSeparator) + 1 : file); char error[256] = {}; snprintf(error, (sizeof(error) / sizeof(char)), ""%s (%d): '%s' returned '%s'. %s"", file_base, line, function, code_name, reason); std::cerr << error << std::endl; return code; } #define LOG_EMBEDDER_ERROR(code, reason) \\ LogEmbedderError(code, reason, #code, __FUNCTION__, __FILE__, __LINE__) static bool IsOpenGLRendererConfigValid(const FlutterRendererConfig* config) { if (config->type != kOpenGL) { return false; } const FlutterOpenGLRendererConfig* open_gl_config = &config->open_gl; if (!SAFE_EXISTS(open_gl_config, make_current) || !SAFE_EXISTS(open_gl_config, clear_current) || !SAFE_EXISTS_ONE_OF(open_gl_config, fbo_callback, fbo_with_frame_info_callback) || !SAFE_EXISTS_ONE_OF(open_gl_config, present, present_with_info)) { return false; } return true; } static bool IsSoftwareRendererConfigValid(const FlutterRendererConfig* config) { if (config->type != kSoftware) { return false; } const FlutterSoftwareRendererConfig* software_config = &config->software; if (SAFE_ACCESS(software_config, surface_present_callback, nullptr) == nullptr) { return false; } return true; } static bool IsRendererValid(const FlutterRendererConfig* config) { if (config == nullptr) { return false; } switch (config->type) { case kOpenGL: return IsOpenGLRendererConfigValid(config); case kSoftware: return IsSoftwareRendererConfigValid(config); default: return false; } return false; } #if OS_LINUX || OS_WIN static void* DefaultGLProcResolver(const char* name) { static fml::RefPtr proc_library = #if OS_LINUX fml::NativeLibrary::CreateForCurrentProcess(); #elif OS_WIN // OS_LINUX fml::NativeLibrary::Create(""opengl32.dll""); #endif // OS_WIN return static_cast( const_cast(proc_library->ResolveSymbol(name))); } #endif // OS_LINUX || OS_WIN static flutter::Shell::CreateCallback InferOpenGLPlatformViewCreationCallback( const FlutterRendererConfig* config, void* user_data, flutter::PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table, std::unique_ptr external_view_embedder) { if (config->type != kOpenGL) { return nullptr; } auto gl_make_current = [ptr = config->open_gl.make_current, user_data]() -> bool { return ptr(user_data); }; auto gl_clear_current = [ptr = config->open_gl.clear_current, user_data]() -> bool { return ptr(user_data); }; auto gl_present = [present = config->open_gl.present, present_with_info = config->open_gl.present_with_info, user_data](uint32_t fbo_id) -> bool { if (present) { return present(user_data); } else { FlutterPresentInfo present_info = {}; present_info.struct_size = sizeof(FlutterPresentInfo); present_info.fbo_id = fbo_id; return present_with_info(user_data, &present_info); } }; auto gl_fbo_callback = [fbo_callback = config->open_gl.fbo_callback, fbo_with_frame_info_callback = config->open_gl.fbo_with_frame_info_callback, user_data](flutter::GLFrameInfo gl_frame_info) -> intptr_t { if (fbo_callback) { return fbo_callback(user_data); } else { FlutterFrameInfo frame_info = {}; frame_info.struct_size = sizeof(FlutterFrameInfo); frame_info.size = {gl_frame_info.width, gl_frame_info.height}; return fbo_with_frame_info_callback(user_data, &frame_info); } }; const FlutterOpenGLRendererConfig* open_gl_config = &config->open_gl; std::function gl_make_resource_current_callback = nullptr; if (SAFE_ACCESS(open_gl_config, make_resource_current, nullptr) != nullptr) { gl_make_resource_current_callback = [ptr = config->open_gl.make_resource_current, user_data]() { return ptr(user_data); }; } std::function gl_surface_transformation_callback = nullptr; if (SAFE_ACCESS(open_gl_config, surface_transformation, nullptr) != nullptr) { gl_surface_transformation_callback = [ptr = config->open_gl.surface_transformation, user_data]() { FlutterTransformation transformation = ptr(user_data); return SkMatrix::MakeAll(transformation.scaleX, // transformation.skewX, // transformation.transX, // transformation.skewY, // transformation.scaleY, // transformation.transY, // transformation.pers0, // transformation.pers1, // transformation.pers2 // ); }; // If there is an external view embedder, ask it to apply the surface // transformation to its surfaces as well. if (external_view_embedder) { external_view_embedder->SetSurfaceTransformationCallback( gl_surface_transformation_callback); } } flutter::GPUSurfaceGLDelegate::GLProcResolver gl_proc_resolver = nullptr; if (SAFE_ACCESS(open_gl_config, gl_proc_resolver, nullptr) != nullptr) { gl_proc_resolver = [ptr = config->open_gl.gl_proc_resolver, user_data](const char* gl_proc_name) { return ptr(user_data, gl_proc_name); }; } else { #if OS_LINUX || OS_WIN gl_proc_resolver = DefaultGLProcResolver; #endif } bool fbo_reset_after_present = SAFE_ACCESS(open_gl_config, fbo_reset_after_present, false); flutter::EmbedderSurfaceGL::GLDispatchTable gl_dispatch_table = { gl_make_current, // gl_make_current_callback gl_clear_current, // gl_clear_current_callback gl_present, // gl_present_callback gl_fbo_callback, // gl_fbo_callback gl_make_resource_current_callback, // gl_make_resource_current_callback gl_surface_transformation_callback, // gl_surface_transformation_callback gl_proc_resolver, // gl_proc_resolver }; return fml::MakeCopyable( [gl_dispatch_table, fbo_reset_after_present, platform_dispatch_table, external_view_embedder = std::move(external_view_embedder)](flutter::Shell& shell) mutable { return std::make_unique( shell, // delegate shell.GetTaskRunners(), // task runners gl_dispatch_table, // embedder GL dispatch table fbo_reset_after_present, // fbo reset after present platform_dispatch_table, // embedder platform dispatch table std::move(external_view_embedder) // external view embedder ); }); } static flutter::Shell::CreateCallback InferSoftwarePlatformViewCreationCallback( const FlutterRendererConfig* config, void* user_data, flutter::PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table, std::unique_ptr external_view_embedder) { if (config->type != kSoftware) { return nullptr; } auto software_present_backing_store = [ptr = config->software.surface_present_callback, user_data]( const void* allocation, size_t row_bytes, size_t height) -> bool { return ptr(user_data, allocation, row_bytes, height); }; flutter::EmbedderSurfaceSoftware::SoftwareDispatchTable software_dispatch_table = { software_present_backing_store, // required }; return fml::MakeCopyable( [software_dispatch_table, platform_dispatch_table, external_view_embedder = std::move(external_view_embedder)](flutter::Shell& shell) mutable { return std::make_unique( shell, // delegate shell.GetTaskRunners(), // task runners software_dispatch_table, // software dispatch table platform_dispatch_table, // platform dispatch table std::move(external_view_embedder) // external view embedder ); }); } static flutter::Shell::CreateCallback InferPlatformViewCreationCallback( const FlutterRendererConfig* config, void* user_data, flutter::PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table, std::unique_ptr external_view_embedder) { if (config == nullptr) { return nullptr; } switch (config->type) { case kOpenGL: return InferOpenGLPlatformViewCreationCallback( config, user_data, platform_dispatch_table, std::move(external_view_embedder)); case kSoftware: return InferSoftwarePlatformViewCreationCallback( config, user_data, platform_dispatch_table, std::move(external_view_embedder)); default: return nullptr; } return nullptr; } static sk_sp MakeSkSurfaceFromBackingStore( GrDirectContext* context, const FlutterBackingStoreConfig& config, const FlutterOpenGLTexture* texture) { GrGLTextureInfo texture_info; texture_info.fTarget = texture->target; texture_info.fID = texture->name; texture_info.fFormat = texture->format; GrBackendTexture backend_texture(config.size.width, // config.size.height, // GrMipMapped::kNo, // texture_info // ); SkSurfaceProps surface_properties( SkSurfaceProps::InitType::kLegacyFontHost_InitType); auto surface = SkSurface::MakeFromBackendTexture( context, // context backend_texture, // back-end texture kBottomLeft_GrSurfaceOrigin, // surface origin 1, // sample count kN32_SkColorType, // color type SkColorSpace::MakeSRGB(), // color space &surface_properties, // surface properties static_cast( texture->destruction_callback), // release proc texture->user_data // release context ); if (!surface) { FML_LOG(ERROR) << ""Could not wrap embedder supplied render texture.""; texture->destruction_callback(texture->user_data); return nullptr; } return surface; } static sk_sp MakeSkSurfaceFromBackingStore( GrDirectContext* context, const FlutterBackingStoreConfig& config, const FlutterOpenGLFramebuffer* framebuffer) { GrGLFramebufferInfo framebuffer_info = {}; framebuffer_info.fFormat = framebuffer->target; framebuffer_info.fFBOID = framebuffer->name; GrBackendRenderTarget backend_render_target( config.size.width, // width config.size.height, // height 1, // sample count 0, // stencil bits framebuffer_info // framebuffer info ); SkSurfaceProps surface_properties( SkSurfaceProps::InitType::kLegacyFontHost_InitType); auto surface = SkSurface::MakeFromBackendRenderTarget( context, // context backend_render_target, // backend render target kBottomLeft_GrSurfaceOrigin, // surface origin kN32_SkColorType, // color type SkColorSpace::MakeSRGB(), // color space &surface_properties, // surface properties static_cast( framebuffer->destruction_callback), // release proc framebuffer->user_data // release context ); if (!surface) { FML_LOG(ERROR) << ""Could not wrap embedder supplied frame-buffer.""; framebuffer->destruction_callback(framebuffer->user_data); return nullptr; } return surface; } static sk_sp MakeSkSurfaceFromBackingStore( GrDirectContext* context, const FlutterBackingStoreConfig& config, const FlutterSoftwareBackingStore* software) { const auto image_info = SkImageInfo::MakeN32Premul(config.size.width, config.size.height); struct Captures { VoidCallback destruction_callback; void* user_data; }; auto captures = std::make_unique(); captures->destruction_callback = software->destruction_callback; captures->user_data = software->user_data; auto release_proc = [](void* pixels, void* context) { auto captures = reinterpret_cast(context); captures->destruction_callback(captures->user_data); }; auto surface = SkSurface::MakeRasterDirectReleaseProc( image_info, // image info const_cast(software->allocation), // pixels software->row_bytes, // row bytes release_proc, // release proc captures.release() // release context ); if (!surface) { FML_LOG(ERROR) << ""Could not wrap embedder supplied software render buffer.""; software->destruction_callback(software->user_data); return nullptr; } return surface; } static std::unique_ptr CreateEmbedderRenderTarget(const FlutterCompositor* compositor, const FlutterBackingStoreConfig& config, GrDirectContext* context) { FlutterBackingStore backing_store = {}; backing_store.struct_size = sizeof(backing_store); // Safe access checks on the compositor struct have been performed in // InferExternalViewEmbedderFromArgs and are not necessary here. auto c_create_callback = compositor->create_backing_store_callback; auto c_collect_callback = compositor->collect_backing_store_callback; { TRACE_EVENT0(""flutter"", ""FlutterCompositorCreateBackingStore""); if (!c_create_callback(&config, &backing_store, compositor->user_data)) { FML_LOG(ERROR) << ""Could not create the embedder backing store.""; return nullptr; } } if (backing_store.struct_size != sizeof(backing_store)) { FML_LOG(ERROR) << ""Embedder modified the backing store struct size.""; return nullptr; } // In case we return early without creating an embedder render target, the // embedder has still given us ownership of its baton which we must return // back to it. If this method is successful, the closure is released when the // render target is eventually released. fml::ScopedCleanupClosure collect_callback( [c_collect_callback, backing_store, user_data = compositor->user_data]() { TRACE_EVENT0(""flutter"", ""FlutterCompositorCollectBackingStore""); c_collect_callback(&backing_store, user_data); }); // No safe access checks on the renderer are necessary since we allocated // the struct. sk_sp render_surface; switch (backing_store.type) { case kFlutterBackingStoreTypeOpenGL: switch (backing_store.open_gl.type) { case kFlutterOpenGLTargetTypeTexture: render_surface = MakeSkSurfaceFromBackingStore( context, config, &backing_store.open_gl.texture); break; case kFlutterOpenGLTargetTypeFramebuffer: render_surface = MakeSkSurfaceFromBackingStore( context, config, &backing_store.open_gl.framebuffer); break; } break; case kFlutterBackingStoreTypeSoftware: render_surface = MakeSkSurfaceFromBackingStore(context, config, &backing_store.software); break; }; if (!render_surface) { FML_LOG(ERROR) << ""Could not create a surface from an embedder provided "" ""render target.""; return nullptr; } return std::make_unique( backing_store, std::move(render_surface), collect_callback.Release()); } static std::pair, bool /* halt engine launch if true */> InferExternalViewEmbedderFromArgs(const FlutterCompositor* compositor) { if (compositor == nullptr) { return {nullptr, false}; } auto c_create_callback = SAFE_ACCESS(compositor, create_backing_store_callback, nullptr); auto c_collect_callback = SAFE_ACCESS(compositor, collect_backing_store_callback, nullptr); auto c_present_callback = SAFE_ACCESS(compositor, present_layers_callback, nullptr); // Make sure the required callbacks are present if (!c_create_callback || !c_collect_callback || !c_present_callback) { FML_LOG(ERROR) << ""Required compositor callbacks absent.""; return {nullptr, true}; } FlutterCompositor captured_compositor = *compositor; flutter::EmbedderExternalViewEmbedder::CreateRenderTargetCallback create_render_target_callback = [captured_compositor](GrDirectContext* context, const auto& config) { return CreateEmbedderRenderTarget(&captured_compositor, config, context); }; flutter::EmbedderExternalViewEmbedder::PresentCallback present_callback = [c_present_callback, user_data = compositor->user_data](const auto& layers) { TRACE_EVENT0(""flutter"", ""FlutterCompositorPresentLayers""); return c_present_callback( const_cast(layers.data()), layers.size(), user_data); }; return {std::make_unique( create_render_target_callback, present_callback), false}; } struct _FlutterPlatformMessageResponseHandle { fml::RefPtr message; }; struct LoadedElfDeleter { void operator()(Dart_LoadedElf* elf) { if (elf) { ::Dart_UnloadELF(elf); } } }; using UniqueLoadedElf = std::unique_ptr; struct _FlutterEngineAOTData { UniqueLoadedElf loaded_elf = nullptr; const uint8_t* vm_snapshot_data = nullptr; const uint8_t* vm_snapshot_instrs = nullptr; const uint8_t* vm_isolate_data = nullptr; const uint8_t* vm_isolate_instrs = nullptr; }; FlutterEngineResult FlutterEngineCreateAOTData( const FlutterEngineAOTDataSource* source, FlutterEngineAOTData* data_out) { if (!flutter::DartVM::IsRunningPrecompiledCode()) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""AOT data can only be created in AOT mode.""); } else if (!source) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Null source specified.""); } else if (!data_out) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Null data_out specified.""); } switch (source->type) { case kFlutterEngineAOTDataSourceTypeElfPath: { if (!source->elf_path || !fml::IsFile(source->elf_path)) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid ELF path specified.""); } auto aot_data = std::make_unique<_FlutterEngineAOTData>(); const char* error = nullptr; Dart_LoadedElf* loaded_elf = Dart_LoadELF( source->elf_path, // file path 0, // file offset &error, // error (out) &aot_data->vm_snapshot_data, // vm snapshot data (out) &aot_data->vm_snapshot_instrs, // vm snapshot instr (out) &aot_data->vm_isolate_data, // vm isolate data (out) &aot_data->vm_isolate_instrs // vm isolate instr (out) ); if (loaded_elf == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, error); } aot_data->loaded_elf.reset(loaded_elf); *data_out = aot_data.release(); return kSuccess; } } return LOG_EMBEDDER_ERROR( kInvalidArguments, ""Invalid FlutterEngineAOTDataSourceType type specified.""); } FlutterEngineResult FlutterEngineCollectAOTData(FlutterEngineAOTData data) { if (data) { data->loaded_elf = nullptr; data->vm_snapshot_data = nullptr; data->vm_snapshot_instrs = nullptr; data->vm_isolate_data = nullptr; data->vm_isolate_instrs = nullptr; } return kSuccess; } void PopulateSnapshotMappingCallbacks(const FlutterProjectArgs* args, flutter::Settings& settings) { // There are no ownership concerns here as all mappings are owned by the // embedder and not the engine. auto make_mapping_callback = [](const uint8_t* mapping, size_t size) { return [mapping, size]() { return std::make_unique(mapping, size); }; }; if (flutter::DartVM::IsRunningPrecompiledCode()) { if (SAFE_ACCESS(args, aot_data, nullptr) != nullptr) { settings.vm_snapshot_data = make_mapping_callback(args->aot_data->vm_snapshot_data, 0); settings.vm_snapshot_instr = make_mapping_callback(args->aot_data->vm_snapshot_instrs, 0); settings.isolate_snapshot_data = make_mapping_callback(args->aot_data->vm_isolate_data, 0); settings.isolate_snapshot_instr = make_mapping_callback(args->aot_data->vm_isolate_instrs, 0); } if (SAFE_ACCESS(args, vm_snapshot_data, nullptr) != nullptr) { settings.vm_snapshot_data = make_mapping_callback( args->vm_snapshot_data, SAFE_ACCESS(args, vm_snapshot_data_size, 0)); } if (SAFE_ACCESS(args, vm_snapshot_instructions, nullptr) != nullptr) { settings.vm_snapshot_instr = make_mapping_callback( args->vm_snapshot_instructions, SAFE_ACCESS(args, vm_snapshot_instructions_size, 0)); } if (SAFE_ACCESS(args, isolate_snapshot_data, nullptr) != nullptr) { settings.isolate_snapshot_data = make_mapping_callback( args->isolate_snapshot_data, SAFE_ACCESS(args, isolate_snapshot_data_size, 0)); } if (SAFE_ACCESS(args, isolate_snapshot_instructions, nullptr) != nullptr) { settings.isolate_snapshot_instr = make_mapping_callback( args->isolate_snapshot_instructions, SAFE_ACCESS(args, isolate_snapshot_instructions_size, 0)); } } #if !OS_FUCHSIA && (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG) settings.dart_library_sources_kernel = make_mapping_callback(kPlatformStrongDill, kPlatformStrongDillSize); #endif // !OS_FUCHSIA && (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG) } FlutterEngineResult FlutterEngineRun(size_t version, const FlutterRendererConfig* config, const FlutterProjectArgs* args, void* user_data, FLUTTER_API_SYMBOL(FlutterEngine) * engine_out) { auto result = FlutterEngineInitialize(version, config, args, user_data, engine_out); if (result != kSuccess) { return result; } return FlutterEngineRunInitialized(*engine_out); } FlutterEngineResult FlutterEngineInitialize(size_t version, const FlutterRendererConfig* config, const FlutterProjectArgs* args, void* user_data, FLUTTER_API_SYMBOL(FlutterEngine) * engine_out) { // Step 0: Figure out arguments for shell creation. if (version != FLUTTER_ENGINE_VERSION) { return LOG_EMBEDDER_ERROR( kInvalidLibraryVersion, ""Flutter embedder version mismatch. There has been a breaking change. "" ""Please consult the changelog and update the embedder.""); } if (engine_out == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""The engine out parameter was missing.""); } if (args == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""The Flutter project arguments were missing.""); } if (SAFE_ACCESS(args, assets_path, nullptr) == nullptr) { return LOG_EMBEDDER_ERROR( kInvalidArguments, ""The assets path in the Flutter project arguments was missing.""); } if (SAFE_ACCESS(args, main_path__unused__, nullptr) != nullptr) { FML_LOG(WARNING) << ""FlutterProjectArgs.main_path is deprecated and should be set null.""; } if (SAFE_ACCESS(args, packages_path__unused__, nullptr) != nullptr) { FML_LOG(WARNING) << ""FlutterProjectArgs.packages_path is deprecated and "" ""should be set null.""; } if (!IsRendererValid(config)) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""The renderer configuration was invalid.""); } std::string icu_data_path; if (SAFE_ACCESS(args, icu_data_path, nullptr) != nullptr) { icu_data_path = SAFE_ACCESS(args, icu_data_path, nullptr); } if (SAFE_ACCESS(args, persistent_cache_path, nullptr) != nullptr) { std::string persistent_cache_path = SAFE_ACCESS(args, persistent_cache_path, nullptr); flutter::PersistentCache::SetCacheDirectoryPath(persistent_cache_path); } if (SAFE_ACCESS(args, is_persistent_cache_read_only, false)) { flutter::PersistentCache::gIsReadOnly = true; } fml::CommandLine command_line; if (SAFE_ACCESS(args, command_line_argc, 0) != 0 && SAFE_ACCESS(args, command_line_argv, nullptr) != nullptr) { command_line = fml::CommandLineFromArgcArgv( SAFE_ACCESS(args, command_line_argc, 0), SAFE_ACCESS(args, command_line_argv, nullptr)); } flutter::Settings settings = flutter::SettingsFromCommandLine(command_line); if (SAFE_ACCESS(args, aot_data, nullptr)) { if (SAFE_ACCESS(args, vm_snapshot_data, nullptr) || SAFE_ACCESS(args, vm_snapshot_instructions, nullptr) || SAFE_ACCESS(args, isolate_snapshot_data, nullptr) || SAFE_ACCESS(args, isolate_snapshot_instructions, nullptr)) { return LOG_EMBEDDER_ERROR( kInvalidArguments, ""Multiple AOT sources specified. Embedders should provide either "" ""*_snapshot_* buffers or aot_data, not both.""); } } PopulateSnapshotMappingCallbacks(args, settings); settings.icu_data_path = icu_data_path; settings.assets_path = args->assets_path; settings.leak_vm = !SAFE_ACCESS(args, shutdown_dart_vm_when_done, false); settings.old_gen_heap_size = SAFE_ACCESS(args, dart_old_gen_heap_size, -1); if (!flutter::DartVM::IsRunningPrecompiledCode()) { // Verify the assets path contains Dart 2 kernel assets. const std::string kApplicationKernelSnapshotFileName = ""kernel_blob.bin""; std::string application_kernel_path = fml::paths::JoinPaths( {settings.assets_path, kApplicationKernelSnapshotFileName}); if (!fml::IsFile(application_kernel_path)) { return LOG_EMBEDDER_ERROR( kInvalidArguments, ""Not running in AOT mode but could not resolve the kernel binary.""); } settings.application_kernel_asset = kApplicationKernelSnapshotFileName; } settings.task_observer_add = [](intptr_t key, fml::closure callback) { fml::MessageLoop::GetCurrent().AddTaskObserver(key, std::move(callback)); }; settings.task_observer_remove = [](intptr_t key) { fml::MessageLoop::GetCurrent().RemoveTaskObserver(key); }; if (SAFE_ACCESS(args, root_isolate_create_callback, nullptr) != nullptr) { VoidCallback callback = SAFE_ACCESS(args, root_isolate_create_callback, nullptr); settings.root_isolate_create_callback = [callback, user_data]() { callback(user_data); }; } flutter::PlatformViewEmbedder::UpdateSemanticsNodesCallback update_semantics_nodes_callback = nullptr; if (SAFE_ACCESS(args, update_semantics_node_callback, nullptr) != nullptr) { update_semantics_nodes_callback = [ptr = args->update_semantics_node_callback, user_data](flutter::SemanticsNodeUpdates update) { for (const auto& value : update) { const auto& node = value.second; SkMatrix transform = node.transform.asM33(); FlutterTransformation flutter_transform{ transform.get(SkMatrix::kMScaleX), transform.get(SkMatrix::kMSkewX), transform.get(SkMatrix::kMTransX), transform.get(SkMatrix::kMSkewY), transform.get(SkMatrix::kMScaleY), transform.get(SkMatrix::kMTransY), transform.get(SkMatrix::kMPersp0), transform.get(SkMatrix::kMPersp1), transform.get(SkMatrix::kMPersp2)}; const FlutterSemanticsNode embedder_node{ sizeof(FlutterSemanticsNode), node.id, static_cast(node.flags), static_cast(node.actions), node.textSelectionBase, node.textSelectionExtent, node.scrollChildren, node.scrollIndex, node.scrollPosition, node.scrollExtentMax, node.scrollExtentMin, node.elevation, node.thickness, node.label.c_str(), node.hint.c_str(), node.value.c_str(), node.increasedValue.c_str(), node.decreasedValue.c_str(), static_cast(node.textDirection), FlutterRect{node.rect.fLeft, node.rect.fTop, node.rect.fRight, node.rect.fBottom}, flutter_transform, node.childrenInTraversalOrder.size(), &node.childrenInTraversalOrder[0], &node.childrenInHitTestOrder[0], node.customAccessibilityActions.size(), &node.customAccessibilityActions[0], node.platformViewId, }; ptr(&embedder_node, user_data); } const FlutterSemanticsNode batch_end_sentinel = { sizeof(FlutterSemanticsNode), kFlutterSemanticsNodeIdBatchEnd, }; ptr(&batch_end_sentinel, user_data); }; } flutter::PlatformViewEmbedder::UpdateSemanticsCustomActionsCallback update_semantics_custom_actions_callback = nullptr; if (SAFE_ACCESS(args, update_semantics_custom_action_callback, nullptr) != nullptr) { update_semantics_custom_actions_callback = [ptr = args->update_semantics_custom_action_callback, user_data](flutter::CustomAccessibilityActionUpdates actions) { for (const auto& value : actions) { const auto& action = value.second; const FlutterSemanticsCustomAction embedder_action = { sizeof(FlutterSemanticsCustomAction), action.id, static_cast(action.overrideId), action.label.c_str(), action.hint.c_str(), }; ptr(&embedder_action, user_data); } const FlutterSemanticsCustomAction batch_end_sentinel = { sizeof(FlutterSemanticsCustomAction), kFlutterSemanticsCustomActionIdBatchEnd, }; ptr(&batch_end_sentinel, user_data); }; } flutter::PlatformViewEmbedder::PlatformMessageResponseCallback platform_message_response_callback = nullptr; if (SAFE_ACCESS(args, platform_message_callback, nullptr) != nullptr) { platform_message_response_callback = [ptr = args->platform_message_callback, user_data](fml::RefPtr message) { auto handle = new FlutterPlatformMessageResponseHandle(); const FlutterPlatformMessage incoming_message = { sizeof(FlutterPlatformMessage), // struct_size message->channel().c_str(), // channel message->data().data(), // message message->data().size(), // message_size handle, // response_handle }; handle->message = std::move(message); return ptr(&incoming_message, user_data); }; } flutter::VsyncWaiterEmbedder::VsyncCallback vsync_callback = nullptr; if (SAFE_ACCESS(args, vsync_callback, nullptr) != nullptr) { vsync_callback = [ptr = args->vsync_callback, user_data](intptr_t baton) { return ptr(user_data, baton); }; } flutter::PlatformViewEmbedder::ComputePlatformResolvedLocaleCallback compute_platform_resolved_locale_callback = nullptr; if (SAFE_ACCESS(args, compute_platform_resolved_locale_callback, nullptr) != nullptr) { compute_platform_resolved_locale_callback = [ptr = args->compute_platform_resolved_locale_callback]( const std::vector& supported_locales_data) { const size_t number_of_strings_per_locale = 3; size_t locale_count = supported_locales_data.size() / number_of_strings_per_locale; std::vector supported_locales; std::vector supported_locales_ptr; for (size_t i = 0; i < locale_count; ++i) { supported_locales.push_back( {.struct_size = sizeof(FlutterLocale), .language_code = supported_locales_data[i * number_of_strings_per_locale + 0] .c_str(), .country_code = supported_locales_data[i * number_of_strings_per_locale + 1] .c_str(), .script_code = supported_locales_data[i * number_of_strings_per_locale + 2] .c_str(), .variant_code = nullptr}); supported_locales_ptr.push_back(&supported_locales[i]); } const FlutterLocale* result = ptr(supported_locales_ptr.data(), locale_count); std::unique_ptr> out = std::make_unique>(); if (result) { std::string language_code(SAFE_ACCESS(result, language_code, """")); if (language_code != """") { out->push_back(language_code); out->emplace_back(SAFE_ACCESS(result, country_code, """")); out->emplace_back(SAFE_ACCESS(result, script_code, """")); } } return out; }; } auto external_view_embedder_result = InferExternalViewEmbedderFromArgs(SAFE_ACCESS(args, compositor, nullptr)); if (external_view_embedder_result.second) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Compositor arguments were invalid.""); } flutter::PlatformViewEmbedder::PlatformDispatchTable platform_dispatch_table = { update_semantics_nodes_callback, // update_semantics_custom_actions_callback, // platform_message_response_callback, // vsync_callback, // compute_platform_resolved_locale_callback, // }; auto on_create_platform_view = InferPlatformViewCreationCallback( config, user_data, platform_dispatch_table, std::move(external_view_embedder_result.first)); if (!on_create_platform_view) { return LOG_EMBEDDER_ERROR( kInternalInconsistency, ""Could not infer platform view creation callback.""); } flutter::Shell::CreateCallback on_create_rasterizer = [](flutter::Shell& shell) { return std::make_unique(shell); }; // TODO(chinmaygarde): This is the wrong spot for this. It belongs in the // platform view jump table. flutter::EmbedderExternalTextureGL::ExternalTextureCallback external_texture_callback; if (config->type == kOpenGL) { const FlutterOpenGLRendererConfig* open_gl_config = &config->open_gl; if (SAFE_ACCESS(open_gl_config, gl_external_texture_frame_callback, nullptr) != nullptr) { external_texture_callback = [ptr = open_gl_config->gl_external_texture_frame_callback, user_data]( int64_t texture_identifier, GrDirectContext* context, const SkISize& size) -> sk_sp { FlutterOpenGLTexture texture = {}; if (!ptr(user_data, texture_identifier, size.width(), size.height(), &texture)) { return nullptr; } GrGLTextureInfo gr_texture_info = {texture.target, texture.name, texture.format}; size_t width = size.width(); size_t height = size.height(); if (texture.width != 0 && texture.height != 0) { width = texture.width; height = texture.height; } GrBackendTexture gr_backend_texture(width, height, GrMipMapped::kNo, gr_texture_info); SkImage::TextureReleaseProc release_proc = texture.destruction_callback; auto image = SkImage::MakeFromTexture( context, // context gr_backend_texture, // texture handle kTopLeft_GrSurfaceOrigin, // origin kRGBA_8888_SkColorType, // color type kPremul_SkAlphaType, // alpha type nullptr, // colorspace release_proc, // texture release proc texture.user_data // texture release context ); if (!image) { // In case Skia rejects the image, call the release proc so that // embedders can perform collection of intermediates. if (release_proc) { release_proc(texture.user_data); } FML_LOG(ERROR) << ""Could not create external texture.""; return nullptr; } return image; }; } } auto thread_host = flutter::EmbedderThreadHost::CreateEmbedderOrEngineManagedThreadHost( SAFE_ACCESS(args, custom_task_runners, nullptr)); if (!thread_host || !thread_host->IsValid()) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Could not setup or infer thread configuration "" ""to run the Flutter engine on.""); } auto task_runners = thread_host->GetTaskRunners(); if (!task_runners.IsValid()) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, ""Task runner configuration was invalid.""); } auto run_configuration = flutter::RunConfiguration::InferFromSettings(settings); if (SAFE_ACCESS(args, custom_dart_entrypoint, nullptr) != nullptr) { auto dart_entrypoint = std::string{args->custom_dart_entrypoint}; if (dart_entrypoint.size() != 0) { run_configuration.SetEntrypoint(std::move(dart_entrypoint)); } } if (!run_configuration.IsValid()) { return LOG_EMBEDDER_ERROR( kInvalidArguments, ""Could not infer the Flutter project to run from given arguments.""); } // Create the engine but don't launch the shell or run the root isolate. auto embedder_engine = std::make_unique( std::move(thread_host), // std::move(task_runners), // std::move(settings), // std::move(run_configuration), // on_create_platform_view, // on_create_rasterizer, // external_texture_callback // ); // Release the ownership of the embedder engine to the caller. *engine_out = reinterpret_cast( embedder_engine.release()); return kSuccess; } FlutterEngineResult FlutterEngineRunInitialized( FLUTTER_API_SYMBOL(FlutterEngine) engine) { if (!engine) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Engine handle was invalid.""); } auto embedder_engine = reinterpret_cast(engine); // The engine must not already be running. Initialize may only be called // once on an engine instance. if (embedder_engine->IsValid()) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Engine handle was invalid.""); } // Step 1: Launch the shell. if (!embedder_engine->LaunchShell()) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Could not launch the engine using supplied "" ""initialization arguments.""); } // Step 2: Tell the platform view to initialize itself. if (!embedder_engine->NotifyCreated()) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, ""Could not create platform view components.""); } // Step 3: Launch the root isolate. if (!embedder_engine->RunRootIsolate()) { return LOG_EMBEDDER_ERROR( kInvalidArguments, ""Could not run the root isolate of the Flutter application using the "" ""project arguments specified.""); } return kSuccess; } FLUTTER_EXPORT FlutterEngineResult FlutterEngineDeinitialize(FLUTTER_API_SYMBOL(FlutterEngine) engine) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Engine handle was invalid.""); } auto embedder_engine = reinterpret_cast(engine); embedder_engine->NotifyDestroyed(); embedder_engine->CollectShell(); return kSuccess; } FlutterEngineResult FlutterEngineShutdown(FLUTTER_API_SYMBOL(FlutterEngine) engine) { auto result = FlutterEngineDeinitialize(engine); if (result != kSuccess) { return result; } auto embedder_engine = reinterpret_cast(engine); delete embedder_engine; return kSuccess; } FlutterEngineResult FlutterEngineSendWindowMetricsEvent( FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterWindowMetricsEvent* flutter_metrics) { if (engine == nullptr || flutter_metrics == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Engine handle was invalid.""); } flutter::ViewportMetrics metrics; metrics.physical_width = SAFE_ACCESS(flutter_metrics, width, 0.0); metrics.physical_height = SAFE_ACCESS(flutter_metrics, height, 0.0); metrics.device_pixel_ratio = SAFE_ACCESS(flutter_metrics, pixel_ratio, 1.0); if (metrics.device_pixel_ratio <= 0.0) { return LOG_EMBEDDER_ERROR( kInvalidArguments, ""Device pixel ratio was invalid. It must be greater than zero.""); } return reinterpret_cast(engine)->SetViewportMetrics( std::move(metrics)) ? kSuccess : LOG_EMBEDDER_ERROR(kInvalidArguments, ""Viewport metrics were invalid.""); } // Returns the flutter::PointerData::Change for the given FlutterPointerPhase. inline flutter::PointerData::Change ToPointerDataChange( FlutterPointerPhase phase) { switch (phase) { case kCancel: return flutter::PointerData::Change::kCancel; case kUp: return flutter::PointerData::Change::kUp; case kDown: return flutter::PointerData::Change::kDown; case kMove: return flutter::PointerData::Change::kMove; case kAdd: return flutter::PointerData::Change::kAdd; case kRemove: return flutter::PointerData::Change::kRemove; case kHover: return flutter::PointerData::Change::kHover; } return flutter::PointerData::Change::kCancel; } // Returns the flutter::PointerData::DeviceKind for the given // FlutterPointerDeviceKind. inline flutter::PointerData::DeviceKind ToPointerDataKind( FlutterPointerDeviceKind device_kind) { switch (device_kind) { case kFlutterPointerDeviceKindMouse: return flutter::PointerData::DeviceKind::kMouse; case kFlutterPointerDeviceKindTouch: return flutter::PointerData::DeviceKind::kTouch; } return flutter::PointerData::DeviceKind::kMouse; } // Returns the flutter::PointerData::SignalKind for the given // FlutterPointerSignaKind. inline flutter::PointerData::SignalKind ToPointerDataSignalKind( FlutterPointerSignalKind kind) { switch (kind) { case kFlutterPointerSignalKindNone: return flutter::PointerData::SignalKind::kNone; case kFlutterPointerSignalKindScroll: return flutter::PointerData::SignalKind::kScroll; } return flutter::PointerData::SignalKind::kNone; } // Returns the buttons to synthesize for a PointerData from a // FlutterPointerEvent with no type or buttons set. inline int64_t PointerDataButtonsForLegacyEvent( flutter::PointerData::Change change) { switch (change) { case flutter::PointerData::Change::kDown: case flutter::PointerData::Change::kMove: // These kinds of change must have a non-zero `buttons`, otherwise // gesture recognizers will ignore these events. return flutter::kPointerButtonMousePrimary; case flutter::PointerData::Change::kCancel: case flutter::PointerData::Change::kAdd: case flutter::PointerData::Change::kRemove: case flutter::PointerData::Change::kHover: case flutter::PointerData::Change::kUp: return 0; } return 0; } FlutterEngineResult FlutterEngineSendPointerEvent( FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterPointerEvent* pointers, size_t events_count) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Engine handle was invalid.""); } if (pointers == nullptr || events_count == 0) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid pointer events.""); } auto packet = std::make_unique(events_count); const FlutterPointerEvent* current = pointers; for (size_t i = 0; i < events_count; ++i) { flutter::PointerData pointer_data; pointer_data.Clear(); // this is currely in use only on android embedding. pointer_data.embedder_id = 0; pointer_data.time_stamp = SAFE_ACCESS(current, timestamp, 0); pointer_data.change = ToPointerDataChange( SAFE_ACCESS(current, phase, FlutterPointerPhase::kCancel)); pointer_data.physical_x = SAFE_ACCESS(current, x, 0.0); pointer_data.physical_y = SAFE_ACCESS(current, y, 0.0); // Delta will be generated in pointer_data_packet_converter.cc. pointer_data.physical_delta_x = 0.0; pointer_data.physical_delta_y = 0.0; pointer_data.device = SAFE_ACCESS(current, device, 0); // Pointer identifier will be generated in // pointer_data_packet_converter.cc. pointer_data.pointer_identifier = 0; pointer_data.signal_kind = ToPointerDataSignalKind( SAFE_ACCESS(current, signal_kind, kFlutterPointerSignalKindNone)); pointer_data.scroll_delta_x = SAFE_ACCESS(current, scroll_delta_x, 0.0); pointer_data.scroll_delta_y = SAFE_ACCESS(current, scroll_delta_y, 0.0); FlutterPointerDeviceKind device_kind = SAFE_ACCESS(current, device_kind, 0); // For backwards compatibility with embedders written before the device // kind and buttons were exposed, if the device kind is not set treat it // as a mouse, with a synthesized primary button state based on the phase. if (device_kind == 0) { pointer_data.kind = flutter::PointerData::DeviceKind::kMouse; pointer_data.buttons = PointerDataButtonsForLegacyEvent(pointer_data.change); } else { pointer_data.kind = ToPointerDataKind(device_kind); if (pointer_data.kind == flutter::PointerData::DeviceKind::kTouch) { // For touch events, set the button internally rather than requiring // it at the API level, since it's a confusing construction to expose. if (pointer_data.change == flutter::PointerData::Change::kDown || pointer_data.change == flutter::PointerData::Change::kMove) { pointer_data.buttons = flutter::kPointerButtonTouchContact; } } else { // Buttons use the same mask values, so pass them through directly. pointer_data.buttons = SAFE_ACCESS(current, buttons, 0); } } packet->SetPointerData(i, pointer_data); current = reinterpret_cast( reinterpret_cast(current) + current->struct_size); } return reinterpret_cast(engine) ->DispatchPointerDataPacket(std::move(packet)) ? kSuccess : LOG_EMBEDDER_ERROR(kInternalInconsistency, ""Could not dispatch pointer events to the "" ""running Flutter application.""); } FlutterEngineResult FlutterEngineSendPlatformMessage( FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterPlatformMessage* flutter_message) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid engine handle.""); } if (flutter_message == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid message argument.""); } if (SAFE_ACCESS(flutter_message, channel, nullptr) == nullptr) { return LOG_EMBEDDER_ERROR( kInvalidArguments, ""Message argument did not specify a valid channel.""); } size_t message_size = SAFE_ACCESS(flutter_message, message_size, 0); const uint8_t* message_data = SAFE_ACCESS(flutter_message, message, nullptr); if (message_size != 0 && message_data == nullptr) { return LOG_EMBEDDER_ERROR( kInvalidArguments, ""Message size was non-zero but the message data was nullptr.""); } const FlutterPlatformMessageResponseHandle* response_handle = SAFE_ACCESS(flutter_message, response_handle, nullptr); fml::RefPtr response; if (response_handle && response_handle->message) { response = response_handle->message->response(); } fml::RefPtr message; if (message_size == 0) { message = fml::MakeRefCounted( flutter_message->channel, response); } else { message = fml::MakeRefCounted( flutter_message->channel, std::vector(message_data, message_data + message_size), response); } return reinterpret_cast(engine) ->SendPlatformMessage(std::move(message)) ? kSuccess : LOG_EMBEDDER_ERROR(kInternalInconsistency, ""Could not send a message to the running "" ""Flutter application.""); } FlutterEngineResult FlutterPlatformMessageCreateResponseHandle( FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterDataCallback data_callback, void* user_data, FlutterPlatformMessageResponseHandle** response_out) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Engine handle was invalid.""); } if (data_callback == nullptr || response_out == nullptr) { return LOG_EMBEDDER_ERROR( kInvalidArguments, ""Data callback or the response handle was invalid.""); } flutter::EmbedderPlatformMessageResponse::Callback response_callback = [user_data, data_callback](const uint8_t* data, size_t size) { data_callback(data, size, user_data); }; auto platform_task_runner = reinterpret_cast(engine) ->GetTaskRunners() .GetPlatformTaskRunner(); auto handle = new FlutterPlatformMessageResponseHandle(); handle->message = fml::MakeRefCounted( """", // The channel is empty and unused as the response handle is going // to referenced directly in the |FlutterEngineSendPlatformMessage| // with the container message discarded. fml::MakeRefCounted( std::move(platform_task_runner), response_callback)); *response_out = handle; return kSuccess; } FlutterEngineResult FlutterPlatformMessageReleaseResponseHandle( FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterPlatformMessageResponseHandle* response) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid engine handle.""); } if (response == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid response handle.""); } delete response; return kSuccess; } FlutterEngineResult FlutterEngineSendPlatformMessageResponse( FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterPlatformMessageResponseHandle* handle, const uint8_t* data, size_t data_length) { if (data_length != 0 && data == nullptr) { return LOG_EMBEDDER_ERROR( kInvalidArguments, ""Data size was non zero but the pointer to the data was null.""); } auto response = handle->message->response(); if (response) { if (data_length == 0) { response->CompleteEmpty(); } else { response->Complete(std::make_unique( std::vector({data, data + data_length}))); } } delete handle; return kSuccess; } FlutterEngineResult __FlutterEngineFlushPendingTasksNow() { fml::MessageLoop::GetCurrent().RunExpiredTasksNow(); return kSuccess; } FlutterEngineResult FlutterEngineRegisterExternalTexture( FLUTTER_API_SYMBOL(FlutterEngine) engine, int64_t texture_identifier) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Engine handle was invalid.""); } if (texture_identifier == 0) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Texture identifier was invalid.""); } if (!reinterpret_cast(engine)->RegisterTexture( texture_identifier)) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, ""Could not register the specified texture.""); } return kSuccess; } FlutterEngineResult FlutterEngineUnregisterExternalTexture( FLUTTER_API_SYMBOL(FlutterEngine) engine, int64_t texture_identifier) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Engine handle was invalid.""); } if (texture_identifier == 0) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Texture identifier was invalid.""); } if (!reinterpret_cast(engine)->UnregisterTexture( texture_identifier)) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, ""Could not un-register the specified texture.""); } return kSuccess; } FlutterEngineResult FlutterEngineMarkExternalTextureFrameAvailable( FLUTTER_API_SYMBOL(FlutterEngine) engine, int64_t texture_identifier) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid engine handle.""); } if (texture_identifier == 0) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid texture identifier.""); } if (!reinterpret_cast(engine) ->MarkTextureFrameAvailable(texture_identifier)) { return LOG_EMBEDDER_ERROR( kInternalInconsistency, ""Could not mark the texture frame as being available.""); } return kSuccess; } FlutterEngineResult FlutterEngineUpdateSemanticsEnabled( FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid engine handle.""); } if (!reinterpret_cast(engine)->SetSemanticsEnabled( enabled)) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, ""Could not update semantics state.""); } return kSuccess; } FlutterEngineResult FlutterEngineUpdateAccessibilityFeatures( FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterAccessibilityFeature flags) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid engine handle.""); } if (!reinterpret_cast(engine) ->SetAccessibilityFeatures(flags)) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, ""Could not update accessibility features.""); } return kSuccess; } FlutterEngineResult FlutterEngineDispatchSemanticsAction( FLUTTER_API_SYMBOL(FlutterEngine) engine, uint64_t id, FlutterSemanticsAction action, const uint8_t* data, size_t data_length) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid engine handle.""); } auto engine_action = static_cast(action); if (!reinterpret_cast(engine) ->DispatchSemanticsAction( id, engine_action, std::vector({data, data + data_length}))) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, ""Could not dispatch semantics action.""); } return kSuccess; } FlutterEngineResult FlutterEngineOnVsync(FLUTTER_API_SYMBOL(FlutterEngine) engine, intptr_t baton, uint64_t frame_start_time_nanos, uint64_t frame_target_time_nanos) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid engine handle.""); } TRACE_EVENT0(""flutter"", ""FlutterEngineOnVsync""); auto start_time = fml::TimePoint::FromEpochDelta( fml::TimeDelta::FromNanoseconds(frame_start_time_nanos)); auto target_time = fml::TimePoint::FromEpochDelta( fml::TimeDelta::FromNanoseconds(frame_target_time_nanos)); if (!reinterpret_cast(engine)->OnVsyncEvent( baton, start_time, target_time)) { return LOG_EMBEDDER_ERROR( kInternalInconsistency, ""Could not notify the running engine instance of a Vsync event.""); } return kSuccess; } FlutterEngineResult FlutterEngineReloadSystemFonts( FLUTTER_API_SYMBOL(FlutterEngine) engine) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid engine handle.""); } TRACE_EVENT0(""flutter"", ""FlutterEngineReloadSystemFonts""); if (!reinterpret_cast(engine) ->ReloadSystemFonts()) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, ""Could not reload system fonts.""); } return kSuccess; } void FlutterEngineTraceEventDurationBegin(const char* name) { fml::tracing::TraceEvent0(""flutter"", name); } void FlutterEngineTraceEventDurationEnd(const char* name) { fml::tracing::TraceEventEnd(name); } void FlutterEngineTraceEventInstant(const char* name) { fml::tracing::TraceEventInstant0(""flutter"", name); } FlutterEngineResult FlutterEnginePostRenderThreadTask( FLUTTER_API_SYMBOL(FlutterEngine) engine, VoidCallback callback, void* baton) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid engine handle.""); } if (callback == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Render thread callback was null.""); } auto task = [callback, baton]() { callback(baton); }; return reinterpret_cast(engine) ->PostRenderThreadTask(task) ? kSuccess : LOG_EMBEDDER_ERROR(kInternalInconsistency, ""Could not post the render thread task.""); } uint64_t FlutterEngineGetCurrentTime() { return fml::TimePoint::Now().ToEpochDelta().ToNanoseconds(); } FlutterEngineResult FlutterEngineRunTask(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterTask* task) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid engine handle.""); } return reinterpret_cast(engine)->RunTask(task) ? kSuccess : LOG_EMBEDDER_ERROR(kInvalidArguments, ""Could not run the specified task.""); } static bool DispatchJSONPlatformMessage(FLUTTER_API_SYMBOL(FlutterEngine) engine, rapidjson::Document document, const std::string& channel_name) { if (channel_name.size() == 0) { return false; } rapidjson::StringBuffer buffer; rapidjson::Writer writer(buffer); if (!document.Accept(writer)) { return false; } const char* message = buffer.GetString(); if (message == nullptr || buffer.GetSize() == 0) { return false; } auto platform_message = fml::MakeRefCounted( channel_name.c_str(), // channel std::vector{message, message + buffer.GetSize()}, // message nullptr // response ); return reinterpret_cast(engine) ->SendPlatformMessage(std::move(platform_message)); } FlutterEngineResult FlutterEngineUpdateLocales(FLUTTER_API_SYMBOL(FlutterEngine) engine, const FlutterLocale** locales, size_t locales_count) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid engine handle.""); } if (locales_count == 0) { return kSuccess; } if (locales == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""No locales were specified.""); } rapidjson::Document document; auto& allocator = document.GetAllocator(); document.SetObject(); document.AddMember(""method"", ""setLocale"", allocator); rapidjson::Value args(rapidjson::kArrayType); args.Reserve(locales_count * 4, allocator); for (size_t i = 0; i < locales_count; ++i) { const FlutterLocale* locale = locales[i]; const char* language_code_str = SAFE_ACCESS(locale, language_code, nullptr); if (language_code_str == nullptr || ::strlen(language_code_str) == 0) { return LOG_EMBEDDER_ERROR( kInvalidArguments, ""Language code is required but not present in FlutterLocale.""); } const char* country_code_str = SAFE_ACCESS(locale, country_code, """"); const char* script_code_str = SAFE_ACCESS(locale, script_code, """"); const char* variant_code_str = SAFE_ACCESS(locale, variant_code, """"); rapidjson::Value language_code, country_code, script_code, variant_code; language_code.SetString(language_code_str, allocator); country_code.SetString(country_code_str ? country_code_str : """", allocator); script_code.SetString(script_code_str ? script_code_str : """", allocator); variant_code.SetString(variant_code_str ? variant_code_str : """", allocator); // Required. args.PushBack(language_code, allocator); args.PushBack(country_code, allocator); args.PushBack(script_code, allocator); args.PushBack(variant_code, allocator); } document.AddMember(""args"", args, allocator); return DispatchJSONPlatformMessage(engine, std::move(document), ""flutter/localization"") ? kSuccess : LOG_EMBEDDER_ERROR(kInternalInconsistency, ""Could not send message to update locale of "" ""a running Flutter application.""); } bool FlutterEngineRunsAOTCompiledDartCode(void) { return flutter::DartVM::IsRunningPrecompiledCode(); } FlutterEngineResult FlutterEnginePostDartObject( FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterEngineDartPort port, const FlutterEngineDartObject* object) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid engine handle.""); } if (!reinterpret_cast(engine)->IsValid()) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Engine not running.""); } if (port == ILLEGAL_PORT) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Attempted to post to an illegal port.""); } if (object == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid Dart object to post.""); } Dart_CObject dart_object = {}; fml::ScopedCleanupClosure typed_data_finalizer; switch (object->type) { case kFlutterEngineDartObjectTypeNull: dart_object.type = Dart_CObject_kNull; break; case kFlutterEngineDartObjectTypeBool: dart_object.type = Dart_CObject_kBool; dart_object.value.as_bool = object->bool_value; break; case kFlutterEngineDartObjectTypeInt32: dart_object.type = Dart_CObject_kInt32; dart_object.value.as_int32 = object->int32_value; break; case kFlutterEngineDartObjectTypeInt64: dart_object.type = Dart_CObject_kInt64; dart_object.value.as_int64 = object->int64_value; break; case kFlutterEngineDartObjectTypeDouble: dart_object.type = Dart_CObject_kDouble; dart_object.value.as_double = object->double_value; break; case kFlutterEngineDartObjectTypeString: if (object->string_value == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""kFlutterEngineDartObjectTypeString must be "" ""a null terminated string but was null.""); } dart_object.type = Dart_CObject_kString; dart_object.value.as_string = const_cast(object->string_value); break; case kFlutterEngineDartObjectTypeBuffer: { auto* buffer = SAFE_ACCESS(object->buffer_value, buffer, nullptr); if (buffer == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""kFlutterEngineDartObjectTypeBuffer must "" ""specify a buffer but found nullptr.""); } auto buffer_size = SAFE_ACCESS(object->buffer_value, buffer_size, 0); auto callback = SAFE_ACCESS(object->buffer_value, buffer_collect_callback, nullptr); auto user_data = SAFE_ACCESS(object->buffer_value, user_data, nullptr); // The user has provided a callback, let them manage the lifecycle of // the underlying data. If not, copy it out from the provided buffer. if (callback == nullptr) { dart_object.type = Dart_CObject_kTypedData; dart_object.value.as_typed_data.type = Dart_TypedData_kUint8; dart_object.value.as_typed_data.length = buffer_size; dart_object.value.as_typed_data.values = buffer; } else { struct ExternalTypedDataPeer { void* user_data = nullptr; VoidCallback trampoline = nullptr; }; auto peer = new ExternalTypedDataPeer(); peer->user_data = user_data; peer->trampoline = callback; // This finalizer is set so that in case of failure of the // Dart_PostCObject below, we collect the peer. The embedder is still // responsible for collecting the buffer in case of non-kSuccess // returns from this method. This finalizer must be released in case // of kSuccess returns from this method. typed_data_finalizer.SetClosure([peer]() { // This is the tiny object we use as the peer to the Dart call so // that we can attach the a trampoline to the embedder supplied // callback. In case of error, we need to collect this object lest // we introduce a tiny leak. delete peer; }); dart_object.type = Dart_CObject_kExternalTypedData; dart_object.value.as_external_typed_data.type = Dart_TypedData_kUint8; dart_object.value.as_external_typed_data.length = buffer_size; dart_object.value.as_external_typed_data.data = buffer; dart_object.value.as_external_typed_data.peer = peer; dart_object.value.as_external_typed_data.callback = +[](void* unused_isolate_callback_data, Dart_WeakPersistentHandle unused_handle, void* peer) { auto typed_peer = reinterpret_cast(peer); typed_peer->trampoline(typed_peer->user_data); delete typed_peer; }; } } break; default: return LOG_EMBEDDER_ERROR( kInvalidArguments, ""Invalid FlutterEngineDartObjectType type specified.""); } if (!Dart_PostCObject(port, &dart_object)) { return LOG_EMBEDDER_ERROR(kInternalInconsistency, ""Could not post the object to the Dart VM.""); } // On a successful call, the VM takes ownership of and is responsible for // invoking the finalizer. typed_data_finalizer.Release(); return kSuccess; } FlutterEngineResult FlutterEngineNotifyLowMemoryWarning( FLUTTER_API_SYMBOL(FlutterEngine) raw_engine) { auto engine = reinterpret_cast(raw_engine); if (engine == nullptr || !engine->IsValid()) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Engine was invalid.""); } engine->GetShell().NotifyLowMemoryWarning(); rapidjson::Document document; auto& allocator = document.GetAllocator(); document.SetObject(); document.AddMember(""type"", ""memoryPressure"", allocator); return DispatchJSONPlatformMessage(raw_engine, std::move(document), ""flutter/system"") ? kSuccess : LOG_EMBEDDER_ERROR( kInternalInconsistency, ""Could not dispatch the low memory notification message.""); } FlutterEngineResult FlutterEnginePostCallbackOnAllNativeThreads( FLUTTER_API_SYMBOL(FlutterEngine) engine, FlutterNativeThreadCallback callback, void* user_data) { if (engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid engine handle.""); } if (callback == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid native thread callback.""); } return reinterpret_cast(engine) ->PostTaskOnEngineManagedNativeThreads( [callback, user_data](FlutterNativeThreadType type) { callback(type, user_data); }) ? kSuccess : LOG_EMBEDDER_ERROR(kInvalidArguments, ""Internal error while attempting to post "" ""tasks to all threads.""); } namespace { static bool ValidDisplayConfiguration(const FlutterEngineDisplay* displays, size_t display_count) { std::set display_ids; for (size_t i = 0; i < display_count; i++) { if (displays[i].single_display && display_count != 1) { return false; } display_ids.insert(displays[i].display_id); } return display_ids.size() == display_count; } } // namespace FlutterEngineResult FlutterEngineNotifyDisplayUpdate( FLUTTER_API_SYMBOL(FlutterEngine) raw_engine, const FlutterEngineDisplaysUpdateType update_type, const FlutterEngineDisplay* embedder_displays, size_t display_count) { if (raw_engine == nullptr) { return LOG_EMBEDDER_ERROR(kInvalidArguments, ""Invalid engine handle.""); } if (!ValidDisplayConfiguration(embedder_displays, display_count)) { return LOG_EMBEDDER_ERROR( kInvalidArguments, ""Invalid FlutterEngineDisplay configuration specified.""); } auto engine = reinterpret_cast(raw_engine); switch (update_type) { case kFlutterEngineDisplaysUpdateTypeStartup: { std::vector displays; for (size_t i = 0; i < display_count; i++) { flutter::Display display = flutter::Display(embedder_displays[i].refresh_rate); if (!embedder_displays[i].single_display) { display = flutter::Display(embedder_displays[i].display_id, embedder_displays[i].refresh_rate); } displays.push_back(display); } engine->GetShell().OnDisplayUpdates(flutter::DisplayUpdateType::kStartup, displays); return kSuccess; } default: return LOG_EMBEDDER_ERROR( kInvalidArguments, ""Invalid FlutterEngineDisplaysUpdateType type specified.""); } } ",16322,True,2926.771186036857,median "// Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include #include #include #include #include #include #include #include