text:
#include "Rendering/RendererDX11.h"
#include "Rendering/RasterizerState.h"
#include "Rendering/Viewport.h"
#include "Rendering/DepthStencilBufferDX11.h"
#include "Rendering/RenderTargetDX11.h"
#include "Rendering/Mesh.h"
#include "Rendering/Quad.h"
#include "Rendering/Cube.h"
#include "Rendering/GBuffer.h"
#include "Rendering/GeometryPass.h"
#include "Rendering/LightingPass.h"
#include "Rendering/Texture2dDX11.h"
#include "Rendering/BlendState.h"
#include "Rendering/DepthStencilState.h"
#include "Rendering/DynamicCubemap.h"
#include "Rendering/Equirect2CubemapPass.h"
#include "Rendering/IrradianceConvPass.h"
#include "Rendering/PrefilteringPass.h"
#include "Rendering/IntegrateBRDFPass.h"
#include "Rendering/ConvertGBufferToViewPass.h"
#include "Rendering/SSAOPass.h"
#include "Rendering/SSAOBlurPass.h"
#include "Rendering/AmbientEmissivePass.h"
#include "Rendering/SkyboxPass.h"
#include "Rendering/BoxBloomPass.h"
#include "Rendering/ExtractBrightnessPass.h"
#include "Rendering/GaussianBlurPass.h"
#include "Rendering/BlendingPass.h"
#include "Rendering/ToneMappingPass.h"
#include "Core/Context.h"
#include "Core/Window.h"
#include "Core/Logger.h"
#include "Component/MeshRenderComponent.h"
#include "Component/LightComponent.h"
#include "Component/CameraComponent.h"
#include "GameFramework/World.h"
#include "GameFramework/Entity.h"
#include "GameFramework/Transform.h"
#include "Resource/Material.h"
#include "Resource/Texture2D.h"
#include "Math/Vector2.h"
#include "MT/ThreadPool.h"
#include <random>

namespace Mile
{
   RendererDX11::RendererDX11(Context* context) :
      SubSystem(context),
      m_window(nullptr),
      m_device(nullptr),
      m_immediateContext(nullptr),
      m_deferredContexts{ nullptr },
      m_swapChain(nullptr),
      m_renderTargetView(nullptr),
      m_depthStencilBuffer(nullptr),
      m_bDepthStencilEnabled(true),
      m_clearColor{ 0.0f, 0.0f, 0.0f, 1.0f },
      m_gBuffer(nullptr),
      m_geometryPass(nullptr),
      m_lightingPass(nullptr),
      m_lightingPassRenderBuffer(nullptr),
      m_skyboxPass(nullptr),
      m_envMap(nullptr),
      m_equirectToCubemapPass(nullptr),
      m_equirectangularMap(nullptr),
      m_cubeMesh(nullptr),
      m_irradianceConvPass(nullptr),
      m_irradianceMap(nullptr),
      m_prefilteringPass(nullptr),
      m_prefilterdEnvMap(nullptr),
      m_integrateBRDFPass(nullptr),
      m_brdfLUT(nullptr),
      m_convertGBufferToViewPass(nullptr),
      m_viewSpaceGBuffer(nullptr),
      m_bEnableSSAO(true),
      m_ssaoPass(nullptr),
      m_ssaoBlurPass(nullptr),
      m_ssaoNoise(nullptr),
      m_ssaoRadius(DEFAULT_SSAO_RADIUS),
      m_ssaoBias(DEFAULT_SSAO_BIAS),
      m_ssaoMagnitude(DEFAULT_SSAO_MAGNITUDE),
      m_noiseScale(Vector2(1.0f, 1.0f)),
      m_bCubemapDirtyFlag(false),
      m_bAlwaysComputeIBL(false),
      m_ambientEmissivePass(nullptr),
      m_ambientEmissivePassRenderBuffer(nullptr),
      m_aoFactor(DEFAULT_AO_FACTOR),
      m_hdrBuffer(nullptr),
      m_bloomType(EBloomType::Box),
      m_boxBloomPass(nullptr),
      m_gaussianBloomIntensity(DEFAULT_GAUSSIAN_BLOOM_INTENSITY),
      m_gaussianBloomAmount(DEFAULT_GAUSSIAN_BLOOM_AMOUNT),
      m_gaussianBloomThreshold(DEFAULT_GAUSSIAN_BLOOM_THRESHOLD),
      m_gaussianBloomDepthThreshold(DEFAULT_GAUSSIAN_BLOOM_DEPTH_THRESHOLD),
      m_extractBrightnessPass(nullptr),
      m_gaussianBlurPass(nullptr),
      m_blendingPass(nullptr),
      m_toneMappingPass(nullptr),
      m_exposureFactor(DEFAULT_EXPOSURE_FACTOR),
      m_gammaFactor(DEFAULT_GAMMA_FACTOR),
      m_mainCamera(nullptr),
      m_viewport(nullptr),
      m_depthDisable(nullptr),
      m_defaultRasterizerState(nullptr),
      m_noCulling(nullptr),
      m_additiveBlendState(nullptr),
      m_defaultBlendState(nullptr),
      m_depthLessEqual(nullptr)
   {
   }

   RendererDX11::~RendererDX11()
   {
      DeInit();
   }

   bool RendererDX11::Init()
   {
      if (m_context == nullptr || m_bIsInitialized)
      {
         MELog(m_context, TEXT("RendererDX11"), ELogType::WARNING, TEXT("RendererDX11 already initialized."), true);
         return false;
      }

      if (InitAPI())
      {
         if (!InitPBR())
         {
            MELog(m_context, TEXT("RendererDX11"), ELogType::FATAL, TEXT("Failed to initialize PBR render pass."), true);
            return false;
         }

         if (!InitPostProcess())
         {
            MELog(m_context, TEXT("RendererDX11"), ELogType::FATAL, TEXT("Failed to initialize post-process pass."), true);
            return false;
         }

         if (!InitStates())
         {
            MELog(m_context, TEXT("RendererDX11"), ELogType::FATAL, TEXT("Failed to initialize render states."), true);
            return false;
         }
      }

      MELog(m_context, TEXT("RendererDX11"), ELogType::MESSAGE, TEXT("RendererDX11 Initialized!"), true);
      m_bIsInitialized = true;
      return true;
   }

   bool RendererDX11::InitAPI()
   {
      /* Initialize low level rendering api **/
      m_window = m_context->GetSubSystem<Window>();
      Vector2 screenRes{ m_window->GetResolution() };
      if (m_window == nullptr)
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Cannot found Window subsystem from Context."), true);
         return false;
      }

      if (!CreateDeviceAndSwapChain())
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create Device and SwapChain."), true);
         return false;
      }

      if (!CreateDepthStencilBuffer())
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create Depth-Stencil Buffer."), true);
         return false;
      }

      m_backBuffer = new RenderTargetDX11(this);
      if (!m_backBuffer->Init(m_renderTargetView, m_depthStencilBuffer))
      {
         return false;
      }

      m_screenQuad = new Quad(this);
      if (!m_screenQuad->Init(-1.0f, -1.0f, 1.0f, 1.0f))
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create screen quad."), true);
         return false;
      }

      m_cubeMesh = new Cube(this);
      if (!m_cubeMesh->Init(Vector3(-1.0f, -1.0f, -1.0f), Vector3(1.0f, 1.0f, 1.0f)))
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create Cube mesh."), true);
         return false;
      }

      // @TODO: Multiple viewports
      m_viewport = new Viewport(this);
      m_viewport->SetWidth(screenRes.x);
      m_viewport->SetHeight(screenRes.y);

      return true;
   }

   bool RendererDX11::InitPBR()
   {
      Vector2 screenRes{ m_window->GetResolution() };
      m_gBuffer = new GBuffer(this);
      if (!m_gBuffer->Init(
         static_cast<unsigned int>(screenRes.x),
         static_cast<unsigned int>(screenRes.y)))
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create GBuffer."), true);
         return false;
      }
      m_gBuffer->SetDepthStencilBuffer(m_depthStencilBuffer);

      m_equirectToCubemapPass = new Equirect2CubemapPass(this);
      if (!m_equirectToCubemapPass->Init(DYNAMIC_CUBEMAP_SIZE))
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create Equirectangular to cubemap convert pass."), true);
         return false;
      }

      m_irradianceConvPass = new IrradianceConvPass(this);
      if (!m_irradianceConvPass->Init(IRRADIANCEMAP_SIZE))
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create Irradiance Convolution pass."), true);
         return false;
      }

      m_prefilteringPass = new PrefilteringPass(this);
      if (!m_prefilteringPass->Init(PREFILTERED_CUBEMAP_SIZE))
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create Prefiltering pass."), true);
         return false;
      }

      m_integrateBRDFPass = new IntegrateBRDFPass(this);
      if (!m_integrateBRDFPass->Init())
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create Integrate brdf pass."), true);
         return false;
      }

      m_geometryPass = new GeometryPass(this);
      if (!m_geometryPass->Init())
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create Geometry Pass."), true);
         return false;
      }

      m_lightingPass = new LightingPass(this);
      if (!m_lightingPass->Init())
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create Lighting Pass."), true);
         return false;
      }

      return true;
   }

   bool RendererDX11::InitSSAO()
   {
      Vector2 screenRes{ m_window->GetResolution() };
      SSAOPass::SSAOParams ssaoParams;
      ssaoParams.NoiseScale = Vector2(screenRes.x / SSAO_NOISE_TEXTURE_RES, screenRes.y / SSAO_NOISE_TEXTURE_RES);

      std::uniform_real_distribution<float> randomFloats(0.0f, 1.0f);
      std::default_random_engine generator;
      for (unsigned int idx = 0; idx < SSAO_KERNEL_SIZE; ++idx)
      {
         Vector4 sample{
            randomFloats(generator) * 2.0f - 1.0f,
            randomFloats(generator) * 2.0f - 1.0f,
            randomFloats(generator) /* Hemisphere : z = [0, 1] */,
            0.0f };
         sample.Normalize();
         sample *= randomFloats(generator);

         float scale = (float)idx / (float)SSAO_KERNEL_SIZE;
         scale = Math::Lerp(0.1f, 1.0f, scale * scale);
         sample *= scale;

         ssaoParams.Samples[idx] = sample;
      }

      std::vector<Vector4> ssaoNoise;
      for (unsigned int idx = 0; idx < static_cast<unsigned int>(SSAO_NOISE_TEXTURE_RES * SSAO_NOISE_TEXTURE_RES); ++idx)
      {
         ssaoNoise.push_back(Vector4(
            randomFloats(generator) * 2.0f - 1.0f,
            randomFloats(generator) * 2.0f - 1.0f,
            0.0f,
            0.0f));
      }

      m_ssaoNoise = new Texture2dDX11(this);
      if (!m_ssaoNoise->Init(
         static_cast<unsigned int>(SSAO_NOISE_TEXTURE_RES), static_cast<unsigned int>(SSAO_NOISE_TEXTURE_RES), 4,
         (unsigned char*)ssaoNoise.data(),
         DXGI_FORMAT_R32G32B32A32_FLOAT))
      {
         MELog(m_context, TEXT("RendererDX11"), ELogType::FATAL, TEXT("Failed to initialize SSAO Noise texture."), true);
         return false;
      }

      m_ssaoPass = new SSAOPass(this);
      if (!m_ssaoPass->Init(
         static_cast<unsigned int>(screenRes.x),
         static_cast<unsigned int>(screenRes.y),
         m_depthStencilBuffer))
      {
         MELog(m_context, TEXT("RendererDX11"), ELogType::FATAL, TEXT("Failed to initialize SSAO pass."), true);
         return false;
      }

      m_ssaoPass->UpdateParameters(*GetRenderContextByType(ERenderContextType::Immediate), ssaoParams);

      m_ssaoBlurPass = new SSAOBlurPass(this);
      if (!m_ssaoBlurPass->Init(
         static_cast<unsigned int>(screenRes.x),
         static_cast<unsigned int>(screenRes.y),
         m_depthStencilBuffer))
      {
         MELog(m_context, TEXT("RendererDX11"), ELogType::FATAL, TEXT("Failed to initialize SSAO Blur pass."), true);
         return false;
      }

      return true;
   }

   bool RendererDX11::InitPostProcess()
   {
      Vector2 screenRes{ m_window->GetResolution() };

      m_hdrBuffer = new RenderTargetDX11(this);
      if (!m_hdrBuffer->Init(
         static_cast<unsigned int>(screenRes.x),
         static_cast<unsigned int>(screenRes.y),
         DXGI_FORMAT_R16G16B16A16_FLOAT,
         m_depthStencilBuffer))
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create HDR Buffer."), true);
         return false;
      }

      m_convertGBufferToViewPass = new ConvertGBufferToViewPass(this);
      if (!m_convertGBufferToViewPass->Init(
         static_cast<unsigned int>(screenRes.x),
         static_cast<unsigned int>(screenRes.y),
         m_depthStencilBuffer))
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create Convert GBuffer to view space pass."), true);
         return false;
      }
      m_viewSpaceGBuffer = m_convertGBufferToViewPass->GetConvertedGBuffer();

      m_ambientEmissivePass = new AmbientEmissivePass(this);
      if (!m_ambientEmissivePass->Init())
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create ambient emissive pass."), true);
         return false;
      }

      m_skyboxPass = new SkyboxPass(this);
      if (!m_skyboxPass->Init())
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create Skybox Pass."), true);
         return false;
      }

      m_boxBloomPass = new BoxBloomPass(this);
      if (!m_boxBloomPass->Init(
         static_cast<unsigned int>(screenRes.x),
         static_cast<unsigned int>(screenRes.y),
         m_depthStencilBuffer))
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create Box Bloom pass."), true);
         return false;
      }

      m_extractBrightnessPass = new ExtractBrightnessPass(this);
      if (!m_extractBrightnessPass->Init(
         static_cast<unsigned int>(screenRes.x),
         static_cast<unsigned int>(screenRes.y),
         m_depthStencilBuffer))
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create Extract brightness pass."), true);
         return false;
      }

      m_gaussianBlurPass = new GaussianBlurPass(this);
      if (!m_gaussianBlurPass->Init(
         static_cast<unsigned int>(screenRes.x),
         static_cast<unsigned int>(screenRes.y),
         m_depthStencilBuffer))
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create Gaussian blur pass."), true);
         return false;
      }

      m_blendingPass = new BlendingPass(this);
      if (!m_blendingPass->Init(
         static_cast<unsigned int>(screenRes.x),
         static_cast<unsigned int>(screenRes.y),
         m_depthStencilBuffer))
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create Blending pass."), true);
         return false;
      }

      m_toneMappingPass = new ToneMappingPass(this);
      if (!m_toneMappingPass->Init())
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create Tone mapping pass."), true);
         return false;
      }

      if (!InitSSAO())
      {
         MELog(m_context, TEXT("RendererDX11"), ELogType::FATAL, TEXT("Failed to initialize SSAO pass."), true);
         return false;
      }

      return true;
   }

   bool RendererDX11::InitStates()
   {
      m_defaultRasterizerState = new RasterizerState(this);
      if (!m_defaultRasterizerState->Init())
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create Default RasteirzerState."), true);
         return false;
      }

      m_noCulling = new RasterizerState(this);
      m_noCulling->SetCullMode(CullMode::NONE);
      if (!m_noCulling->Init())
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create no culling rasterizer state."), true);
         return false;
      }

      m_defaultBlendState = new BlendState(this);
      if (!m_defaultBlendState->Init())
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create default blend state."), true);
         return false;
      }

      m_additiveBlendState = new BlendState(this);
      if (!m_additiveBlendState->Init())
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create additive blend state."), true);
         return false;
      }

      m_additiveBlendState->SetRenderTargetBlendState(
         {
            true,
            EBlend::ONE, EBlend::ONE, EBlendOP::ADD,
            EBlend::ONE, EBlend::ZERO, EBlendOP::ADD,
            (UINT8)EColorWriteEnable::ColorWriteEnableAll
         });

      m_depthLessEqual = new DepthStencilState(this);
      D3D11_DEPTH_STENCIL_DESC depthLessEqualDesc = DepthStencilState::GetDefaultDesc();
      depthLessEqualDesc.DepthEnable = true;
      depthLessEqualDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL;
      m_depthLessEqual->SetDesc(depthLessEqualDesc);
      if (!m_depthLessEqual->Init())
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create DEPTH LESS EQUAL state."), true);
         return false;
      }

      m_depthDisable = new DepthStencilState(this);
      D3D11_DEPTH_STENCIL_DESC depthDisableDesc = DepthStencilState::GetDefaultDesc();
      depthDisableDesc.DepthEnable = false;
      m_depthDisable->SetDesc(depthDisableDesc);
      if (!m_depthDisable->Init())
      {
         MELog(m_context,
            TEXT("RendererDX11"),
            ELogType::FATAL,
            TEXT("Failed to create DEPTH DISALBE state."), true);
         return false;
      }

      return true;
   }

   void RendererDX11::DeInit()
   {
      if (m_bIsInitialized)
      {
         SafeDelete(m_viewport);
         SafeDelete(m_depthDisable);
         SafeDelete(m_depthLessEqual);
         SafeDelete(m_additiveBlendState);
         SafeDelete(m_defaultBlendState);
         SafeDelete(m_defaultRasterizerState);
         SafeDelete(m_noCulling);
         SafeDelete(m_screenQuad);
         SafeDelete(m_cubeMesh);
         SafeDelete(m_equirectToCubemapPass);
         SafeDelete(m_irradianceConvPass);
         SafeDelete(m_prefilteringPass);
         SafeDelete(m_integrateBRDFPass);
         SafeDelete(m_geometryPass);
         SafeDelete(m_lightingPass);
         SafeDelete(m_lightingPassRenderBuffer);
         SafeDelete(m_ambientEmissivePass);
         SafeDelete(m_ambientEmissivePassRenderBuffer);
         SafeDelete(m_skyboxPass);
         SafeDelete(m_toneMappingPass);
         SafeDelete(m_boxBloomPass);
         SafeDelete(m_extractBrightnessPass);
         SafeDelete(m_gaussianBlurPass);
         SafeDelete(m_blendingPass);
         SafeDelete(m_gBuffer);
         SafeDelete(m_convertGBufferToViewPass);
         SafeDelete(m_ssaoNoise);
         SafeDelete(m_ssaoPass);
         SafeDelete(m_ssaoBlurPass);
         SafeDelete(m_backBuffer);
         SafeDelete(m_depthStencilBuffer);
         SafeRelease(m_swapChain);

         for (auto deferredContext : m_deferredContexts)
         {
            SafeRelease(deferredContext);
         }

         SafeRelease(m_immediateContext);
         SafeRelease(m_device);

         SubSystem::DeInit();
         MELog(m_context, TEXT("RendererDX11"), ELogType::MESSAGE, TEXT("RendererDX11 deinitialized."), true);
      }
   }

   bool RendererDX11::CreateDeviceAndSwapChain()
   {
      DXGI_SWAP_CHAIN_DESC swDesc;
      ZeroMemory(&swDesc, sizeof(swDesc));

      swDesc.BufferCount = 1;
      swDesc.BufferDesc.Width = m_window->GetResWidth();
      swDesc.BufferDesc.Height = m_window->GetResHeight();
      swDesc.BufferDesc.Format = DXGI_FORMAT::DXGI_FORMAT_B8G8R8A8_UNORM;
      swDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
      swDesc.OutputWindow = reinterpret_cast<HWND>(m_window->GetHandle());
      swDesc.SampleDesc.Count = 1;
      swDesc.SampleDesc.Quality = 0;
      swDesc.Windowed = !m_window->IsFullScreen();

      unsigned int createDeviceFlags = 0;
#ifdef _DEBUG
      createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

      D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL::D3D_FEATURE_LEVEL_11_0 };
      unsigned int numOfFeatureLevels = ARRAYSIZE(featureLevels);
      D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL::D3D_FEATURE_LEVEL_11_0;

      auto hr = D3D11CreateDeviceAndSwapChain(
         nullptr,
         D3D_DRIVER_TYPE_HARDWARE,
         NULL,
         createDeviceFlags,
         featureLevels,
         numOfFeatureLevels,
         D3D11_SDK_VERSION,
         &swDesc,
         &m_swapChain,
         &m_device,
         &featureLevel,
         &m_immediateContext);

      if (FAILED(hr))
      {
         /* Failed to create device and swap chain. **/
         return false;
      }

      /* Create Render target view **/
      ID3D11Texture2D* backBuffer = nullptr;
      hr = m_swapChain->GetBuffer(
         0,
         __uuidof(ID3D11Texture2D),
         (LPVOID*)&backBuffer);

      if (FAILED(hr))
      {
         /* Failed to get back buffer texture resource from swap chain. **/
         return false;
      }

      hr = m_device->CreateRenderTargetView(
         backBuffer,
         nullptr,
         &m_renderTargetView);
      SafeRelease(backBuffer);

      if (FAILED(hr))
      {
         /* Failed to create render target view with backbuffer. **/
         return false;
      }

      // Create Deferred Contexts
      for (auto idx = 0; idx < REQUIRED_RENDERCONTEXT_NUM; ++idx)
      {
         hr = m_device->CreateDeferredContext(0, &m_deferredContexts[idx]);
         if (FAILED(hr))
         {
            // Failed to create deferred contexts.
            return false;
         }
      }

      return true;
   }

   bool RendererDX11::CreateDepthStencilBuffer()
   {
      if (m_device == nullptr)
      {
         return false;
      }

      m_depthStencilBuffer = new DepthStencilBufferDX11(this);
      bool res = m_depthStencilBuffer->Init(m_window->GetResWidth(),
         m_window->GetResHeight(),
         true);

      if (!res)
      {
         return false;
      }

      return true;
   }

   void RendererDX11::AcquireMeshRenderersAndMaterial(World* world)
   {
      if (world != nullptr)
      {
         m_meshRenderComponents.clear();
         m_materialMap.clear();

         m_meshRenderComponents = std::move(world->GetComponentsFromEntities<MeshRenderComponent>(true, true));
         for (auto renderComponent : m_meshRenderComponents)
         {
            Material* material = renderComponent->GetMaterial();
            if (material != nullptr) /** nullptr À϶§ ±âº» material ÇÊ¿äÇÒ±î? */
            {
               m_materialMap[material].push_back(renderComponent);
            }
         }
      }
   }

   void RendererDX11::AcquireLights(World* world)
   {
      if (world != nullptr)
      {
         m_lightComponents.clear();
         m_lightComponents = std::move(world->GetComponentsFromEntities<LightComponent>(true, true));
      }
   }

   void RendererDX11::AcquireCameras(World* world)
   {
      m_cameras.clear();
      if (world != nullptr)
      {
         m_cameras = std::move(world->GetComponentsFromEntities<CameraComponent>(true, true));
      }
   }

   void RendererDX11::Render()
   {
      auto threadPool = m_context->GetSubSystem<ThreadPool>();
      //Clear( *m_immediateContext );

      World* world = m_context->GetSubSystem<World>();
      if (world != nullptr)
      {
         /* Pre-process part**/
         auto acquireMeshRenderersAndMatBinder = std::bind(&RendererDX11::AcquireMeshRenderersAndMaterial,
            this,
            world);
         auto acquireMeshRenderersAndMatTask = threadPool->AddTask(acquireMeshRenderersAndMatBinder);

         auto acquireLightBinder = std::bind(&RendererDX11::AcquireLights, this, world);
         auto acquireLightTask = threadPool->AddTask(acquireLightBinder);

         auto acquireCamerasBinder = std::bind(&RendererDX11::AcquireCameras, this, world);
         auto acquireCamerasTask = threadPool->AddTask(acquireCamerasBinder);

         acquireMeshRenderersAndMatTask.get();
         acquireLightTask.get();
         acquireCamerasTask.get();

         // @TODO: Implement Multiple camera rendering
         if (!m_cameras.empty())
         {
            m_mainCamera = m_cameras[0];
            SetClearColor(m_mainCamera->GetClearColor());

            /* Main Rendering part **/
            /* PBS Workflow **/
            auto geometryPassBinder = std::bind(
               &RendererDX11::RunGeometryPass,
               this,
               GetRenderContextByType(ERenderContextType::GeometryPass));
            auto geometryPassTask = threadPool->AddTask(geometryPassBinder);

            auto lightingPassBinder = std::bind(
               &RendererDX11::RunLightingPass,
               this,
               GetRenderContextByType(ERenderContextType::LightingPass));
            auto lightingPassTask = threadPool->AddTask(lightingPassBinder);

            ID3D11CommandList* geometryPassCmdList = geometryPassTask.get();
            ID3D11CommandList* lightingPassCmdList = lightingPassTask.get();
            ID3D11CommandList* postProcessCmdList = RunPostProcessPass(GetRenderContextByType(ERenderContextType::PostProcessPass));

            SAFE_EXECUTE_CMDLIST(m_immediateContext, geometryPassCmdList, false);
            SAFE_EXECUTE_CMDLIST(m_immediateContext, lightingPassCmdList, false);
            SAFE_EXECUTE_CMDLIST(m_immediateContext, postProcessCmdList, false);

            SafeRelease(geometryPassCmdList);
            SafeRelease(lightingPassCmdList);
            SafeRelease(postProcessCmdList);
         }
      }

      Present();
   }

   ID3D11CommandList* RendererDX11::RunGeometryPass(ID3D11DeviceContext* deviceContextPtr)
   {
      if (deviceContextPtr != nullptr)
      {
         ID3D11DeviceContext& deviceContext = *deviceContextPtr;
         m_geometryPass->SetGBuffer(m_gBuffer);
         if (m_geometryPass->Bind(deviceContext))
         {
            m_defaultRasterizerState->Bind(deviceContext);
            m_viewport->Bind(deviceContext);

            auto camTransform = m_mainCamera->GetTransform();
            Matrix viewMatrix = Matrix::CreateView(
               camTransform->GetPosition(TransformSpace::World),
               camTransform->GetForward(TransformSpace::World),
               camTransform->GetUp(TransformSpace::World));
            Matrix projMatrix = Matrix::CreatePerspectiveProj(
               m_mainCamera->GetFov(),
               m_window->GetAspectRatio(),
               m_mainCamera->GetNearPlane(),
               m_mainCamera->GetFarPlane());

            for (auto batchedMaterial : m_materialMap)
            {
               /* ¹°¸® ±â¹Ý ¸ÓÅ׸®¾ó Á¤º¸ Ãëµæ **/
               Material* material = batchedMaterial.first;
               if (material != nullptr)
               {
                  EMaterialType materialType = material->GetMaterialType();
                  switch (materialType)
                  {
                  case EMaterialType::Opaque:
                  default:
                     Texture2dDX11* baseColorTex = material->GetTexture2D(MaterialTextureProperty::BaseColor)->GetRawTexture();
                     Texture2dDX11* emissiveTex = material->GetTexture2D(MaterialTextureProperty::Emissive)->GetRawTexture();
                     Texture2dDX11* metallicRoughnessTex = material->GetTexture2D(MaterialTextureProperty::MetallicRoughness)->GetRawTexture();
                     Texture2dDX11* specularMapTex = material->GetTexture2D(MaterialTextureProperty::Specular)->GetRawTexture();
                     Texture2dDX11* aoTex = material->GetTexture2D(MaterialTextureProperty::AO)->GetRawTexture();
                     Texture2dDX11* normalTex = material->GetTexture2D(MaterialTextureProperty::Normal)->GetRawTexture();

                     Vector4 baseColorFactor = material->GetVector4Factor(MaterialFactorProperty::BaseColor);
                     Vector4 emissiveFactor = material->GetVector4Factor(MaterialFactorProperty::Emissive);
                     float metallicFactor = material->GetScalarFactor(MaterialFactorProperty::Metallic);
                     float roughnessFactor = material->GetScalarFactor(MaterialFactorProperty::Roughness);
                     float specularFactor = material->GetScalarFactor(MaterialFactorProperty::Specular);
                     Vector2 uvOffset = material->GetVector2Factor(MaterialFactorProperty::UVOffset);

                     m_geometryPass->UpdateMaterialBuffer(
                        deviceContext,
                        { baseColorFactor, emissiveFactor, metallicFactor, roughnessFactor, uvOffset, specularFactor });

                     SAFE_TEX_BIND(baseColorTex, deviceContext, 0, EShaderType::PixelShader);
                     SAFE_TEX_BIND(emissiveTex, deviceContext, 1, EShaderType::PixelShader);
                     SAFE_TEX_BIND(metallicRoughnessTex, deviceContext, 2, EShaderType::PixelShader);
                     SAFE_TEX_BIND(specularMapTex, deviceContext, 3, EShaderType::PixelShader);
                     SAFE_TEX_BIND(aoTex, deviceContext, 4, EShaderType::PixelShader);
                     SAFE_TEX_BIND(normalTex, deviceContext, 5, EShaderType::PixelShader);

                     for (auto meshRenderer : batchedMaterial.second)
                     {
                        Transform* transform = meshRenderer->GetTransform();
                        Mesh* mesh = meshRenderer->GetMesh();

                        Matrix worldMatrix = transform->GetWorldMatrix();

                        Matrix worldViewMatrix = worldMatrix * viewMatrix;
                        m_geometryPass->UpdateTransformBuffer(
                           deviceContext,
                           { worldMatrix, worldViewMatrix, worldViewMatrix * projMatrix });

                        mesh->Bind(deviceContext, 0);
                        deviceContext.DrawIndexed(mesh->GetIndexCount(), 0, 0);
                     }

                     SAFE_TEX_UNBIND(baseColorTex, deviceContext);
                     SAFE_TEX_UNBIND(emissiveTex, deviceContext);
                     SAFE_TEX_UNBIND(metallicRoughnessTex, deviceContext);
                     SAFE_TEX_UNBIND(specularMapTex, deviceContext);
                     SAFE_TEX_UNBIND(aoTex, deviceContext);
                     SAFE_TEX_UNBIND(normalTex, deviceContext);
                     break;
                  }
               }
            }

            m_geometryPass->Unbind(deviceContext);
         }

         ID3D11CommandList* commandList = nullptr;
         auto result = deviceContext.FinishCommandList(false, &commandList);
         if (!FAILED(result))
         {
            return commandList;
         }
      }

      return nullptr;
   }

   ID3D11CommandList* RendererDX11::RunLightingPass(ID3D11DeviceContext* deviceContextPtr)
   {
      if (deviceContextPtr != nullptr)
      {
         ID3D11DeviceContext& deviceContext = *deviceContextPtr;

         CalculateDiffuseIrradiance(deviceContext);
         RenderLight(deviceContext);

         ID3D11CommandList* commandList = nullptr;
         auto result = deviceContext.FinishCommandList(false, &commandList);
         if (!FAILED(result))
         {
            return commandList;
         }
      }

      return nullptr;
   }

   ID3D11CommandList* RendererDX11::RunPostProcessPass(ID3D11DeviceContext* deviceContextPtr)
   {
      if (deviceContextPtr != nullptr)
      {
         ID3D11DeviceContext& deviceContext = *deviceContextPtr;
         m_viewSpaceGBuffer = ConvertGBufferToViewSpace(deviceContext, m_gBuffer);

         RenderTargetDX11* output = RenderAmbientEmissive(deviceContext, m_hdrBuffer);
         output = Bloom(deviceContext, output);
         output = RenderSkybox(deviceContext, output);

         ToneMappingWithGammaCorrection(deviceContext, output);

         ID3D11CommandList* commandList = nullptr;
         auto result = deviceContext.FinishCommandList(false, &commandList);
         if (!FAILED(result))
         {
            return commandList;
         }
      }

      return nullptr;
   }

   void RendererDX11::CalculateDiffuseIrradiance(ID3D11DeviceContext& deviceContext)
   {
      if (m_bCubemapDirtyFlag || m_bAlwaysComputeIBL)
      {

         static const Matrix captureProj = Matrix::CreatePerspectiveProj(90.0f, 1.0f, 0.1f, 10.0f);
         static const std::array<Matrix, CUBE_FACES> captureMatrix =
         {
            // +x
            Matrix::CreateView(Vector3(0.0f, 0.0f, 0.0f), Vector3(1.0f, 0.0f, 0.0f), Vector3(0.0f, 1.0f, 0.0f)) * captureProj,
            // -x
            Matrix::CreateView(Vector3(0.0f, 0.0f, 0.0f), Vector3(-1.0f, 0.0f, 0.0f), Vector3(0.0f, 1.0f, 0.0f)) * captureProj,
            // +y
            Matrix::CreateView(Vector3(0.0f, 0.0f, 0.0f), Vector3(0.0f, 1.0f, 0.0f), Vector3(0.0f, 0.0f, -1.0f)) * captureProj,
            // -y
            Matrix::CreateView(Vector3(0.0f, 0.0f, 0.0f), Vector3(0.0f, -1.0f, 0.0f), Vector3(0.0f, 0.0f, 1.0f)) * captureProj,
            // +z
            Matrix::CreateView(Vector3(0.0f, 0.0f, 0.0f), Vector3(0.0f, 0.0f, 1.0f), Vector3(0.0f, 1.0f, 0.0f)) * captureProj,
            // -z
            Matrix::CreateView(Vector3(0.0f, 0.0f, 0.0f), Vector3(0.0f, 0.0f, -1.0f), Vector3(0.0f, 1.0f, 0.0f)) * captureProj
         };

         ConvertEquirectToCubemap(deviceContext, captureMatrix);
         SolveDiffuseIntegral(deviceContext, captureMatrix);
         ComputePrefilteredEnvMap(deviceContext, captureMatrix);
         IntegrateBRDF(deviceContext);
         m_bCubemapDirtyFlag = false;
      }
   }

   void RendererDX11::ConvertEquirectToCubemap(ID3D11DeviceContext& deviceContext, const std::array<Matrix, CUBE_FACES>& captureMatrix)
   {
      m_envMap = m_equirectToCubemapPass->GetCubemap();
      if (m_equirectToCubemapPass->Bind(deviceContext, m_equirectangularMap->GetRawTexture()))
      {
         m_depthLessEqual->Bind(deviceContext);
         m_noCulling->Bind(deviceContext);
         m_cubeMesh->Bind(deviceContext, 0);
         for (unsigned int faceIndex = 0; faceIndex < CUBE_FACES; ++faceIndex)
         {
            m_envMap->BindAsRenderTarget(deviceContext, faceIndex);
            m_equirectToCubemapPass->UpdateTransformBuffer(
               deviceContext,
               { captureMatrix[faceIndex] });
            deviceContext.DrawIndexed(m_cubeMesh->GetIndexCount(), 0, 0);
            m_envMap->UnbindAsRenderTarget(deviceContext);
         }

         m_envMap->GenerateMips(deviceContext);
         m_equirectToCubemapPass->Unbind(deviceContext);
      }
   }

   void RendererDX11::SolveDiffuseIntegral(ID3D11DeviceContext& deviceContext, const std::array<Matrix, CUBE_FACES>& captureMatrix)
   {
      m_irradianceMap = m_irradianceConvPass->GetIrradianceMap();
      if (m_irradianceConvPass->Bind(deviceContext, m_envMap))
      {
         m_depthLessEqual->Bind(deviceContext);
         m_noCulling->Bind(deviceContext);
         m_cubeMesh->Bind(deviceContext, 0);
         for (unsigned int faceIndex = 0; faceIndex < CUBE_FACES; ++faceIndex)
         {
            m_irradianceMap->BindAsRenderTarget(deviceContext, faceIndex);
            m_irradianceConvPass->UpdateTransformBuffer(
               deviceContext,
               { captureMatrix[faceIndex] });
            deviceContext.DrawIndexed(m_cubeMesh->GetIndexCount(), 0, 0);
            m_irradianceMap->UnbindAsRenderTarget(deviceContext);
         }

         m_irradianceMap->GenerateMips(deviceContext);
         m_irradianceConvPass->Unbind(deviceContext);
      }
   }

   void RendererDX11::ComputePrefilteredEnvMap(ID3D11DeviceContext& deviceContext, const std::array<Matrix, CUBE_FACES>& captureMatrix)
   {
      m_prefilterdEnvMap = m_prefilteringPass->GetPrefilteredEnvironmentMap();
      m_prefilterdEnvMap->GenerateMips(deviceContext);
      if (m_prefilteringPass->Bind(deviceContext, m_envMap))
      {
         /** Generate Empty mips */
         for (unsigned int mipLevel = 0; mipLevel < PREFILTERED_CUBEMAP_MAX_MIPLEVELS; ++mipLevel)
         {
            Viewport* viewport = m_prefilteringPass->GetViewport(mipLevel);
            viewport->Bind(deviceContext);
            m_depthLessEqual->Bind(deviceContext);
            m_noCulling->Bind(deviceContext);
            m_cubeMesh->Bind(deviceContext, 0);

            float roughness = static_cast<float>(mipLevel) / static_cast<float>(PREFILTERED_CUBEMAP_MAX_MIPLEVELS - 1);
            for (unsigned int faceIdx = 0; faceIdx < CUBE_FACES; ++faceIdx)
            {
               m_prefilteringPass->UpdateTransformBuffer(
                  deviceContext,
                  { captureMatrix[faceIdx] });
               m_prefilteringPass->UpdatePrefilteringParams(
                  deviceContext,
                  { roughness });
               m_prefilterdEnvMap->BindAsRenderTarget(deviceContext, faceIdx, mipLevel);

               deviceContext.DrawIndexed(m_cubeMesh->GetIndexCount(), 0, 0);

               m_prefilterdEnvMap->UnbindAsRenderTarget(deviceContext);
            }
         }

         m_prefilteringPass->Unbind(deviceContext);
      }
   }

   void RendererDX11::IntegrateBRDF(ID3D11DeviceContext& deviceContext)
   {
      m_brdfLUT = m_integrateBRDFPass->GetBrdfLUT();
      if (m_integrateBRDFPass->Bind(deviceContext))
      {
         m_screenQuad->Bind(deviceContext, 0);
         m_depthDisable->Bind(deviceContext);

         deviceContext.DrawIndexed(m_screenQuad->GetIndexCount(), 0, 0);

         m_integrateBRDFPass->Unbind(deviceContext);
      }
   }

   void RendererDX11::RenderLight(ID3D11DeviceContext& deviceContext)
   {
      Transform* camTransform = m_mainCamera->GetTransform();
      m_lightingPass->SetGBuffer(m_gBuffer);
      if (m_lightingPass->Bind(deviceContext))
      {
         m_hdrBuffer->BindAsRenderTarget(deviceContext, true, false);
         m_depthDisable->Bind(deviceContext);
         m_viewport->Bind(deviceContext);
         m_defaultRasterizerState->Bind(deviceContext);
         m_additiveBlendState->Bind(deviceContext);
         m_screenQuad->Bind(deviceContext, 0);

         for (auto lightComponent : m_lightComponents)
         {
            m_lightingPass->UpdateCameraParamsBuffer(
               deviceContext,
               { camTransform->GetPosition(TransformSpace::World) });

            Transform* lightTransform = lightComponent->GetTransform();
            Vector3 lightPosition = lightTransform->GetPosition(TransformSpace::World);
            Vector3 lightDirection = lightTransform->GetForward(TransformSpace::World);
            Vector3 lightRadiance = lightComponent->GetRadiance();
            m_lightingPass->UpdateLightParamsBuffer(
               deviceContext,
               {
                  Vector4(lightPosition.x, lightPosition.y, lightPosition.z, 1.0f),
                  Vector4(lightDirection.x, lightDirection.y, lightDirection.z, 0.0f),
                  Vector4(lightRadiance.x, lightRadiance.y, lightRadiance.z, 1.0f),
                  static_cast<UINT32>(lightComponent->GetLightType())
               });

            deviceContext.DrawIndexed(m_screenQuad->GetIndexCount(), 0, 0);
         }

         m_hdrBuffer->UnbindRenderTarget(deviceContext);
         m_lightingPass->Unbind(deviceContext);
      }
   }

   GBuffer* RendererDX11::ConvertGBufferToViewSpace(ID3D11DeviceContext& deviceContext, GBuffer* gBuffer)
   {
      if (gBuffer != nullptr)
      {
         auto camTransform = m_mainCamera->GetTransform();
         Matrix viewMatrix = Matrix::CreateView(
            camTransform->GetPosition(TransformSpace::World),
            camTransform->GetForward(TransformSpace::World),
            camTransform->GetUp(TransformSpace::World));

         if (m_convertGBufferToViewPass->Bind(deviceContext, gBuffer))
         {
            m_depthDisable->Bind(deviceContext);
            m_viewport->Bind(deviceContext);
            m_defaultRasterizerState->Bind(deviceContext);
            m_screenQuad->Bind(deviceContext, 0);

            m_convertGBufferToViewPass->UpdateParameters(deviceContext,
               {
                  viewMatrix
               });
            deviceContext.DrawIndexed(m_screenQuad->GetIndexCount(), 0, 0);

            m_convertGBufferToViewPass->Unbind(deviceContext);
         }

         return m_convertGBufferToViewPass->GetConvertedGBuffer();
      }

      return nullptr;
   }

   RenderTargetDX11* RendererDX11::RenderAmbientEmissive(ID3D11DeviceContext& deviceContext, RenderTargetDX11* renderTarget)
   {
      if (renderTarget != nullptr)
      {
         RenderTargetDX11* aoBuffer = nullptr;
         if (m_bEnableSSAO)
         {
            aoBuffer = SSAO(deviceContext, m_viewSpaceGBuffer, m_ssaoRadius, m_ssaoBias);
            aoBuffer = SSAOBlur(deviceContext, aoBuffer);
         }

         Transform* camTransform = m_mainCamera->GetTransform();
         m_ambientEmissivePass->SetGBuffer(m_gBuffer);
         m_ambientEmissivePass->SetIrradianceMap(m_irradianceConvPass->GetIrradianceMap());
         m_ambientEmissivePass->SetPrefilteredMap(m_prefilterdEnvMap);
         m_ambientEmissivePass->SetBRDFLUT(m_brdfLUT);
         if (m_ambientEmissivePass->Bind(deviceContext))
         {
            renderTarget->BindAsRenderTarget(deviceContext, false, false);
            m_depthDisable->Bind(deviceContext);
            m_viewport->Bind(deviceContext);
            m_defaultRasterizerState->Bind(deviceContext);
            m_additiveBlendState->Bind(deviceContext);
            m_screenQuad->Bind(deviceContext, 0);

            if (aoBuffer != nullptr)
            {
               aoBuffer->BindAsShaderResource(deviceContext, 8, EShaderType::PixelShader);
            }

            m_ambientEmissivePass->UpdateAmbientParamsBuffer(
               deviceContext,
               {
                  camTransform->GetPosition(TransformSpace::World),
                  m_aoFactor, static_cast<unsigned int>(m_bEnableSSAO ? 1 : 0)
               });

            deviceContext.DrawIndexed(m_screenQuad->GetIndexCount(), 0, 0);

            if (aoBuffer != nullptr)
            {
               aoBuffer->UnbindShaderResource(deviceContext);
            }

            renderTarget->UnbindRenderTarget(deviceContext);
            m_ambientEmissivePass->Unbind(deviceContext);
         }

         return renderTarget;
      }

      return nullptr;
   }

   RenderTargetDX11* RendererDX11::RenderSkybox(ID3D11DeviceContext& deviceContext, RenderTargetDX11* renderTarget)
   {
      if (renderTarget != nullptr)
      {
         Transform* camTransform = m_mainCamera->GetTransform();
         if (m_skyboxPass->Bind(deviceContext, m_equirectToCubemapPass->GetCubemap()))
         {
            renderTarget->BindAsRenderTarget(deviceContext, false, false);
            m_depthLessEqual->Bind(deviceContext);
            m_viewport->Bind(deviceContext);
            m_noCulling->Bind(deviceContext);

            Matrix viewMatrix = Matrix::CreateView(
               Vector3(0.0f, 0.0f, 0.0f),
               camTransform->GetForward(TransformSpace::World),
               camTransform->GetUp(TransformSpace::World));
            Matrix projMatrix = Matrix::CreatePerspectiveProj(
               m_mainCamera->GetFov(),
               m_window->GetAspectRatio(),
               0.1f,
               10.0f);

            m_skyboxPass->UpdateTransformBuffer(
               deviceContext,
               {
                  viewMatrix * projMatrix
               });

            m_cubeMesh->Bind(deviceContext, 0);
            deviceContext.DrawIndexed(m_cubeMesh->GetIndexCount(), 0, 0);
            renderTarget->UnbindRenderTarget(deviceContext);
            m_skyboxPass->Unbind(deviceContext);
         }

         return renderTarget;
      }

      return nullptr;
   }

   RenderTargetDX11* RendererDX11::SSAO(ID3D11DeviceContext& deviceContext, GBuffer* gBuffer, float radius, float bias)
   {
      if (m_ssaoPass->Bind(deviceContext, gBuffer, m_ssaoNoise))
      {
         m_depthDisable->Bind(deviceContext);
         m_viewport->Bind(deviceContext);
         m_defaultRasterizerState->Bind(deviceContext);
         m_screenQuad->Bind(deviceContext, 0);

         auto camTransform = m_mainCamera->GetTransform();
         Matrix projMatrix = Matrix::CreatePerspectiveProj(
            m_mainCamera->GetFov(),
            m_window->GetAspectRatio(),
            m_mainCamera->GetNearPlane(),
            m_mainCamera->GetFarPlane());

         m_ssaoPass->UpdateVariableParams(deviceContext,
            {
               projMatrix,
               m_ssaoRadius, m_ssaoBias, m_ssaoMagnitude
            });
         deviceContext.DrawIndexed(m_screenQuad->GetIndexCount(), 0, 0);

         m_ssaoPass->Unbind(deviceContext);
         return m_ssaoPass->GetOutputBuffer();
      }

      return nullptr;
   }

   RenderTargetDX11* RendererDX11::SSAOBlur(ID3D11DeviceContext& deviceContext, RenderTargetDX11* ssaoInput)
   {
      if (m_ssaoBlurPass->Bind(deviceContext, ssaoInput))
      {
         m_depthDisable->Bind(deviceContext);
         m_viewport->Bind(deviceContext);
         m_defaultRasterizerState->Bind(deviceContext);
         m_screenQuad->Bind(deviceContext, 0);

         deviceContext.DrawIndexed(m_screenQuad->GetIndexCount(), 0, 0);

         m_ssaoBlurPass->Unbind(deviceContext);
         return m_ssaoBlurPass->GetOutputBuffer();
      }

      return nullptr;
   }

   RenderTargetDX11* RendererDX11::ExtractBrightness(ID3D11DeviceContext& deviceContext, GBuffer* gBuffer, RenderTargetDX11* renderBuffer, float depthThreshold, float threshold)
   {
      if (m_extractBrightnessPass->Bind(deviceContext, gBuffer, renderBuffer))
      {
         m_depthDisable->Bind(deviceContext);
         m_viewport->Bind(deviceContext);
         m_defaultRasterizerState->Bind(deviceContext);
         m_screenQuad->Bind(deviceContext, 0);

         m_extractBrightnessPass->UpdateParameters(deviceContext, { threshold });
         deviceContext.DrawIndexed(m_screenQuad->GetIndexCount(), 0, 0);

         m_extractBrightnessPass->Unbind(deviceContext);
         return m_extractBrightnessPass->GetOutputBuffer();
      }

      return renderBuffer;
   }

   RenderTargetDX11* RendererDX11::GaussianBlur(ID3D11DeviceContext& deviceContext, RenderTargetDX11* renderBuffer, unsigned int gaussianAmount)
   {
      if (m_gaussianBlurPass->Bind(deviceContext, renderBuffer))
      {
         m_depthDisable->Bind(deviceContext);
         m_viewport->Bind(deviceContext);
         m_defaultRasterizerState->Bind(deviceContext);
         m_screenQuad->Bind(deviceContext, 0);

         bool bHorizontal = true;
         for (unsigned int epoch = 0; epoch < gaussianAmount; ++epoch)
         {
            if (epoch > 0)
            {
               m_gaussianBlurPass->SwapBuffers(deviceContext, bHorizontal);
            }

            m_gaussianBlurPass->UpdateParameters(deviceContext, { static_cast<unsigned int>( bHorizontal ? 1 : 0 ) });
            deviceContext.DrawIndexed(m_screenQuad->GetIndexCount(), 0, 0);

            bHorizontal = !bHorizontal;
         }

         m_gaussianBlurPass->Unbind(deviceContext);
         return m_gaussianBlurPass->GetOutputBuffer();
      }

      return renderBuffer;
   }

   RenderTargetDX11* RendererDX11::Bloom(ID3D11DeviceContext& deviceContext, RenderTargetDX11* renderBuffer)
   {
      RenderTargetDX11* output = renderBuffer;
      switch (m_bloomType)
      {
      case EBloomType::Box:
         output = BoxBloom(deviceContext, renderBuffer);
         break;

      case EBloomType::Gaussian:
         output = GaussianBloom(deviceContext, renderBuffer);
      case EBloomType::None:
         break;
      }

      return output;
   }

   RenderTargetDX11* RendererDX11::BoxBloom(ID3D11DeviceContext& deviceContext, RenderTargetDX11* renderBuffer)
   {
      if (m_boxBloomPass->Bind(deviceContext, renderBuffer))
      {
         m_boxBloomPass->UpdateParameters(deviceContext, {});
         m_depthDisable->Bind(deviceContext);
         m_viewport->Bind(deviceContext);
         m_defaultRasterizerState->Bind(deviceContext);
         m_screenQuad->Bind(deviceContext, 0);

         deviceContext.DrawIndexed(m_screenQuad->GetIndexCount(), 0, 0);

         m_boxBloomPass->Unbind(deviceContext);
         return Blending(deviceContext, m_boxBloomPass->GetOutputBuffer(), renderBuffer);
      }

      return nullptr;
   }

   RenderTargetDX11* RendererDX11::GaussianBloom(ID3D11DeviceContext& deviceContext, RenderTargetDX11* renderBuffer)
   {
      RenderTargetDX11* extractedBrightness = ExtractBrightness(deviceContext, m_gBuffer, renderBuffer, m_gaussianBloomDepthThreshold, m_gaussianBloomThreshold);
      RenderTargetDX11* blurredExtractedBrightness = GaussianBlur(deviceContext, extractedBrightness, m_gaussianBloomAmount);
      return Blending(deviceContext, blurredExtractedBrightness, renderBuffer, m_gaussianBloomIntensity, 1.0f);
   }

   RenderTargetDX11* RendererDX11::Blending(ID3D11DeviceContext& deviceContext, RenderTargetDX11* srcBuffer, RenderTargetDX11* destBuffer, float srcRatio, float destRatio)
   {
      if (srcBuffer != nullptr && destBuffer != nullptr)
      {
         if (m_blendingPass->Bind(deviceContext, srcBuffer, destBuffer))
         {
            m_blendingPass->UpdateParameters(deviceContext,
               {
                  srcRatio,
                  destRatio
               });
            m_depthDisable->Bind(deviceContext);
            m_viewport->Bind(deviceContext);
            m_defaultRasterizerState->Bind(deviceContext);
            m_screenQuad->Bind(deviceContext, 0);

            deviceContext.DrawIndexed(m_screenQuad->GetIndexCount(), 0, 0);
            m_blendingPass->Unbind(deviceContext);

            return m_blendingPass->GetOutputBuffer();
         }
      }

      return destBuffer;
   }

   void RendererDX11::ToneMappingWithGammaCorrection(ID3D11DeviceContext& deviceContext, RenderTargetDX11* renderBuffer)
   {
      if (m_toneMappingPass->Bind(deviceContext, renderBuffer))
      {
         m_toneMappingPass->UpdateParameters(
            deviceContext,
            {
               m_exposureFactor,
               m_gammaFactor
            });

         m_backBuffer->BindAsRenderTarget(deviceContext, true, false);
         m_depthDisable->Bind(deviceContext);
         m_viewport->Bind(deviceContext);
         m_defaultRasterizerState->Bind(deviceContext);
         m_screenQuad->Bind(deviceContext, 0);

         deviceContext.DrawIndexed(m_screenQuad->GetIndexCount(), 0, 0);
         m_backBuffer->UnbindRenderTarget(deviceContext);
         m_toneMappingPass->Unbind(deviceContext);
      }
   }

   void RendererDX11::Clear(ID3D11DeviceContext& deviceContext)
   {
      float clearColor[4] = { m_clearColor.x, m_clearColor.y, m_clearColor.z, m_clearColor.w };
      deviceContext.ClearRenderTargetView(m_renderTargetView,
         clearColor);

      ClearDepthStencil(deviceContext);
   }

   void RendererDX11::ClearDepthStencil(ID3D11DeviceContext& deviceContext)
   {
      if (m_bDepthStencilEnabled)
      {
         deviceContext.ClearDepthStencilView(
            m_depthStencilBuffer->GetDSV(),
            D3D11_CLEAR_DEPTH, 1.0f, 0);
      }
   }

   void RendererDX11::Present()
   {
      if (m_swapChain != nullptr)
      {
         /* @TODO: Impl VSYNC **/
         m_swapChain->Present(0, 0);
      }
   }

   void RendererDX11::SetClearColor(Vector4 clearColor)
   {
      m_clearColor = clearColor;
   }

   void RendererDX11::SetDepthStencilEnable(ID3D11DeviceContext& deviceContext, bool bDepthStencilEnable)
   {
      m_bDepthStencilEnabled = bDepthStencilEnable;
      SetBackbufferAsRenderTarget(deviceContext);
   }

   void RendererDX11::SetEquirectangularMap(Texture2D* texture)
   {
      if (m_equirectangularMap != texture)
      {
         m_equirectangularMap = texture;
         m_bCubemapDirtyFlag = true;
      }
   }

   void RendererDX11::SetComputeIBLAsRealtime(bool bComputeIBLAsRealtime)
   {
      m_bAlwaysComputeIBL =
         (m_equirectangularMap != nullptr) ?
         bComputeIBLAsRealtime : false;
   }

   void RendererDX11::SetBackbufferAsRenderTarget(ID3D11DeviceContext& deviceContext)
   {
      if (m_bDepthStencilEnabled)
      {
         deviceContext.OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilBuffer->GetDSV());
      }
      else
      {
         deviceContext.OMSetRenderTargets(1, &m_renderTargetView, nullptr);
      }
   }

   ID3D11DeviceContext* RendererDX11::GetRenderContextByType(ERenderContextType type)
   {
      if (type != ERenderContextType::Immediate)
      {
         return m_deferredContexts[static_cast<unsigned int>(type)];
      }

      return m_immediateContext;
   }
}


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<link onerror="wx_loaderror(this)" onerror="wx_loaderror(this)" rel="stylesheet" type="text/css" href="https://res.wx.qq.com/mpres/htmledition/style/page/resource/res_iframe2f613f.css"/>

获取聊天记录

获取聊天记录

此接口返回的聊天记录中,对于图片、语音、视频,分别展示成文本格式的[image]、[voice]、[video]。对于较可能包含重要信息的图片消息,后续将提供图片拉取URL,近期将上线。

调用说明

1

2

3

4

5

6

7

8

9

http请求方式: POST

https://api.weixin.qq.com/customservice/msgrecord/getmsglist
?access_token=ACCESS_TOKEN

POST数据示例如下:

{

"starttime" : 987654321,

"endtime" : 987654321,

"msgid" : 1,

"number" : 10000

}

参数说明

参数	说明

starttime	起始时间,unix时间戳

endtime	结束时间,unix时间戳,每次查询时段不能超过24小时

msgid	消息id顺序从小到大,从1开始

number	每次获取条数,最多10000条

返回说明

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

{

"recordlist" : [

{

"openid" :
"oDF3iY9WMaswOPWjCIp_f3Bnpljk"
,

"opercode" : 2002,

"text" :
" 您好,客服test1为您服务。"
,

"time" : 1400563710,

"worker" :
"test1@test"

},

{

"openid" :
"oDF3iY9WMaswOPWjCIp_f3Bnpljk"
,

"opercode" : 2003,

"text" :
"你好,有什么事情?"
,

"time" : 1400563731,

"worker" :
"test1@test"

}

],

     "number":2,

     "msgid":20165267

}

参数说明

参数	说明

worker	完整客服帐号,格式为:帐号前缀@公众号微信号

openid	用户标识

opercode	操作码,2002(客服发送信息),2003(客服接收消息)

text	聊天记录

time	操作时间,unix时间戳

返回码说明

返回码	说明

65400	API不可用,即没有开通或升级到新版客服功能

65416	查询参数不合法

65417	查询时间段超出限制

调用示例

 第一次
请求:

https://api.weixin.qq.com/customservice/msgrecord/getmsglist
?access_token=ACCESS_TOKEN

POST数据示例如下:

{

"starttime" : 1464710400,

"endtime" : 1464796800,

"msgid" : 1,

"number" : 10000

}

 返回:

{

"recordlist" : [

{

"openid" :
"oDF3iY9WMaswOPWjCIp_f3Bnpljk"
,

"opercode" : 2002,

"text" :
" 您好,客服test1为您服务。"
,

"time" : 1464710500,

"worker" :
"test1@test"

},

{

"openid" :
"oDF3iY9WMaswOPWjCIp_f3Bnpljk"
,

"opercode" : 2003,

"text" :
"你好,有什么事情?"
,

"time" : 1464710600,

"worker" :
"test1@test"

},

         ......

],

     "number":10000,

     "msgid":20165258

}

请求的number(10000)和返回的number(10000)一样,该时间段可能还有聊天记录未获取,将msgid(20165258)填进下次请求中;

  第二次
请求:

https://api.weixin.qq.com/customservice/msgrecord/getmsglist
?access_token=ACCESS_TOKEN

POST数据示例如下:

{

"starttime" : 1464710400,

"endtime" : 1464796800,

"msgid" : 20165258,

"number" : 10000

}

返回:

{

"recordlist" : [

{

"openid" :
"oDF3iY9WMaswOPWjCIp_f3Bnpljk"
,

"opercode" : 2002,

"text" :
" 您好,客服test1为您服务。"
,

"time" : 1464710700,

"worker" :
"test1@test"

},

{

"openid" :
"oDF3iY9WMaswOPWjCIp_f3Bnpljk"
,

"opercode" : 2003,

"text" :
"你好,有什么事情?"
,

"time" : 1464710800,

"worker" :
"test1@test"

},

         ......

],

     "number":4,

     "msgid":20165267

}

请求的number(10000)和返回的number(4)不一样,则该时间段的后续聊天记录获取完毕;

redpajama_set_name: RedPajamaGithub


text:
package com.impirobotics.frc2014.subsystems;

import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.command.Subsystem;
import com.impirobotics.frc2014.RobotMap;
import com.impirobotics.frc2014.commands.pneumatics.Pneumatics_Start;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;

public class PneumaticsSubsystem  extends Subsystem {
    private Compressor compressor;

    public PneumaticsSubsystem () {
        compressor = new Compressor(
            RobotMap.DIO__PNEUMATICS__COMPRESSOR,
            RobotMap.RELAY__PNEUMATICS__COMPRESSOR);

        LiveWindow.addActuator("Pneumatics", "Compressor", compressor);
    }

    public void initDefaultCommand() {
        setDefaultCommand(new Pneumatics_Start());
    }

    public void updateStatus() {
    }

    public void start() {
        compressor.start();
    }

    public void stop() {
        compressor.stop();
    }
}


text:
import { CircleIconButtonProps } from '../../CircleIconButton';

export type CallButtonsProps = {
  currentLocale?: string;
} & Pick<CircleIconButtonProps, 'size' | 'placement' | 'className'>;


text:
package com.netflix.priam.backup;

import com.netflix.priam.utils.GsonJsonSerializer;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by aagrawal on 2/16/17. This class holds the result from BackupVerification. The default
 * are all null and false.
 */
public class BackupVerificationResult {
    public boolean valid = false;
    public String remotePath = null;
    public Instant snapshotInstant = null;
    public boolean manifestAvailable = false;
    public List<String> filesInMetaOnly = new ArrayList<>();
    public int filesMatched = 0;

    @Override
    public String toString() {
        return GsonJsonSerializer.getGson().toJson(this);
    }
}


text:
![Seneca](http://senecajs.org/files/assets/seneca-logo.png)
# A [Seneca.js][] service load balancer that allows you to run multiple instances of services listening for the same pattern.

# Seneca-load-balancer

### IN PROGRESS, NOT PROD READY

[![npm version][npm-badge]][npm-url]
[![Build Status][travis-badge]][travis-url]
[![Dependency Status][david-badge]][david-url]
[![Gitter chat][gitter-badge]][gitter-url]

This is a plugin for Seneca that allows you to load balance between multiple
running instances of your services. This allows you to build what appears to be
the evolving standard for microservices (run as many as needed of the same service
at once to meet demand, load balance between them). This only works with http
and tcp transports.

 - lead maintainer: [Glen Keane][lead]

## Example

At the end of this example, you will have seen how to run some services, hook your
load-balancer to them, and then the load balancer will send out jobs to them from
some client. The client sends all acts to the load-balancer, the load-balancer
then sends acts to a running service, and the service gets a reply from the client.

The service/server below (service.js) is run with the command `node math.js SOME_PORT`,
allowing you to create the same service listening on multiple ports.

```javascript
var seneca = require('seneca')()

// A basic pattern to use
seneca.add({ a: 1 }, function (input, done) {
  console.log(input)
  done(null, { b: 1, port: process.argv[2] })
})

// eg. run with node ./test.js 10201
seneca.listen({ port: process.argv[2] })
```

The code below (balancer.js) is how you would setup your customised load-balancer. You just
`.use()` the load-balancer, and supply it with some options/config. I will supply
`SOME_LOAD_BALANCE_CONFIG_OBJECT` later.

```javascript
var Seneca = require('seneca')()
var SOME_LOAD_BALANCE_CONFIG_OBJECT = {...}

seneca.use(require('seneca-load-balancer'), SOME_LOAD_BALANCE_CONFIG_OBJECT)

seneca.listen({port: 10100})
```

The code below (client.js) is an example of a client that wants to use our already defined
service. This client connects to our load-balancer, NOT the services themselves.

```javascript
var seneca = require('seneca')()

seneca.client({ port: 10100, pin: {} })

setInterval(function () {
  seneca.act({ a: 1 }, console.log)
}, 10000)
```

If you ran service.js three times, you need some way of connecting to it.
e.g if you ran the following:
```bash
node ./service.js 10201
node ./service.js 10202
node ./service.js 10203
```

now run the client. this will try every ten seconds to hit our currently running
service, and log the result. when it starts getting replies with the `b` and `port`
property, we know we succeeded
```bash
node ./client.js
```

Now, we need the balancer to connect our client to our services. This is where
the config object mentioned above comes in. This object has a specific stucture,
explained in full later. however, for this example, the following config works:
```javascript
var config = {
  services: [
    {
      //we can use seneca pattern style definitions here, or standard objects!
      pattern: 'a:1',
      locations: [
        { host: 'localhost', port: '10201', spec: 'http' },
        { host: 'localhost', port: '10202', spec: 'http' },
        { host: 'localhost', port: '10203', spec: 'http' }
      ]
    }
  ]
}
```

now, with the config above, run `./balancer.js` with the following:
```bash
node ./balancer.js
```

## Contributing

This module follows the general [Senecajs org][senecaOrg] contribution guidelines, and encourages open participation. If you feel you can help in any way, or discover any Issues, feel free to [create an issue][issue] or [create a pull request][pr]!

If you wish to read more on our guidelines, feel free to

  - Checkout the concise [contribution file][contrib]
  - Checkout our much more indepth [contributing guidelines][contribGuide]

## License
Copyright Glen Keane and other contributors 2016, Licensed under [MIT][].

[Seneca.js]: https://www.npmjs.com/package/seneca
[senecaOrg]: https://github.com/senecajs/
[issue]: https://github.com/thekemkid/seneca-load-balancer/issues
[pr]:https://github.com/thekemkid/seneca-load-balancer/pulls
[MIT]: ./LICENSE
[contrib]: ./CONTRIBUTING.md
[contribGuide]: http://senecajs.org/contribute/
[npm-badge]: https://img.shields.io/npm/v/seneca-load-balancer.svg
[npm-url]: https://npmjs.com/package/seneca-load-balancer
[travis-badge]: https://api.travis-ci.org/thekemkid/seneca-load-balancer.svg
[travis-url]: https://travis-ci.org/thekemid/seneca-load-balancer
[david-badge]: https://david-dm.org/thekemid/seneca-load-balancer.svg
[david-url]: https://david-dm.org/thekemid/seneca-load-balancer
[gitter-badge]: https://badges.gitter.im/senecajs/seneca.svg
[gitter-url]: https://gitter.im/senecajs/seneca

[lead]: https://github.com/thekemkid


text:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Compiler;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using FlatRedBall.Content.AnimationChain;
#if XNA4
using TargetPlatform = Microsoft.Xna.Framework.Content.Pipeline.TargetPlatform;
#else
using TargetPlatform = Microsoft.Xna.Framework.TargetPlatform;
#endif

namespace FlatRedBall.Content.Scene
{
    [ContentTypeWriter]
    class SpriteSaveWriter : ContentTypeWriter<SpriteSaveContent>
    {
        protected override void Write(ContentWriter output, SpriteSaveContent value)
        {
            if (ObjectReader.UseReflection)
            {
                ObjectWriter.WriteObject<SpriteSaveContent>(output, value);
            }
            else
            {
                WriteUsingGeneratedCode(output, value);
            }

        }

        public static void WriteUsingGeneratedCode(ContentWriter output, SpriteSaveContent value)
        {

            output.Write(value.TextureReference != null);
            if (value.TextureReference != null)
                output.WriteExternalReference(value.TextureReference);
            //output.Write(value.AnimationChainReference != null);
            //if (value.AnimationChainReference != null)
            //    output.WriteExternalReference(value.AnimationChainReference);
            output.Write(value.X);
            output.Write(value.Y);
            output.Write(value.Z);
            output.Write(value.XVelocity);
            output.Write(value.YVelocity);
            output.Write(value.ZVelocity);
            output.Write(value.XAcceleration);
            output.Write(value.YAcceleration);
            output.Write(value.ZAcceleration);
            output.Write(value.RotationX);
            output.Write(value.RotationY);
            output.Write(value.RotationZ);
            output.Write(value.RotationZVelocity);
            output.Write(value.ScaleX);
            output.Write(value.ScaleY);
            output.Write(value.ScaleXVelocity);
            output.Write(value.ScaleYVelocity);
            output.Write(value.RelativeX);
            output.Write(value.RelativeY);
            output.Write(value.RelativeZ);
            output.Write(value.RelativeRotationX);
            output.Write(value.RelativeRotationY);
            output.Write(value.RelativeRotationZ);
            output.Write(value.Fade);
            output.Write(value.FadeRate);
            output.Write(value.TintRed);
            output.Write(value.TintGreen);
            output.Write(value.TintBlue);
            output.Write(value.TintRedRate);
            output.Write(value.TintBlueRate);
            output.Write(value.TintGreenRate);
            if (value.ColorOperation != null)
                output.Write(value.ColorOperation);
            else
                output.Write("");
            if (value.BlendOperation != null)
                output.Write(value.BlendOperation);
            else
                output.Write("");
            if (value.Name != null)
                output.Write(value.Name);
            else
                output.Write("");
            if (value.Parent != null)
                output.Write(value.Parent);
            else
                output.Write("");
            if (value.Texture != null)
                output.Write(value.Texture);
            else
                output.Write("");
            output.Write(value.Animate);
            output.Write(value.CurrentChain);
            if (value.AnimationChainsFile != null)
                output.Write(value.AnimationChainsFile);
            else
                output.Write("");
            if (value.Type != null)
                output.Write(value.Type);
            else
                output.Write("");
            output.Write(value.Ordered);
            output.Write(value.Active);
            output.Write(value.ConstantPixelSize);
            output.Write(value.Visible);
            output.Write(value.TopTextureCoordinate);
            output.Write(value.BottomTextureCoordinate);
            output.Write(value.LeftTextureCoordinate);
            output.Write(value.RightTextureCoordinate);
            output.Write(value.FlipHorizontal);
            output.Write(value.FlipVertical);
            output.Write(System.Convert.ToInt32(value.TextureAddressMode));

        }

        public override string GetRuntimeReader(TargetPlatform targetPlatform)
        {
            return typeof(SpriteReader).AssemblyQualifiedName;
        }
    }
}


text:
<?php

namespace Google\AdsApi\Dfp\v201705;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class ResumeAndOverbookOrders extends \Google\AdsApi\Dfp\v201705\ResumeOrders
{

    /**
     * @param boolean $skipInventoryCheck
     */
    public function __construct($skipInventoryCheck = null)
    {
      parent::__construct($skipInventoryCheck);
    }

}


text:
namespace java {
  namespace lang {
    class Class;
  }
  namespace io {
    class IOException;
    class Closeable;
    class InputStream;
  }
}
template<class T> class JArray;

namespace org {
  namespace apache {
    namespace lucene {
      namespace store {

        class InputStreamDataInput : public ::org::apache::lucene::store::DataInput {
        public:
          enum {
            mid_init$_be2e4f90,
            mid_close_54c6a166,
            mid_readByte_54c6a172,
            mid_readBytes_86f4435f,
            max_mid
          };

          static ::java::lang::Class *class$;
          static jmethodID *mids$;
          static bool live$;
          static jclass initializeClass(bool);

          explicit InputStreamDataInput(jobject obj) : ::org::apache::lucene::store::DataInput(obj) {
            if (obj != NULL)
              env->getClass(initializeClass);
          }
          InputStreamDataInput(const InputStreamDataInput& obj) : ::org::apache::lucene::store::DataInput(obj) {}

          InputStreamDataInput(const ::java::io::InputStream &);

          void close() const;
          jbyte readByte() const;
          void readBytes(const JArray< jbyte > &, jint, jint) const;
        };
      }
    }
  }
}

#include <Python.h>

namespace org {
  namespace apache {
    namespace lucene {
      namespace store {
        extern PyTypeObject PY_TYPE(InputStreamDataInput);

        class t_InputStreamDataInput {
        public:
          PyObject_HEAD
          InputStreamDataInput object;
          static PyObject *wrap_Object(const InputStreamDataInput&);
          static PyObject *wrap_jobject(const jobject&);
          static void install(PyObject *module);
          static void initialize(PyObject *module);
        };
      }
    }
  }
}

#endif


text:
#ifndef HKX_ENVIRONMENT_H
#define HKX_ENVIRONMENT_H

extern HK_EXPORT_COMMON const class hkClass hkxEnvironmentVariableClass;

/// hkxEnvironment meta information
extern HK_EXPORT_COMMON const class hkClass hkxEnvironmentClass;

/// An hkxEnvironment represent a set of variables+values (string+string) used during processing of assets.
/// It is similar to the concept of the OS shell environment variables. Examples of them
/// would be: the name of the asset, the current configuration being used, etc.
/// NOTE: Variables are considered case-insensitive. Values are returned with the case they were stored
class HK_EXPORT_COMMON hkxEnvironment : public hkReferencedObject
{
	public:
		//+version(1)
		//+vtable(true)

		HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_SCENE_DATA );
		HK_DECLARE_REFLECTION();

		hkxEnvironment();
		hkxEnvironment(hkFinishLoadedObjectFlag f);

			/// Sets the value of the given variable. If the variable is new, it adds it. If value is HK_NULL, the
			/// variable is removed. Returns HK_FAILURE if trying to remove a non-existent variable.
		hkResult setVariable (const char* name, const char* value);

			/// Returns the stored value for the given variable. Return HK_NULL is the variable is unknown.
		const char* getVariableValue (const char* name) const;

			/// Erases all variables
		void clear ();

			/// Returns a single string representation of the environment, of the form
			/// var=value ; var = value ;.
		void convertToString( hkStringBuf& out ) const;

			/// Interprets a string as a sequence of name=value pairs, separated by semicolons. Quotes can be used on
			/// either side. If no value is provided, the variable will be removed (if present). Returns HK_FAILURE
			/// if the string couldn't be properly parsed.
			/// Example of a string is:
			/// \code var1 = "How are you?"; "var 2"= well ;var_3=; "var 4"= "thank you" \endcode
		hkResult interpretString(const char* str);

			/// Direct access to the variables. Returns the number of variables stored.
		int getNumVariables () const;

			/// Direct access to the variables. Returns the name of the i-th variable
		const char* getVariableName (int i) const;

			/// Direct access to the variables. Returns the value of the i-th variable
		const char* getVariableValue (int i) const;

			// Public for serialization
		struct Variable
		{
			HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_SCENE_DATA, hkxEnvironment::Variable );
			HK_DECLARE_REFLECTION();

			Variable() {}
			Variable(hkFinishLoadedObjectFlag f) : m_name(f), m_value(f) {}

			hkStringPtr m_name;
			hkStringPtr m_value;
		};

	private:

		int findVariableByName (const char* name) const;

		hkArray<struct Variable> m_variables;

};

#endif //HKX_ENVIRONMENT_H

/*
 * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907)
 *
 * Confidential Information of Havok.  (C) Copyright 1999-2014
 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
 * Logo, and the Havok buzzsaw logo are trademarks of Havok.  Title, ownership
 * rights, and intellectual property rights in the Havok software remain in
 * Havok and/or its suppliers.
 *
 * Use of this software for evaluation purposes is subject to and indicates
 * acceptance of the End User licence Agreement for this product. A copy of
 * the license is included with this software and is also available at www.havok.com/tryhavok.
 *
 */


text:
package models

import akka.actor.Actor
import akka.actor.Props
import javax.inject.Inject
import play.api.Play.current
import play.api.data.Form
import play.api.data.Forms
import play.api.libs.concurrent.Akka
import play.api.libs.json.Json
import play.api.libs.mailer.Email
import play.api.libs.mailer.MailerClient

class EmailActor @Inject() (mailer: MailerClient) {

  def sendEmail(m: EmailMessage, body: String) {
    val email2Contact = Email(
      m.subject,
      "Nilda Doce Tentação <carlos.fattor@gmail.com>",
      Seq(m.to),
      bodyText = Some(body),
      bodyHtml = Some(body))
    mailer.send(email2Contact)
  }

  def sendEmailAdmin(m: EmailMessage, body: String) {
    val email2Contact = Email(
      m.subject,
      "Nilda Doce Tentação <carlos.fattor@gmail.com>",
      Seq("carlos.fattor@gmail.com"),
      bodyText = Some(body),
      bodyHtml = Some(body))
    mailer.send(email2Contact)
  }
}

sealed trait EmailMessage {
  val name: String
  val to: String
  val site: Option[String]
  val comment: String
  val subject: String
}

case class MailToContact(name: String, to: String, site: Option[String], comment: String) extends EmailMessage {
  val subject = "Email de contato"
}

object MailToContact {
  import play.api.data.Forms._

  implicit val jsonFormat = Json.format[MailToContact]

  val contactFormValidation = Form(
    mapping(
      "name" -> nonEmptyText,
      "to" -> nonEmptyText,
      "site" -> optional(text),
      "comment" -> nonEmptyText) {
        (name, to, site, comment) =>
          MailToContact(
            name,
            to,
            site,
            comment)
      } {
        mailToContact =>
          Some(
            mailToContact.name,
            mailToContact.to,
            mailToContact.site,
            mailToContact.comment)
      })
}

case class MailToNewsLetter(to: String) extends EmailMessage {
  val subject = "Email de new letter"
  val name: String = ""
  val site: Option[String] = Some("")
  val comment: String = ""
}

object MailToNewsLetter {
  implicit val jsonFormat = Json.format[MailToNewsLetter]
}


text:
using Newtonsoft.Json;
using RestSharp;

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;

namespace EasyPost {
    public class Client {
        public string version;

        internal RestClient client;
        internal ClientConfiguration configuration;

        public Client(ClientConfiguration clientConfiguration) {
            System.Net.ServicePointManager.SecurityProtocol = Security.GetProtocol();

            if (clientConfiguration == null) throw new ArgumentNullException("clientConfiguration");
            configuration = clientConfiguration;

            client = new RestClient(clientConfiguration.ApiBase);

            Assembly assembly = Assembly.GetExecutingAssembly();
            FileVersionInfo info = FileVersionInfo.GetVersionInfo(assembly.Location);
            version = info.FileVersion;
        }

        public IRestResponse Execute(Request request) {
            return client.Execute(PrepareRequest(request));
        }

        public T Execute<T>(Request request) where T : new() {
            RestResponse<T> response = (RestResponse<T>)client.Execute<T>(PrepareRequest(request));
            int StatusCode = Convert.ToInt32(response.StatusCode);

            if (StatusCode > 399) {
                try {
                    Dictionary<string, Dictionary<string, object>> Body = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, object>>>(response.Content);
                    throw new HttpException(StatusCode, (string)Body["error"]["message"], (string)Body["error"]["code"]);
                } catch {
                    throw new HttpException(StatusCode, "RESPONSE.PARSE_ERROR", response.Content);
                }
            }

            return response.Data;
        }

        internal RestRequest PrepareRequest(Request request) {
            RestRequest restRequest = (RestRequest)request;

            restRequest.AddHeader("user_agent", string.Concat("EasyPost/v2 CSharp/", version));
            restRequest.AddHeader("authorization", "Bearer " + this.configuration.ApiKey);
            restRequest.AddHeader("content_type", "application/x-www-form-urlencoded");

            return restRequest;
        }
    }
}


text:
#ifndef CTEST_H
#define CTEST_H

#ifdef SPLATT_USE_MPI
#include <mpi.h>
#endif

typedef void (*SetupFunc)(void*);
typedef void (*TearDownFunc)(void*);

struct ctest {
    const char* ssname;  // suite name
    const char* ttname;  // test name
    void (*run)();
    int skip;

    void* data;
    SetupFunc setup;
    TearDownFunc teardown;

    unsigned int magic;
};

#define __FNAME(sname, tname) __ctest_##sname##_##tname##_run
#define __TNAME(sname, tname) __ctest_##sname##_##tname

#define __CTEST_MAGIC (0xdeadbeef)
#ifdef __APPLE__
#define __Test_Section __attribute__ ((unused,section ("__DATA, .ctest")))
#else
#define __Test_Section __attribute__ ((unused,section (".ctest")))
#endif

#define __CTEST_STRUCT(sname, tname, _skip, __data, __setup, __teardown) \
    struct ctest __TNAME(sname, tname) __Test_Section = { \
        .ssname=#sname, \
        .ttname=#tname, \
        .run = __FNAME(sname, tname), \
        .skip = _skip, \
        .data = __data, \
        .setup = (SetupFunc)__setup,					\
        .teardown = (TearDownFunc)__teardown,				\
        .magic = __CTEST_MAGIC };

#define CTEST_DATA(sname) struct sname##_data

#define CTEST_SETUP(sname) \
    void __attribute__ ((weak)) sname##_setup(struct sname##_data* data)

#define CTEST_TEARDOWN(sname) \
    void __attribute__ ((weak)) sname##_teardown(struct sname##_data* data)

#define __CTEST_INTERNAL(sname, tname, _skip) \
    void __FNAME(sname, tname)(); \
    __CTEST_STRUCT(sname, tname, _skip, NULL, NULL, NULL) \
    void __FNAME(sname, tname)()

#ifdef __APPLE__
#define SETUP_FNAME(sname) NULL
#define TEARDOWN_FNAME(sname) NULL
#else
#define SETUP_FNAME(sname) sname##_setup
#define TEARDOWN_FNAME(sname) sname##_teardown
#endif

#define __CTEST2_INTERNAL(sname, tname, _skip) \
    static struct sname##_data  __ctest_##sname##_data; \
    CTEST_SETUP(sname); \
    CTEST_TEARDOWN(sname); \
    void __FNAME(sname, tname)(struct sname##_data* data); \
    __CTEST_STRUCT(sname, tname, _skip, &__ctest_##sname##_data, SETUP_FNAME(sname), TEARDOWN_FNAME(sname)) \
    void __FNAME(sname, tname)(struct sname##_data* data)

void CTEST_LOG(char *fmt, ...);
void CTEST_ERR(char *fmt, ...);  // doesn't return

#define CTEST(sname, tname) __CTEST_INTERNAL(sname, tname, 0)
#define CTEST_SKIP(sname, tname) __CTEST_INTERNAL(sname, tname, 1)

#define CTEST2(sname, tname) __CTEST2_INTERNAL(sname, tname, 0)
#define CTEST2_SKIP(sname, tname) __CTEST2_INTERNAL(sname, tname, 1)

void assert_str(const char* exp, const char* real, const char* caller, int line);
#define ASSERT_STR(exp, real) assert_str(exp, real, __FILE__, __LINE__)

void assert_data(const unsigned char* exp, int expsize,
                 const unsigned char* real, int realsize,
                 const char* caller, int line);
#define ASSERT_DATA(exp, expsize, real, realsize) \
    assert_data(exp, expsize, real, realsize, __FILE__, __LINE__)

void assert_equal(long exp, long real, const char* caller, int line);
#define ASSERT_EQUAL(exp, real) assert_equal(exp, real, __FILE__, __LINE__)

void assert_not_equal(long exp, long real, const char* caller, int line);
#define ASSERT_NOT_EQUAL(exp, real) assert_not_equal(exp, real, __FILE__, __LINE__)

void assert_null(void* real, const char* caller, int line);
#define ASSERT_NULL(real) assert_null((void*)real, __FILE__, __LINE__)

void assert_not_null(const void* real, const char* caller, int line);
#define ASSERT_NOT_NULL(real) assert_not_null(real, __FILE__, __LINE__)

void assert_true(int real, const char* caller, int line);
#define ASSERT_TRUE(real) assert_true(real, __FILE__, __LINE__)

void assert_false(int real, const char* caller, int line);
#define ASSERT_FALSE(real) assert_false(real, __FILE__, __LINE__)

void assert_fail(const char* caller, int line);
#define ASSERT_FAIL() assert_fail(__FILE__, __LINE__)

void assert_dbl_near(double exp, double real, double tol, const char* caller, int line);
#define ASSERT_DBL_NEAR(exp, real) assert_dbl_near(exp, real, 1e-4, __FILE__, __LINE__)
#define ASSERT_DBL_NEAR_TOL(exp, real, tol) assert_dbl_near(exp, real, tol, __FILE__, __LINE__)

void assert_dbl_far(double exp, double real, double tol, const char* caller, int line);
#define ASSERT_DBL_FAR(exp, real) assert_dbl_far(exp, real, 1e-4, __FILE__, __LINE__)
#define ASSERT_DBL_FAR_TOL(exp, real, tol) assert_dbl_far(exp, real, tol, __FILE__, __LINE__)

#ifdef CTEST_MAIN

#include <setjmp.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <inttypes.h>
#include <unistd.h>
#include <stdint.h>
#include <stdlib.h>

#ifdef __APPLE__
#include <dlfcn.h>
#endif

//#define COLOR_OK

static size_t ctest_errorsize;
static char* ctest_errormsg;
#define MSG_SIZE 4096
static char ctest_errorbuffer[MSG_SIZE];
static jmp_buf ctest_err;
static int color_output = 1;
static const char* suite_name;

typedef int (*filter_func)(struct ctest*);

#define ANSI_BLACK    "\033[0;30m"
#define ANSI_RED      "\033[0;31m"
#define ANSI_GREEN    "\033[0;32m"
#define ANSI_YELLOW   "\033[0;33m"
#define ANSI_BLUE     "\033[0;34m"
#define ANSI_MAGENTA  "\033[0;35m"
#define ANSI_CYAN     "\033[0;36m"
#define ANSI_GREY     "\033[0;37m"
#define ANSI_DARKGREY "\033[01;30m"
#define ANSI_BRED     "\033[01;31m"
#define ANSI_BGREEN   "\033[01;32m"
#define ANSI_BYELLOW  "\033[01;33m"
#define ANSI_BBLUE    "\033[01;34m"
#define ANSI_BMAGENTA "\033[01;35m"
#define ANSI_BCYAN    "\033[01;36m"
#define ANSI_WHITE    "\033[01;37m"
#define ANSI_NORMAL   "\033[0m"

static CTEST(suite, test) { }

static void msg_start(const char* color, const char* title) {
    int size;
    if (color_output) {
        size = snprintf(ctest_errormsg, ctest_errorsize, "%s", color);
        ctest_errorsize -= size;
        ctest_errormsg += size;
    }
    size = snprintf(ctest_errormsg, ctest_errorsize, "  %s: ", title);
    ctest_errorsize -= size;
    ctest_errormsg += size;
}

static void msg_end() {
    int size;
    if (color_output) {
        size = snprintf(ctest_errormsg, ctest_errorsize, ANSI_NORMAL);
        ctest_errorsize -= size;
        ctest_errormsg += size;
    }
    size = snprintf(ctest_errormsg, ctest_errorsize, "\n");
    ctest_errorsize -= size;
    ctest_errormsg += size;
}

void CTEST_LOG(char *fmt, ...)
{
    va_list argp;
    msg_start(ANSI_BLUE, "LOG");

    va_start(argp, fmt);
    int size = vsnprintf(ctest_errormsg, ctest_errorsize, fmt, argp);
    ctest_errorsize -= size;
    ctest_errormsg += size;
    va_end(argp);

    msg_end();
}

void CTEST_ERR(char *fmt, ...)
{
    va_list argp;
    msg_start(ANSI_YELLOW, "ERR");

    va_start(argp, fmt);
    int size = vsnprintf(ctest_errormsg, ctest_errorsize, fmt, argp);
    ctest_errorsize -= size;
    ctest_errormsg += size;
    va_end(argp);

    msg_end();
    longjmp(ctest_err, 1);
}

void assert_str(const char* exp, const char*  real, const char* caller, int line) {
    if ((exp == NULL && real != NULL) ||
        (exp != NULL && real == NULL) ||
        (exp && real && strcmp(exp, real) != 0)) {
        CTEST_ERR("%s:%d  expected '%s', got '%s'", caller, line, exp, real);
    }
}

void assert_data(const unsigned char* exp, int expsize,
                 const unsigned char* real, int realsize,
                 const char* caller, int line) {
    int i;
    if (expsize != realsize) {
        CTEST_ERR("%s:%d  expected %d bytes, got %d", caller, line, expsize, realsize);
    }
    for (i=0; i<expsize; i++) {
        if (exp[i] != real[i]) {
            CTEST_ERR("%s:%d expected 0x%02x at offset %d got 0x%02x",
                caller, line, exp[i], i, real[i]);
        }
    }
}

void assert_equal(long exp, long real, const char* caller, int line) {
    if (exp != real) {
        CTEST_ERR("%s:%d  expected %ld, got %ld", caller, line, exp, real);
    }
}

void assert_not_equal(long exp, long real, const char* caller, int line) {
    if ((exp) == (real)) {
        CTEST_ERR("%s:%d  should not be %ld", caller, line, real);
    }
}

void assert_dbl_near(double exp, double real, double tol, const char* caller, int line) {
    double diff = exp - real;
    double absdiff = diff;
    /* avoid using fabs and linking with a math lib */
    if(diff < 0) {
      absdiff *= -1;
    }
    if (absdiff > tol) {
        CTEST_ERR("%s:%d  expected %0.3e, got %0.3e (diff %0.3e, tol %0.3e)", caller, line, exp, real, diff, tol);
    }
}

void assert_dbl_far(double exp, double real, double tol, const char* caller, int line) {
    double diff = exp - real;
    double absdiff = diff;
    /* avoid using fabs and linking with a math lib */
    if(diff < 0) {
      absdiff *= -1;
    }
    if (absdiff <= tol) {
        CTEST_ERR("%s:%d  expected %0.3e, got %0.3e (diff %0.3e, tol %0.3e)", caller, line, exp, real, diff, tol);
    }
}

void assert_null(void* real, const char* caller, int line) {
    if ((real) != NULL) {
        CTEST_ERR("%s:%d  should be NULL", caller, line);
    }
}

void assert_not_null(const void* real, const char* caller, int line) {
    if (real == NULL) {
        CTEST_ERR("%s:%d  should not be NULL", caller, line);
    }
}

void assert_true(int real, const char* caller, int line) {
    if ((real) == 0) {
        CTEST_ERR("%s:%d  should be true", caller, line);
    }
}

void assert_false(int real, const char* caller, int line) {
    if ((real) != 0) {
        CTEST_ERR("%s:%d  should be false", caller, line);
    }
}

void assert_fail(const char* caller, int line) {
    CTEST_ERR("%s:%d  shouldn't come here", caller, line);
}

static int suite_all(struct ctest* t) {
    return 1;
}

static int suite_filter(struct ctest* t) {
    return strncmp(suite_name, t->ssname, strlen(suite_name)) == 0;
}

static uint64_t getCurrentTime() {
    struct timeval now;
    gettimeofday(&now, NULL);
    uint64_t now64 = now.tv_sec;
    now64 *= 1000000;
    now64 += (now.tv_usec);
    return now64;
}

static void color_print(const char* color, const char* text) {
#ifdef SPLATT_USE_MPI
  int rank = 0;
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  if(rank > 0) {
    return;
  }
#endif

    if (color_output)
        printf("%s%s"ANSI_NORMAL"\n", color, text);
    else
        printf("%s\n", text);
}

#ifdef __APPLE__
static void *find_symbol(struct ctest *test, const char *fname)
{
    size_t len = strlen(test->ssname) + 1 + strlen(fname);
    char *symbol_name = (char *) malloc(len + 1);
    memset(symbol_name, 0, len + 1);
    snprintf(symbol_name, len + 1, "%s_%s", test->ssname, fname);

    //fprintf(stderr, ">>>> dlsym: loading %s\n", symbol_name);
    void *symbol = dlsym(RTLD_DEFAULT, symbol_name);
    if (!symbol) {
        //fprintf(stderr, ">>>> ERROR: %s\n", dlerror());
    }
    // returns NULL on error

    free(symbol_name);
    return symbol;
}
#endif

#ifdef CTEST_SEGFAULT
#include <signal.h>
static void sighandler(int signum)
{
    char msg[128];
    sprintf(msg, "[SIGNAL %d: %s]", signum, sys_siglist[signum]);
    color_print(ANSI_BRED, msg);
    fflush(stdout);

    /* "Unregister" the signal handler and send the signal back to the process
     * so it can terminate as expected */
    signal(signum, SIG_DFL);
    kill(getpid(), signum);
}
#endif

int ctest_main(int argc, const char *argv[])
{
    static int total = 0;
    static int num_ok = 0;
    static int num_fail = 0;
    static int num_skip = 0;
    static int index = 1;
    static filter_func filter = suite_all;

    int rank = 0;
#ifdef SPLATT_USE_MPI
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
#endif

#ifdef CTEST_SEGFAULT
    signal(SIGSEGV, sighandler);
#endif

    if (argc == 2) {
        suite_name = argv[1];
        filter = suite_filter;
    }

    color_output = isatty(1);
    uint64_t t1 = getCurrentTime();

    struct ctest* ctest_begin = &__TNAME(suite, test);
    struct ctest* ctest_end = &__TNAME(suite, test);
    // find begin and end of section by comparing magics
    while (1) {
        struct ctest* t = ctest_begin-1;
        if (t->magic != __CTEST_MAGIC) break;
        ctest_begin--;
    }
    while (1) {
        struct ctest* t = ctest_end+1;
        if (t->magic != __CTEST_MAGIC) break;
        ctest_end++;
    }
    ctest_end++;    // end after last one

    static struct ctest* test;
    for (test = ctest_begin; test != ctest_end; test++) {
        if (test == &__ctest_suite_test) continue;
        if (filter(test)) total++;
    }

    for (test = ctest_begin; test != ctest_end; test++) {
        if (test == &__ctest_suite_test) continue;
        if (filter(test)) {
            ctest_errorbuffer[0] = 0;
            ctest_errorsize = MSG_SIZE-1;
            ctest_errormsg = ctest_errorbuffer;
            if(rank == 0) {
              printf("TEST %d/%d %s:%s ", index, total, test->ssname, test->ttname);
              fflush(stdout);
            }
            if (test->skip) {
                color_print(ANSI_BYELLOW, "[SKIPPED]");
                num_skip++;
            } else {
                int result = setjmp(ctest_err);
                if (result == 0) {
#ifdef __APPLE__
                    if (!test->setup) {
                        test->setup = find_symbol(test, "setup");
                    }
                    if (!test->teardown) {
                        test->teardown = find_symbol(test, "teardown");
                    }
#endif

                    if (test->setup) test->setup(test->data);
                    if (test->data)
                      test->run(test->data);
                    else
                      test->run();
                    if (test->teardown) test->teardown(test->data);
                    // if we got here it's ok
#ifdef COLOR_OK
                    color_print(ANSI_BGREEN, "[OK]");
#else
                    if(rank == 0) {
                      printf("[OK]\n");
                    }
#endif
                    num_ok++;
                } else {
                    color_print(ANSI_BRED, "[FAIL]");
                    num_fail++;
                }
                if (ctest_errorsize != MSG_SIZE-1) printf("%s", ctest_errorbuffer);
            }
            index++;
        }
    }
    uint64_t t2 = getCurrentTime();

    const char* color = (num_fail) ? ANSI_BRED : ANSI_GREEN;
    char results[80];
    sprintf(results, "RESULTS: %d tests (%d ok, %d failed, %d skipped) ran in %"PRIu64" ms", total, num_ok, num_fail, num_skip, (t2 - t1)/1000);
    color_print(color, results);
    return num_fail;
}

#endif

#endif


text:
/* ------------------------------------------------------------------------------
 *
 *  # D3.js - vertical sortable bars
 *
 *  Demo d3.js vertical bar chart setup with animated sorting and .tsv data source
 *
 *  Version: 1.0
 *  Latest update: August 1, 2015
 *
 * ---------------------------------------------------------------------------- */

$(function () {

    // Add uniform styling
    $(".toggle-sort").uniform();

    // Initialize chart
    sortableVertical('#d3-bar-sortable-vertical', 400);

    // Chart setup
    function sortableVertical(element, height) {

        // Basic setup
        // ------------------------------

        // Define main variables
        var d3Container = d3.select(element),
            margin = {top: 5, right: 20, bottom: 20, left: 40},
            width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right,
            height = height - margin.top - margin.bottom - 5;

        // Format data
        var formatPercent = d3.format(".0%");

        // Construct scales
        // ------------------------------

        // Horizontal
        var x = d3.scale.ordinal()
            .rangeRoundBands([0, width], .1, 1);

        // Vertical
        var y = d3.scale.linear()
            .range([height, 0]);

        // Colors
        var colors = d3.scale.category20c();

        // Create axes
        // ------------------------------

        // Horizontal
        var xAxis = d3.svg.axis()
            .scale(x)
            .orient("bottom");

        // Vertical
        var yAxis = d3.svg.axis()
            .scale(y)
            .orient("left")
            .tickFormat(formatPercent);

        // Create chart
        // ------------------------------

        // Add SVG element
        var container = d3Container.append("svg");

        // Add SVG group
        var svg = container
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        // Load data
        // ------------------------------

        d3.tsv("assets/demo_data/d3/bars/bars_basic.tsv", function(error, data) {

            // Pull out values
            data.forEach(function(d) {
                d.frequency = +d.frequency;
            });

            // Set input domains
            // ------------------------------

            // Horizontal
            x.domain(data.map(function(d) { return d.letter; }));

            // Vertical
            y.domain([0, d3.max(data, function(d) { return d.frequency; })]);

            //
            // Append chart elements
            //

            // Append axes
            // ------------------------------

            // Horizontal
            svg.append("g")
                .attr("class", "d3-axis d3-axis-horizontal d3-axis-strong")
                .attr("transform", "translate(0," + height + ")")
                .call(xAxis);

            // Vertical
            var verticalAxis = svg.append("g")
                .attr("class", "d3-axis d3-axis-vertical d3-axis-strong")
                .call(yAxis);

            // Add text label
            verticalAxis.append("text")
                .attr("transform", "rotate(-90)")
                .attr("y", 10)
                .attr("dy", ".71em")
                .style("text-anchor", "end")
                .style("fill", "#999")
                .style("font-size", 12)
                .text("Frequency");

            // Append bars
            // ------------------------------

            svg.selectAll(".d3-bar")
                .data(data)
                .enter()
                .append("rect")
                    .attr("class", "d3-bar")
                    .attr("fill", function(d, i) { return colors(i); })
                    .attr("x", function(d) { return x(d.letter); })
                    .attr("width", x.rangeBand())
                    .attr("y", function(d) { return y(d.frequency); })
                    .attr("height", function(d) { return height - y(d.frequency); });

            // Change data sets
            // ------------------------------

            // Attach change event
            d3.select(".toggle-sort").on("change", change);

            // Sort values on page load with delay
            var sortTimeout = setTimeout(function() {
                d3.select(".toggle-sort").property("checked", true).each(change);
                $.uniform.update();
            }, 2000);

            // Sorting function
            function change() {
                clearTimeout(sortTimeout);

                // Copy-on-write since tweens are evaluated after a delay.
                var x0 = x.domain(data.sort(this.checked
                    ? function(a, b) { return b.frequency - a.frequency; }
                    : function(a, b) { return d3.ascending(a.letter, b.letter); })
                    .map(function(d) { return d.letter; }))
                    .copy();

                var transition = svg.transition().duration(750),
                    delay = function(d, i) { return i * 50; };

                transition.selectAll(".d3-bar")
                    .delay(delay)
                    .attr("x", function(d) { return x0(d.letter); });

                transition.select(".d3-axis-horizontal")
                    .call(xAxis)
                    .selectAll("g")
                    .delay(delay);
            }
        });

        // Resize chart
        // ------------------------------

        // Call function on window resize
        $(window).on('resize', resize);

        // Call function on sidebar width change
        $('.sidebar-control').on('click', resize);

        // Resize function
        //
        // Since D3 doesn't support SVG resize by default,
        // we need to manually specify parts of the graph that need to
        // be updated on window resize
        function resize() {

            // Layout variables
            width = d3Container.node().getBoundingClientRect().width - margin.left - margin.right;

            // Layout
            // -------------------------

            // Main svg width
            container.attr("width", width + margin.left + margin.right);

            // Width of appended group
            svg.attr("width", width + margin.left + margin.right);

            // Axes
            // -------------------------

            // Horizontal range
            x.rangeRoundBands([0, width], .1, 1);

            // Horizontal axis
            svg.selectAll('.d3-axis-horizontal').call(xAxis);

            // Chart elements
            // -------------------------

            // Line path
            svg.selectAll('.d3-bar').attr("width", x.rangeBand()).attr("x", function(d) { return x(d.letter); });
        }
    }
});


text:
package actions;

import java.awt.event.*;
import javax.swing.*;

import gui.*;

public class ButtonPrevious extends AbstractAction
{
  public ButtonPrevious(ImageIcon icon)
  {
    super("Previous Window", icon);
  }

  public void actionPerformed(ActionEvent e)
  {
    MainWindow.centerPanel.selectFrame(false);
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class pylapp.buza.android.dao.buza.DaoImplEmptyMockBuza</title>
<meta name="date" content="2016-07-21">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
pylapp.buza.android.dao.buza.DaoImplEmptyMockBuza

Packages that use DaoImplEmptyMockBuza

Package
Description

pylapp.buza.android.dao.buza

Uses of DaoImplEmptyMockBuza in pylapp.buza.android.dao.buza

Fields in pylapp.buza.android.dao.buza declared as DaoImplEmptyMockBuza

Modifier and Type
Field and Description

private static DaoImplEmptyMockBuza
DaoImplEmptyMockBuza.sInstance

The singleton

Methods in pylapp.buza.android.dao.buza that return DaoImplEmptyMockBuza

Modifier and Type
Method and Description

static DaoImplEmptyMockBuza
DaoImplEmptyMockBuza.getInstance()

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes