<commit_before>/*     Copyright 2015-2018 Egor Yusov
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS.
*
*  In no event and under no legal theory, whether in tort (including negligence),
*  contract, or otherwise, unless required by applicable law (such as deliberate
*  and grossly negligent acts) or agreed to in writing, shall any Contributor be
*  liable for any damages, including any direct, indirect, special, incidental,
*  or consequential damages of any character arising as a result of this License or
*  out of the use or inability to use the software (including but not limited to damages
*  for loss of goodwill, work stoppage, computer failure or malfunction, or any and
*  all other commercial damages or losses), even if such Contributor has been advised
*  of the possibility of such damages.
*/

#include "SampleApp.hpp"
#include "ImguiUWPEventHelper.h"
#include "InputControllerEventHandlerUWP.h"
#include "RenderDeviceD3D12.h"
#include "RenderDeviceD3D11.h"
#include "SwapChainD3D12.h"
#include "SwapChainD3D11.h"
#include "EngineFactoryD3D11.h"
#include "EngineFactoryD3D12.h"
#include "ImGuiImplUWP.hpp"

namespace Diligent
{

class SampleAppUWP final : public SampleApp
{
public:
    SampleAppUWP()
    {
        m_DeviceType = RENDER_DEVICE_TYPE_D3D12;
    }

    virtual void OnSetWindow(Windows::UI::Core::CoreWindow^ window)override final
    {
        m_ImguiEventHandler = ImguiUWPEventHelper::Create(window);
        m_InputControllerEventHandlerUWP = InputControllerEventHandlerUWP::Create(window, m_TheSample->GetInputController().GetSharedState());
    }

    virtual void OnWindowSizeChanged()override final
    {
        InitWindowSizeDependentResources();

        if (m_SampleInitialized)
        {
            const auto& SCDesc = m_pSwapChain->GetDesc();
            m_TheSample->WindowResize(SCDesc.Width, SCDesc.Height);
        }
    }

    virtual void Render()override
    {
        // Don't try to render anything before the first Update.
        if (m_timer.GetFrameCount() == 0)
        {
            return;
        }
        SampleApp::Render();
        m_bFrameReady = true;
    }

    // Notifies the app that it is being suspended.
    virtual void OnSuspending()override final
    {
        // TODO: Replace this with your app's suspending logic.

        // Process lifetime management may terminate suspended apps at any time, so it is
        // good practice to save any state that will allow the app to restart where it left off.

        //m_sceneRenderer->SaveState();

        // If your application uses video memory allocations that are easy to re-create,
        // consider releasing that memory to make it available to other applications.
    }

    // Notifes the app that it is no longer suspended.
    virtual void OnResuming()override final
    {
        // TODO: Replace this with your app's resuming logic.
    }

    // Notifies renderers that device resources need to be released.
    virtual void OnDeviceRemoved()override final
    {
        // TODO: Save any necessary application or renderer state and release the renderer
        // and its resources which are no longer valid.
        //m_sceneRenderer->SaveState();
        m_TheSample.reset();
    }

    virtual void Present()override
    {
        if (m_pSwapChain)
            m_pSwapChain->Present();

        //// If the device was removed either by a disconnection or a driver upgrade, we
        //// must recreate all device resources.
        //if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
        //{
        //	m_deviceRemoved = true;
        //}
        //else
        //{
        //	DX::ThrowIfFailed(hr);
        //}
    }

    virtual std::shared_ptr<DX::DeviceResources> InitDeviceResources()override
    {
        try
        {
            InitializeDiligentEngine(nullptr);

            ID3D12Device *pd3d12Device = nullptr;
            ID3D11Device *pd3d11Device = nullptr;
            if (m_DeviceType == RENDER_DEVICE_TYPE_D3D12)
            {
                // Store pointers to the Direct3D 11.1 API device and immediate context.
                RefCntAutoPtr<IRenderDeviceD3D12> pRenderDeviceD3D12(m_pDevice, IID_RenderDeviceD3D12);
                pd3d12Device = pRenderDeviceD3D12->GetD3D12Device();
            }
            else if (m_DeviceType == RENDER_DEVICE_TYPE_D3D11)
            {
                RefCntAutoPtr<IRenderDeviceD3D11> pRenderDeviceD3D11(m_pDevice, IID_RenderDeviceD3D11);
                pd3d11Device = pRenderDeviceD3D11->GetD3D11Device();
            }
            else
            {
                UNEXPECTED("Unexpected device type");
            }
            m_DeviceResources = std::make_shared<DX::DeviceResources>(pd3d11Device, pd3d12Device);
        }
        catch(...)
        {
            LOG_ERROR("Failed to initialize Diligent Engine.");
        }

        return m_DeviceResources;
    }

    virtual void InitWindowSizeDependentResources()override
    {
        if (!m_DeviceResources)
            return;

        m_DeviceResources->UpdateRenderTargetSize();
        auto backBufferWidth = m_DeviceResources->GetBackBufferWidth();
        auto backBufferHeight = m_DeviceResources->GetBackBufferHeight();

        if (m_swapChain != nullptr)
        {
            m_swapChain.Reset();

            // If the swap chain already exists, resize it.
            m_pSwapChain->Resize(backBufferWidth, backBufferHeight);

    #if 0
        	if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
        	{
        		// If the device was removed for any reason, a new device and swap chain will need to be created.
        		m_deviceRemoved = true;

        		// Do not continue execution of this method. DeviceResources will be destroyed and re-created.
        		return;
        	}
        	else
        	{
        		DX::ThrowIfFailed(hr);
        	}
    #endif
        }
        else
        {
        	//DXGI_SCALING scaling = DisplayMetrics::SupportHighResolutions ? DXGI_SCALING_NONE : DXGI_SCALING_STRETCH;
            SwapChainDesc  SCDesc;
            SCDesc.Width  = backBufferWidth;
            SCDesc.Height = backBufferHeight;
            SCDesc.ColorBufferFormat = TEX_FORMAT_RGBA8_UNORM_SRGB;
            SCDesc.DepthBufferFormat = TEX_FORMAT_D32_FLOAT;
            auto window = m_DeviceResources->GetWindow();
            UWPNativeWindow UWPWindow{reinterpret_cast<IUnknown*>(window)};
            IDXGISwapChain3 *pDXGISwapChain3 = nullptr;
            if (m_DeviceType == RENDER_DEVICE_TYPE_D3D12)
            {
                GetEngineFactoryD3D12()->CreateSwapChainD3D12(m_pDevice, m_pImmediateContext, SCDesc, FullScreenModeDesc{}, UWPWindow, &m_pSwapChain);
            }
            else if (m_DeviceType == RENDER_DEVICE_TYPE_D3D11)
            {
                GetEngineFactoryD3D11()->CreateSwapChainD3D11(m_pDevice, m_pImmediateContext, SCDesc, FullScreenModeDesc{}, UWPWindow, &m_pSwapChain);
            }
            else
                UNEXPECTED("Unexpected device type");
        }

        IDXGISwapChain3 *pDXGISwapChain3 = nullptr;
        if (m_DeviceType == RENDER_DEVICE_TYPE_D3D12)
        {
            RefCntAutoPtr<ISwapChainD3D12> pSwapChainD3D12(m_pSwapChain, IID_SwapChainD3D12);
            pSwapChainD3D12->GetDXGISwapChain()->QueryInterface(__uuidof(pDXGISwapChain3), reinterpret_cast<void**>(&pDXGISwapChain3));
        }
        else if (m_DeviceType == RENDER_DEVICE_TYPE_D3D11)
        {
            RefCntAutoPtr<ISwapChainD3D11> pSwapChainD3D11(m_pSwapChain, IID_SwapChainD3D11);
            pSwapChainD3D11->GetDXGISwapChain()->QueryInterface(__uuidof(pDXGISwapChain3), reinterpret_cast<void**>(&pDXGISwapChain3));
        }
        else
            UNEXPECTED("Unexpected device type");
        m_swapChain.Attach(pDXGISwapChain3);

        m_DeviceResources->SetSwapChainRotation(m_swapChain.Get());
    }

    virtual void CreateRenderers()override
    {
        if (!m_DeviceResources)
            return;

        const auto& SCDesc = m_pSwapChain->GetDesc();
        m_pImGui.reset(new ImGuiImplUWP(m_pDevice, SCDesc.ColorBufferFormat, SCDesc.DepthBufferFormat, SCDesc.Width, SCDesc.Height));

        InitializeSample();

        m_SampleInitialized = true;
    }

private:
    ImguiUWPEventHelper^ m_ImguiEventHandler;
    InputControllerEventHandlerUWP^ m_InputControllerEventHandlerUWP;

    Microsoft::WRL::ComPtr<IDXGISwapChain3>	m_swapChain;
    bool m_SampleInitialized = false;
};

NativeAppBase* CreateApplication()
{
    return new SampleAppUWP;
}

}
<commit_msg>Minor update to SampleAppUWP to support dynamic engine libraries<commit_after>/*     Copyright 2015-2018 Egor Yusov
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS.
*
*  In no event and under no legal theory, whether in tort (including negligence),
*  contract, or otherwise, unless required by applicable law (such as deliberate
*  and grossly negligent acts) or agreed to in writing, shall any Contributor be
*  liable for any damages, including any direct, indirect, special, incidental,
*  or consequential damages of any character arising as a result of this License or
*  out of the use or inability to use the software (including but not limited to damages
*  for loss of goodwill, work stoppage, computer failure or malfunction, or any and
*  all other commercial damages or losses), even if such Contributor has been advised
*  of the possibility of such damages.
*/

#include "SampleApp.hpp"
#include "ImguiUWPEventHelper.h"
#include "InputControllerEventHandlerUWP.h"
#include "RenderDeviceD3D12.h"
#include "RenderDeviceD3D11.h"
#include "SwapChainD3D12.h"
#include "SwapChainD3D11.h"
#include "EngineFactoryD3D11.h"
#include "EngineFactoryD3D12.h"
#include "ImGuiImplUWP.hpp"

namespace Diligent
{

class SampleAppUWP final : public SampleApp
{
public:
    SampleAppUWP()
    {
        m_DeviceType = RENDER_DEVICE_TYPE_D3D12;
    }

    virtual void OnSetWindow(Windows::UI::Core::CoreWindow^ window)override final
    {
        m_ImguiEventHandler = ImguiUWPEventHelper::Create(window);
        m_InputControllerEventHandlerUWP = InputControllerEventHandlerUWP::Create(window, m_TheSample->GetInputController().GetSharedState());
    }

    virtual void OnWindowSizeChanged()override final
    {
        InitWindowSizeDependentResources();

        if (m_SampleInitialized)
        {
            const auto& SCDesc = m_pSwapChain->GetDesc();
            m_TheSample->WindowResize(SCDesc.Width, SCDesc.Height);
        }
    }

    virtual void Render()override
    {
        // Don't try to render anything before the first Update.
        if (m_timer.GetFrameCount() == 0)
        {
            return;
        }
        SampleApp::Render();
        m_bFrameReady = true;
    }

    // Notifies the app that it is being suspended.
    virtual void OnSuspending()override final
    {
        // TODO: Replace this with your app's suspending logic.

        // Process lifetime management may terminate suspended apps at any time, so it is
        // good practice to save any state that will allow the app to restart where it left off.

        //m_sceneRenderer->SaveState();

        // If your application uses video memory allocations that are easy to re-create,
        // consider releasing that memory to make it available to other applications.
    }

    // Notifes the app that it is no longer suspended.
    virtual void OnResuming()override final
    {
        // TODO: Replace this with your app's resuming logic.
    }

    // Notifies renderers that device resources need to be released.
    virtual void OnDeviceRemoved()override final
    {
        // TODO: Save any necessary application or renderer state and release the renderer
        // and its resources which are no longer valid.
        //m_sceneRenderer->SaveState();
        m_TheSample.reset();
    }

    virtual void Present()override
    {
        if (m_pSwapChain)
            m_pSwapChain->Present();

        //// If the device was removed either by a disconnection or a driver upgrade, we
        //// must recreate all device resources.
        //if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
        //{
        //	m_deviceRemoved = true;
        //}
        //else
        //{
        //	DX::ThrowIfFailed(hr);
        //}
    }

    virtual std::shared_ptr<DX::DeviceResources> InitDeviceResources()override
    {
        try
        {
            InitializeDiligentEngine(nullptr);

            ID3D12Device *pd3d12Device = nullptr;
            ID3D11Device *pd3d11Device = nullptr;
            if (m_DeviceType == RENDER_DEVICE_TYPE_D3D12)
            {
                // Store pointers to the Direct3D 11.1 API device and immediate context.
                RefCntAutoPtr<IRenderDeviceD3D12> pRenderDeviceD3D12(m_pDevice, IID_RenderDeviceD3D12);
                pd3d12Device = pRenderDeviceD3D12->GetD3D12Device();
            }
            else if (m_DeviceType == RENDER_DEVICE_TYPE_D3D11)
            {
                RefCntAutoPtr<IRenderDeviceD3D11> pRenderDeviceD3D11(m_pDevice, IID_RenderDeviceD3D11);
                pd3d11Device = pRenderDeviceD3D11->GetD3D11Device();
            }
            else
            {
                UNEXPECTED("Unexpected device type");
            }
            m_DeviceResources = std::make_shared<DX::DeviceResources>(pd3d11Device, pd3d12Device);
        }
        catch(...)
        {
            LOG_ERROR("Failed to initialize Diligent Engine.");
        }

        return m_DeviceResources;
    }

    virtual void InitWindowSizeDependentResources()override
    {
        if (!m_DeviceResources)
            return;

        m_DeviceResources->UpdateRenderTargetSize();
        auto backBufferWidth = m_DeviceResources->GetBackBufferWidth();
        auto backBufferHeight = m_DeviceResources->GetBackBufferHeight();

        if (m_swapChain != nullptr)
        {
            m_swapChain.Reset();

            // If the swap chain already exists, resize it.
            m_pSwapChain->Resize(backBufferWidth, backBufferHeight);

    #if 0
        	if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
        	{
        		// If the device was removed for any reason, a new device and swap chain will need to be created.
        		m_deviceRemoved = true;

        		// Do not continue execution of this method. DeviceResources will be destroyed and re-created.
        		return;
        	}
        	else
        	{
        		DX::ThrowIfFailed(hr);
        	}
    #endif
        }
        else
        {
        	//DXGI_SCALING scaling = DisplayMetrics::SupportHighResolutions ? DXGI_SCALING_NONE : DXGI_SCALING_STRETCH;
            SwapChainDesc  SCDesc;
            SCDesc.Width  = backBufferWidth;
            SCDesc.Height = backBufferHeight;
            SCDesc.ColorBufferFormat = TEX_FORMAT_RGBA8_UNORM_SRGB;
            SCDesc.DepthBufferFormat = TEX_FORMAT_D32_FLOAT;
            auto window = m_DeviceResources->GetWindow();
            UWPNativeWindow UWPWindow{reinterpret_cast<IUnknown*>(window)};
            IDXGISwapChain3 *pDXGISwapChain3 = nullptr;
            if (m_DeviceType == RENDER_DEVICE_TYPE_D3D12)
            {
                RefCntAutoPtr<IEngineFactoryD3D12> pFactoryD3D12{m_pEngineFactory, IID_EngineFactoryD3D12};
                pFactoryD3D12->CreateSwapChainD3D12(m_pDevice, m_pImmediateContext, SCDesc, FullScreenModeDesc{}, UWPWindow, &m_pSwapChain);
            }
            else if (m_DeviceType == RENDER_DEVICE_TYPE_D3D11)
            {
                RefCntAutoPtr<IEngineFactoryD3D11> pFactoryD3D11{m_pEngineFactory, IID_EngineFactoryD3D11};
                pFactoryD3D11->CreateSwapChainD3D11(m_pDevice, m_pImmediateContext, SCDesc, FullScreenModeDesc{}, UWPWindow, &m_pSwapChain);
            }
            else
                UNEXPECTED("Unexpected device type");
        }

        IDXGISwapChain3 *pDXGISwapChain3 = nullptr;
        if (m_DeviceType == RENDER_DEVICE_TYPE_D3D12)
        {
            RefCntAutoPtr<ISwapChainD3D12> pSwapChainD3D12(m_pSwapChain, IID_SwapChainD3D12);
            pSwapChainD3D12->GetDXGISwapChain()->QueryInterface(__uuidof(pDXGISwapChain3), reinterpret_cast<void**>(&pDXGISwapChain3));
        }
        else if (m_DeviceType == RENDER_DEVICE_TYPE_D3D11)
        {
            RefCntAutoPtr<ISwapChainD3D11> pSwapChainD3D11(m_pSwapChain, IID_SwapChainD3D11);
            pSwapChainD3D11->GetDXGISwapChain()->QueryInterface(__uuidof(pDXGISwapChain3), reinterpret_cast<void**>(&pDXGISwapChain3));
        }
        else
            UNEXPECTED("Unexpected device type");
        m_swapChain.Attach(pDXGISwapChain3);

        m_DeviceResources->SetSwapChainRotation(m_swapChain.Get());
    }

    virtual void CreateRenderers()override
    {
        if (!m_DeviceResources)
            return;

        const auto& SCDesc = m_pSwapChain->GetDesc();
        m_pImGui.reset(new ImGuiImplUWP(m_pDevice, SCDesc.ColorBufferFormat, SCDesc.DepthBufferFormat, SCDesc.Width, SCDesc.Height));

        InitializeSample();

        m_SampleInitialized = true;
    }

private:
    ImguiUWPEventHelper^ m_ImguiEventHandler;
    InputControllerEventHandlerUWP^ m_InputControllerEventHandlerUWP;

    Microsoft::WRL::ComPtr<IDXGISwapChain3>	m_swapChain;
    bool m_SampleInitialized = false;
};

NativeAppBase* CreateApplication()
{
    return new SampleAppUWP;
}

}
<|endoftext|>


<commit_before>/*
 * GStreamer
 * Copyright (C) 2009 Julien Isorce <julien.isorce@gmail.com>
 * Copyright (C) 2009 Andrey Nechypurenko <andreynech@gmail.com>
 * Copyright (C) 2010 Nuno Santos <nunosantos@imaginando.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include <QtGui>
#include "gstthread.h"
#include "qglrenderer.h"
#include "pipeline.h"

#if defined(Q_WS_MAC)
extern void *qt_current_nsopengl_context();
#endif

/**
 * GluPerspective is part of the GLU library, and not supported as of newer (3.x?)
 * versions of OpenGL. An easy way to update the example is to write your own
 * replacement, something like this:
 *
 * See http://stackoverflow.com/questions/9210118/qts-opengl-samples-complain-about-some-errors-and-wont-run
 */
void gluPerspective(double fovy,double aspect, double zNear, double zFar)
{
     // Start in projection mode.
     glMatrixMode(GL_PROJECTION);
     glLoadIdentity();
     double xmin, xmax, ymin, ymax;
     ymax = zNear * tan(fovy * M_PI / 360.0);
     ymin = -ymax;
     xmin = ymin * aspect;
     xmax = ymax * aspect;
     glFrustum(xmin, xmax, ymin, ymax, zNear, zFar);
}

QGLRenderer::QGLRenderer(const QString &videoLocation,
                         QWidget *parent)
  : QGLWidget(parent),
    videoLoc(videoLocation),
    gst_thread(NULL),
    closing(false),
    frame(NULL)
{
    move(20, 10);
    resize(640, 480);
}

QGLRenderer::~QGLRenderer()
{
}

void
QGLRenderer::initializeGL()
{
    GLContextID ctx;

#if defined(Q_WS_WIN)
    ctx.contextId = wglGetCurrentContext();
    ctx.dc = wglGetCurrentDC();
#elif defined (Q_WS_MAC)
    ctx.contextId = (NSOpenGLContext*) qt_current_nsopengl_context();
#elif defined(Q_WS_X11)
    ctx.contextId = glXGetCurrentContext();
    const char *display_name = getenv("DISPLAY");
    if(display_name == NULL)
    {
        // actually we should look for --display command line parameter here
        display_name = ":0.0";
    }
    ctx.display = XOpenDisplay(display_name);
    ctx.wnd = this->winId();
#endif

    // We need to unset Qt context before initializing gst-gl plugin.
    // Otherwise the attempt to share gst-gl context with Qt will fail.
    this->doneCurrent();
    this->gst_thread =
      new GstThread(ctx, this->videoLoc, SLOT(newFrame()), this);
    this->makeCurrent();

    QObject::connect(this->gst_thread, SIGNAL(finished()),
                   this, SLOT(close()));
    QObject::connect(this, SIGNAL(closeRequested()),
                   this->gst_thread, SLOT(stop()), Qt::QueuedConnection);

    qglClearColor(QApplication::palette().color(QPalette::Active,
                                                QPalette::Window));
    //glShadeModel(GL_FLAT);
    //glEnable(GL_DEPTH_TEST);
    //glEnable(GL_CULL_FACE);
    glEnable(GL_TEXTURE_RECTANGLE_ARB); // Enable Texture Mapping

    this->gst_thread->start();
}

void
QGLRenderer::resizeGL(int width, int height)
{
  // Reset The Current Viewport And Perspective Transformation
  glViewport(0, 0, width, height);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();

  gluPerspective(45.0f, (GLfloat)width/(GLfloat)height, 0.1f, 100.0f);
  glMatrixMode(GL_MODELVIEW);
}

void
QGLRenderer::newFrame()
{
    Pipeline *pipeline = this->gst_thread->getPipeline();
    if(!pipeline)
      return;

    /* frame is initialized as null */
    if (this->frame)
        pipeline->queue_output_buf.put(this->frame);

    this->frame = pipeline->queue_input_buf.get();

    /* direct call to paintGL (no queued) */
    this->updateGL();
}

void
QGLRenderer::paintGL()
{
    static GLfloat	xrot = 0;
    static GLfloat	yrot = 0;
    static GLfloat	zrot = 0;

    if (this->frame)
    {

        GLfloat width = this->frame->width;
        GLfloat height = this->frame->height;

        glEnable(GL_DEPTH_TEST);

        glEnable(GL_TEXTURE_RECTANGLE_ARB);
        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, this->frame->texture);
        if(glGetError () != GL_NO_ERROR)
        {
          qDebug ("failed to bind texture that comes from gst-gl");
          emit closeRequested();
          return;
        }

        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_S,
                      GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_T,
                      GL_CLAMP_TO_EDGE);
        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        glTranslatef(0.0f,0.0f,-5.0f);

        glRotatef(xrot,1.0f,0.0f,0.0f);
        glRotatef(yrot,0.0f,1.0f,0.0f);
        glRotatef(zrot,0.0f,0.0f,1.0f);

        glBegin(GL_QUADS);
            // Front Face
            glTexCoord2f(width, 0.0f); glVertex3f(-1.0f, -1.0f,  1.0f);
            glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f,  1.0f);
            glTexCoord2f(0.0f, height); glVertex3f( 1.0f,  1.0f,  1.0f);
            glTexCoord2f(width, height); glVertex3f(-1.0f,  1.0f,  1.0f);
            // Back Face
            glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
            glTexCoord2f(0.0f, height); glVertex3f(-1.0f,  1.0f, -1.0f);
            glTexCoord2f(width, height); glVertex3f( 1.0f,  1.0f, -1.0f);
            glTexCoord2f(width, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
            // Top Face
            glTexCoord2f(width, height); glVertex3f(-1.0f,  1.0f, -1.0f);
            glTexCoord2f(width, 0.0f); glVertex3f(-1.0f,  1.0f,  1.0f);
            glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f,  1.0f,  1.0f);
            glTexCoord2f(0.0f, height); glVertex3f( 1.0f,  1.0f, -1.0f);
            // Bottom Face
            glTexCoord2f(width, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
            glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
            glTexCoord2f(0.0f, height); glVertex3f( 1.0f, -1.0f,  1.0f);
            glTexCoord2f(width,height); glVertex3f(-1.0f, -1.0f,  1.0f);
            // Right face
            glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
            glTexCoord2f(0.0f, height); glVertex3f( 1.0f,  1.0f, -1.0f);
            glTexCoord2f(width, height); glVertex3f( 1.0f,  1.0f,  1.0f);
            glTexCoord2f(width, 0.0f); glVertex3f( 1.0f, -1.0f,  1.0f);
            // Left Face
            glTexCoord2f(width, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
            glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f,  1.0f);
            glTexCoord2f(0.0f, height); glVertex3f(-1.0f,  1.0f,  1.0f);
            glTexCoord2f(width, height); glVertex3f(-1.0f,  1.0f, -1.0f);
        glEnd();

        xrot+=0.3f;
        yrot+=0.2f;
        zrot+=0.4f;

        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
    }
}

void
QGLRenderer::closeEvent(QCloseEvent* event)
{
    if(this->closing == false)
    {
        this->closing = true;
        emit closeRequested();
        event->ignore();
    }
}
<commit_msg>qglwtextureshare example: disable setting display<commit_after>/*
 * GStreamer
 * Copyright (C) 2009 Julien Isorce <julien.isorce@gmail.com>
 * Copyright (C) 2009 Andrey Nechypurenko <andreynech@gmail.com>
 * Copyright (C) 2010 Nuno Santos <nunosantos@imaginando.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include <QtGui>
#include "gstthread.h"
#include "qglrenderer.h"
#include "pipeline.h"

#if defined(Q_WS_MAC)
extern void *qt_current_nsopengl_context();
#endif

/**
 * GluPerspective is part of the GLU library, and not supported as of newer (3.x?)
 * versions of OpenGL. An easy way to update the example is to write your own
 * replacement, something like this:
 *
 * See http://stackoverflow.com/questions/9210118/qts-opengl-samples-complain-about-some-errors-and-wont-run
 */
void gluPerspective(double fovy,double aspect, double zNear, double zFar)
{
     // Start in projection mode.
     glMatrixMode(GL_PROJECTION);
     glLoadIdentity();
     double xmin, xmax, ymin, ymax;
     ymax = zNear * tan(fovy * M_PI / 360.0);
     ymin = -ymax;
     xmin = ymin * aspect;
     xmax = ymax * aspect;
     glFrustum(xmin, xmax, ymin, ymax, zNear, zFar);
}

QGLRenderer::QGLRenderer(const QString &videoLocation,
                         QWidget *parent)
  : QGLWidget(parent),
    videoLoc(videoLocation),
    gst_thread(NULL),
    closing(false),
    frame(NULL)
{
    move(20, 10);
    resize(640, 480);
}

QGLRenderer::~QGLRenderer()
{
}

void
QGLRenderer::initializeGL()
{
    GLContextID ctx;

#if defined(Q_WS_WIN)
    ctx.contextId = wglGetCurrentContext();
    ctx.dc = wglGetCurrentDC();
#elif defined (Q_WS_MAC)
    ctx.contextId = (NSOpenGLContext*) qt_current_nsopengl_context();
#elif defined(Q_WS_X11)
// XXX: aalex disabled this:
//     ctx.contextId = glXGetCurrentContext();
//     const char *display_name = getenv("DISPLAY");
//     if(display_name == NULL)
//     {
//         // actually we should look for --display command line parameter here
//         display_name = ":0.0";
//     }
//     ctx.display = XOpenDisplay(display_name);
//     ctx.wnd = this->winId();
#endif

    // We need to unset Qt context before initializing gst-gl plugin.
    // Otherwise the attempt to share gst-gl context with Qt will fail.
    this->doneCurrent();
    this->gst_thread =
      new GstThread(ctx, this->videoLoc, SLOT(newFrame()), this);
    this->makeCurrent();

    QObject::connect(this->gst_thread, SIGNAL(finished()),
                   this, SLOT(close()));
    QObject::connect(this, SIGNAL(closeRequested()),
                   this->gst_thread, SLOT(stop()), Qt::QueuedConnection);

    qglClearColor(QApplication::palette().color(QPalette::Active,
                                                QPalette::Window));
    //glShadeModel(GL_FLAT);
    //glEnable(GL_DEPTH_TEST);
    //glEnable(GL_CULL_FACE);
    glEnable(GL_TEXTURE_RECTANGLE_ARB); // Enable Texture Mapping

    this->gst_thread->start();
}

void
QGLRenderer::resizeGL(int width, int height)
{
  // Reset The Current Viewport And Perspective Transformation
  glViewport(0, 0, width, height);

  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();

  gluPerspective(45.0f, (GLfloat)width/(GLfloat)height, 0.1f, 100.0f);
  glMatrixMode(GL_MODELVIEW);
}

void
QGLRenderer::newFrame()
{
    Pipeline *pipeline = this->gst_thread->getPipeline();
    if(!pipeline)
      return;

    /* frame is initialized as null */
    if (this->frame)
        pipeline->queue_output_buf.put(this->frame);

    this->frame = pipeline->queue_input_buf.get();

    /* direct call to paintGL (no queued) */
    this->updateGL();
}

void
QGLRenderer::paintGL()
{
    static GLfloat	xrot = 0;
    static GLfloat	yrot = 0;
    static GLfloat	zrot = 0;

    if (this->frame)
    {

        GLfloat width = this->frame->width;
        GLfloat height = this->frame->height;

        glEnable(GL_DEPTH_TEST);

        glEnable(GL_TEXTURE_RECTANGLE_ARB);
        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, this->frame->texture);
        if(glGetError () != GL_NO_ERROR)
        {
          qDebug ("failed to bind texture that comes from gst-gl");
          emit closeRequested();
          return;
        }

        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_S,
                      GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_WRAP_T,
                      GL_CLAMP_TO_EDGE);
        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        glTranslatef(0.0f,0.0f,-5.0f);

        glRotatef(xrot,1.0f,0.0f,0.0f);
        glRotatef(yrot,0.0f,1.0f,0.0f);
        glRotatef(zrot,0.0f,0.0f,1.0f);

        glBegin(GL_QUADS);
            // Front Face
            glTexCoord2f(width, 0.0f); glVertex3f(-1.0f, -1.0f,  1.0f);
            glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f,  1.0f);
            glTexCoord2f(0.0f, height); glVertex3f( 1.0f,  1.0f,  1.0f);
            glTexCoord2f(width, height); glVertex3f(-1.0f,  1.0f,  1.0f);
            // Back Face
            glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
            glTexCoord2f(0.0f, height); glVertex3f(-1.0f,  1.0f, -1.0f);
            glTexCoord2f(width, height); glVertex3f( 1.0f,  1.0f, -1.0f);
            glTexCoord2f(width, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
            // Top Face
            glTexCoord2f(width, height); glVertex3f(-1.0f,  1.0f, -1.0f);
            glTexCoord2f(width, 0.0f); glVertex3f(-1.0f,  1.0f,  1.0f);
            glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f,  1.0f,  1.0f);
            glTexCoord2f(0.0f, height); glVertex3f( 1.0f,  1.0f, -1.0f);
            // Bottom Face
            glTexCoord2f(width, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
            glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
            glTexCoord2f(0.0f, height); glVertex3f( 1.0f, -1.0f,  1.0f);
            glTexCoord2f(width,height); glVertex3f(-1.0f, -1.0f,  1.0f);
            // Right face
            glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
            glTexCoord2f(0.0f, height); glVertex3f( 1.0f,  1.0f, -1.0f);
            glTexCoord2f(width, height); glVertex3f( 1.0f,  1.0f,  1.0f);
            glTexCoord2f(width, 0.0f); glVertex3f( 1.0f, -1.0f,  1.0f);
            // Left Face
            glTexCoord2f(width, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
            glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f,  1.0f);
            glTexCoord2f(0.0f, height); glVertex3f(-1.0f,  1.0f,  1.0f);
            glTexCoord2f(width, height); glVertex3f(-1.0f,  1.0f, -1.0f);
        glEnd();

        xrot+=0.3f;
        yrot+=0.2f;
        zrot+=0.4f;

        glBindTexture(GL_TEXTURE_RECTANGLE_ARB, 0);
    }
}

void
QGLRenderer::closeEvent(QCloseEvent* event)
{
    if(this->closing == false)
    {
        this->closing = true;
        emit closeRequested();
        event->ignore();
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _XMLOFF_XMLCNITM_HXX
#define _XMLOFF_XMLCNITM_HXX

#include <svl/poolitem.hxx>

class SvXMLNamespaceMap;
namespace rtl { class OUString; }

//============================================================================

class SvXMLAttrContainerItem_Impl;

class SvXMLAttrContainerItem: public SfxPoolItem
{
    SvXMLAttrContainerItem_Impl *pImpl;

public:
    TYPEINFO();

    SvXMLAttrContainerItem( sal_uInt16 nWhich = 0 );
    SvXMLAttrContainerItem( const SvXMLAttrContainerItem& );
    virtual ~SvXMLAttrContainerItem();

    virtual int operator==( const SfxPoolItem& ) const;
    using SfxPoolItem::Compare;
    virtual int Compare( const SfxPoolItem &rWith ) const;

    virtual SfxItemPresentation GetPresentation(
                                SfxItemPresentation ePresentation,
                                SfxMapUnit eCoreMetric,
                                SfxMapUnit ePresentationMetric,
                                XubString &rText,
                                const IntlWrapper *pIntlWrapper = 0 ) const;

    virtual sal_uInt16 GetVersion( sal_uInt16 nFileFormatVersion ) const;

    virtual sal_Bool             QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 ) const;
    virtual sal_Bool             PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId = 0 );

    virtual SfxPoolItem *Clone( SfxItemPool * = 0) const
    { return new SvXMLAttrContainerItem( *this ); }

    sal_Bool AddAttr( const ::rtl::OUString& rLName,
                          const ::rtl::OUString& rValue );
    sal_Bool AddAttr( const ::rtl::OUString& rPrefix,
                          const ::rtl::OUString& rNamespace,
                          const ::rtl::OUString& rLName,
                          const ::rtl::OUString& rValue );

    sal_uInt16 GetAttrCount() const;
    ::rtl::OUString GetAttrNamespace( sal_uInt16 i ) const;
    ::rtl::OUString GetAttrPrefix( sal_uInt16 i ) const;
    const ::rtl::OUString& GetAttrLName( sal_uInt16 i ) const;
    const ::rtl::OUString& GetAttrValue( sal_uInt16 i ) const;

    sal_uInt16 GetFirstNamespaceIndex() const;
    sal_uInt16 GetNextNamespaceIndex( sal_uInt16 nIdx ) const;
    const ::rtl::OUString& GetNamespace( sal_uInt16 i ) const;
    const ::rtl::OUString& GetPrefix( sal_uInt16 i ) const;
};

#endif //  _XMLOFF_XMLCNITM_HXX

<commit_msg>removetooltypes01: #i112600# Merge changes<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _XMLOFF_XMLCNITM_HXX
#define _XMLOFF_XMLCNITM_HXX

#include <svl/poolitem.hxx>

class SvXMLNamespaceMap;
namespace rtl { class OUString; }

//============================================================================

class SvXMLAttrContainerItem_Impl;

class SvXMLAttrContainerItem: public SfxPoolItem
{
    SvXMLAttrContainerItem_Impl *pImpl;

public:
    TYPEINFO();

    SvXMLAttrContainerItem( sal_uInt16 nWhich = 0 );
    SvXMLAttrContainerItem( const SvXMLAttrContainerItem& );
    virtual ~SvXMLAttrContainerItem();

    virtual int operator==( const SfxPoolItem& ) const;
    using SfxPoolItem::Compare;
    virtual int Compare( const SfxPoolItem &rWith ) const;

    virtual SfxItemPresentation GetPresentation(
                                SfxItemPresentation ePresentation,
                                SfxMapUnit eCoreMetric,
                                SfxMapUnit ePresentationMetric,
                                XubString &rText,
                                const IntlWrapper *pIntlWrapper = 0 ) const;

    virtual sal_uInt16 GetVersion( sal_uInt16 nFileFormatVersion ) const;

    virtual sal_Bool             QueryValue( com::sun::star::uno::Any& rVal, sal_uInt8 nMemberId = 0 ) const;
    virtual sal_Bool             PutValue( const com::sun::star::uno::Any& rVal, sal_uInt8 nMemberId = 0 );

    virtual SfxPoolItem *Clone( SfxItemPool * = 0) const
    { return new SvXMLAttrContainerItem( *this ); }

    sal_Bool AddAttr( const ::rtl::OUString& rLName,
                          const ::rtl::OUString& rValue );
    sal_Bool AddAttr( const ::rtl::OUString& rPrefix,
                          const ::rtl::OUString& rNamespace,
                          const ::rtl::OUString& rLName,
                          const ::rtl::OUString& rValue );

    sal_uInt16 GetAttrCount() const;
    ::rtl::OUString GetAttrNamespace( sal_uInt16 i ) const;
    ::rtl::OUString GetAttrPrefix( sal_uInt16 i ) const;
    const ::rtl::OUString& GetAttrLName( sal_uInt16 i ) const;
    const ::rtl::OUString& GetAttrValue( sal_uInt16 i ) const;

    sal_uInt16 GetFirstNamespaceIndex() const;
    sal_uInt16 GetNextNamespaceIndex( sal_uInt16 nIdx ) const;
    const ::rtl::OUString& GetNamespace( sal_uInt16 i ) const;
    const ::rtl::OUString& GetPrefix( sal_uInt16 i ) const;
};

#endif //  _XMLOFF_XMLCNITM_HXX

<|endoftext|>


<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "assert.h"

#include "chainparams.h"
#include "main.h"
#include "util.h"

#include <boost/assign/list_of.hpp>

using namespace boost::assign;

struct SeedSpec6 {
    uint8_t addr[16];
    uint16_t port;
};

#include "chainparamsseeds.h"

//
// Main network
//

// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
    // It'll only connect to one or two seed nodes because once it connects,
    // it'll get a pile of addresses with newer timestamps.
    // Seed nodes are given a random 'last seen time' of between one and two
    // weeks ago.
    const int64_t nOneWeek = 7*24*60*60;
    for (unsigned int i = 0; i < count; i++)
    {
        struct in6_addr ip;
        memcpy(&ip, data[i].addr, sizeof(ip));
        CAddress addr(CService(ip, data[i].port));
        addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
        vSeedsOut.push_back(addr);
    }
}

class CMainParams : public CChainParams {
public:
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
        // a large 4-byte int at any alignment.
        pchMessageStart[0] = 0xde;
        pchMessageStart[1] = 0x63;
        pchMessageStart[2] = 0x19;
        pchMessageStart[3] = 0x68;
        nDefaultPort = 8881;
        nRPCPort = 8882;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.
        //
        //CBlock(hash=000001faef25dec4fbcf906e6242621df2c183bf232f263d0ba5b101911e4563, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=12630d16a97f24b287c8c2594dda5fb98c9e6c70fc61d44191931ea2aa08dc90, nTime=1393221600, nBits=1e0fffff, nNonce=164482, vtx=1, vchBlockSig=)
        //  Coinbase(hash=12630d16a9, nTime=1393221600, ver=1, vin.size=1, vout.size=1, nLockTime=0)
        //    CTxIn(COutPoint(0000000000, 4294967295), coinbase 00012a24323020466562203230313420426974636f696e2041544d7320636f6d6520746f20555341)
        //    CTxOut(empty)
        //  vMerkleTree: 12630d16a9
        const char* pszTimestamp = "http://www.coindesk.com/central-bank-africa-warning-oc/";
        std::vector<CTxIn> vin;
        vin.resize(1);
        vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        std::vector<CTxOut> vout;
        vout.resize(1);
        vout[0].SetEmpty();
        CTransaction txNew(1, 1488326400, vin, vout, 0);
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1488326400;
        genesis.nBits    = bnProofOfWorkLimit.GetCompact();
        genesis.nNonce   = 1493173;
        hashGenesisBlock = genesis.GetHash();
        assert(hashGenesisBlock == uint256("0x00000068ea1bda5d79b59679d475024f8bc3344a5571a2c00bed231c7495fae6"));
        assert(genesis.hashMerkleRoot == uint256("0x77ddb788074e852f05e6df55d8cbe2fdfa943905b6b83e47e4b8698ba7300b27"));

        // Add seednodes below //
        //  vSeeds.push_back(CDNSSeedData("yourdomain.com",  "seednode1.yourdomain.com"));
        //  vSeeds.push_back(CDNSSeedData("yourdomain.com",  "seednode2.yourdomain.com"));
        //  vSeeds.push_back(CDNSSeedData("yourdomain.com",  "seednode3.yourdomain.com"));
        //  vSeeds.push_back(CDNSSeedData("yourdomain.com",  "seednode4.yourdomain.com"));

        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,0);
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,5);
        base58Prefixes[SECRET_KEY] =     std::vector<unsigned char>(1,128);
        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >();
        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >();

        convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));

    }

    virtual const CBlock& GenesisBlock() const { return genesis; }
    virtual Network NetworkID() const { return CChainParams::MAIN; }

    virtual const vector<CAddress>& FixedSeeds() const {
        return vFixedSeeds;
    }
protected:
    CBlock genesis;
    vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;

//
// Testnet
//

class CTestNetParams : public CMainParams {
public:
    CTestNetParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
        // a large 4-byte int at any alignment.
        pchMessageStart[0] = 0xec;
        pchMessageStart[1] = 0xe6;
        pchMessageStart[2] = 0x7e;
        pchMessageStart[3] = 0x19;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
        nDefaultPort = 18881;
        nRPCPort = 18882;
        strDataDir = "testnet";

        // Modify the testnet genesis block so the timestamp is valid for a later start.
        genesis.nBits  = bnProofOfWorkLimit.GetCompact();
        genesis.nNonce = 52927;
        genesis.nTime    = 1487718210;
        hashGenesisBlock = genesis.GetHash();
        assert(hashGenesisBlock == uint256("0x0000b4d12c8764bbcad6ab4c55d935cba73f4b48796bee054ca9a76a4c79d83a"));

        vFixedSeeds.clear();
        vSeeds.clear();

        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 111);
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 196);
        base58Prefixes[SECRET_KEY]     = std::vector<unsigned char>(1, 239);
        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();

        convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));

    }
    virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;

//
// Regression test
//
class CRegTestParams : public CTestNetParams {
public:
    CRegTestParams() {
        pchMessageStart[0] = 0xcc;
        pchMessageStart[1] = 0xb5;
        pchMessageStart[2] = 0xe2;
        pchMessageStart[3] = 0xd6;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);
        genesis.nTime = 1411111111;
        genesis.nBits  = bnProofOfWorkLimit.GetCompact();
        genesis.nNonce = 8;
        hashGenesisBlock = genesis.GetHash();
        nDefaultPort = 28881;
        strDataDir = "regtest";
        assert(hashGenesisBlock == uint256("0x4f5c235cc8abab84b409ed3175fe4a3d2b229197f855101c9f2245c6a7d055f8"));

        vSeeds.clear();  // Regtest mode doesn't have any DNS seeds.
    }

    virtual bool RequireRPCPassword() const { return false; }
    virtual Network NetworkID() const { return CChainParams::REGTEST; }
};
static CRegTestParams regTestParams;

static CChainParams *pCurrentParams = &mainParams;

const CChainParams &Params() {
    return *pCurrentParams;
}

void SelectParams(CChainParams::Network network) {
    switch (network) {
        case CChainParams::MAIN:
            pCurrentParams = &mainParams;
            break;
        case CChainParams::TESTNET:
            pCurrentParams = &testNetParams;
            break;
        case CChainParams::REGTEST:
            pCurrentParams = &regTestParams;
            break;
        default:
            assert(false && "Unimplemented network");
            return;
    }
}

bool SelectParamsFromCommandLine() {
    bool fRegTest = GetBoolArg("-regtest", false);
    bool fTestNet = GetBoolArg("-testnet", false);

    if (fTestNet && fRegTest) {
        return false;
    }

    if (fRegTest) {
        SelectParams(CChainParams::REGTEST);
    } else if (fTestNet) {
        SelectParams(CChainParams::TESTNET);
    } else {
        SelectParams(CChainParams::MAIN);
    }
    return true;
}
<commit_msg>Update chainparams.cpp<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "assert.h"

#include "chainparams.h"
#include "main.h"
#include "util.h"

#include <boost/assign/list_of.hpp>

using namespace boost::assign;

struct SeedSpec6 {
    uint8_t addr[16];
    uint16_t port;
};

#include "chainparamsseeds.h"

//
// Main network
//

// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
    // It'll only connect to one or two seed nodes because once it connects,
    // it'll get a pile of addresses with newer timestamps.
    // Seed nodes are given a random 'last seen time' of between one and two
    // weeks ago.
    const int64_t nOneWeek = 7*24*60*60;
    for (unsigned int i = 0; i < count; i++)
    {
        struct in6_addr ip;
        memcpy(&ip, data[i].addr, sizeof(ip));
        CAddress addr(CService(ip, data[i].port));
        addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
        vSeedsOut.push_back(addr);
    }
}

class CMainParams : public CChainParams {
public:
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
        // a large 4-byte int at any alignment.
        pchMessageStart[0] = 0xde;
        pchMessageStart[1] = 0x63;
        pchMessageStart[2] = 0x19;
        pchMessageStart[3] = 0x68;
        nDefaultPort = 8881;
        nRPCPort = 8882;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.
        //
        //CBlock(hash=000001faef25dec4fbcf906e6242621df2c183bf232f263d0ba5b101911e4563, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=12630d16a97f24b287c8c2594dda5fb98c9e6c70fc61d44191931ea2aa08dc90, nTime=1393221600, nBits=1e0fffff, nNonce=164482, vtx=1, vchBlockSig=)
        //  Coinbase(hash=12630d16a9, nTime=1393221600, ver=1, vin.size=1, vout.size=1, nLockTime=0)
        //    CTxIn(COutPoint(0000000000, 4294967295), coinbase 00012a24323020466562203230313420426974636f696e2041544d7320636f6d6520746f20555341)
        //    CTxOut(empty)
        //  vMerkleTree: 12630d16a9
        const char* pszTimestamp = "http://www.coindesk.com/central-bank-africa-warning-onecoin/";
        std::vector<CTxIn> vin;
        vin.resize(1);
        vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        std::vector<CTxOut> vout;
        vout.resize(1);
        vout[0].SetEmpty();
        CTransaction txNew(1, 1488326400, vin, vout, 0);
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1488326400;
        genesis.nBits    = bnProofOfWorkLimit.GetCompact();
        genesis.nNonce   = 1493173;
        hashGenesisBlock = genesis.GetHash();
        assert(hashGenesisBlock == uint256("0x00000068ea1bda5d79b59679d475024f8bc3344a5571a2c00bed231c7495fae6"));
        assert(genesis.hashMerkleRoot == uint256("0x77ddb788074e852f05e6df55d8cbe2fdfa943905b6b83e47e4b8698ba7300b27"));

        // Add seednodes below //
        //  vSeeds.push_back(CDNSSeedData("yourdomain.com",  "seednode1.yourdomain.com"));
        //  vSeeds.push_back(CDNSSeedData("yourdomain.com",  "seednode2.yourdomain.com"));
        //  vSeeds.push_back(CDNSSeedData("yourdomain.com",  "seednode3.yourdomain.com"));
        //  vSeeds.push_back(CDNSSeedData("yourdomain.com",  "seednode4.yourdomain.com"));

        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,0);
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,5);
        base58Prefixes[SECRET_KEY] =     std::vector<unsigned char>(1,128);
        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >();
        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >();

        convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));

    }

    virtual const CBlock& GenesisBlock() const { return genesis; }
    virtual Network NetworkID() const { return CChainParams::MAIN; }

    virtual const vector<CAddress>& FixedSeeds() const {
        return vFixedSeeds;
    }
protected:
    CBlock genesis;
    vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;

//
// Testnet
//

class CTestNetParams : public CMainParams {
public:
    CTestNetParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        // The characters are rarely used upper ASCII, not valid as UTF-8, and produce
        // a large 4-byte int at any alignment.
        pchMessageStart[0] = 0xec;
        pchMessageStart[1] = 0xe6;
        pchMessageStart[2] = 0x7e;
        pchMessageStart[3] = 0x19;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);
        nDefaultPort = 18881;
        nRPCPort = 18882;
        strDataDir = "testnet";

        // Modify the testnet genesis block so the timestamp is valid for a later start.
        genesis.nBits  = bnProofOfWorkLimit.GetCompact();
        genesis.nNonce = 52927;
        genesis.nTime    = 1487718210;
        hashGenesisBlock = genesis.GetHash();
        assert(hashGenesisBlock == uint256("0x0000b4d12c8764bbcad6ab4c55d935cba73f4b48796bee054ca9a76a4c79d83a"));

        vFixedSeeds.clear();
        vSeeds.clear();

        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 111);
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 196);
        base58Prefixes[SECRET_KEY]     = std::vector<unsigned char>(1, 239);
        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();

        convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));

    }
    virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;

//
// Regression test
//
class CRegTestParams : public CTestNetParams {
public:
    CRegTestParams() {
        pchMessageStart[0] = 0xcc;
        pchMessageStart[1] = 0xb5;
        pchMessageStart[2] = 0xe2;
        pchMessageStart[3] = 0xd6;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);
        genesis.nTime = 1411111111;
        genesis.nBits  = bnProofOfWorkLimit.GetCompact();
        genesis.nNonce = 8;
        hashGenesisBlock = genesis.GetHash();
        nDefaultPort = 28881;
        strDataDir = "regtest";
        assert(hashGenesisBlock == uint256("0x4f5c235cc8abab84b409ed3175fe4a3d2b229197f855101c9f2245c6a7d055f8"));

        vSeeds.clear();  // Regtest mode doesn't have any DNS seeds.
    }

    virtual bool RequireRPCPassword() const { return false; }
    virtual Network NetworkID() const { return CChainParams::REGTEST; }
};
static CRegTestParams regTestParams;

static CChainParams *pCurrentParams = &mainParams;

const CChainParams &Params() {
    return *pCurrentParams;
}

void SelectParams(CChainParams::Network network) {
    switch (network) {
        case CChainParams::MAIN:
            pCurrentParams = &mainParams;
            break;
        case CChainParams::TESTNET:
            pCurrentParams = &testNetParams;
            break;
        case CChainParams::REGTEST:
            pCurrentParams = &regTestParams;
            break;
        default:
            assert(false && "Unimplemented network");
            return;
    }
}

bool SelectParamsFromCommandLine() {
    bool fRegTest = GetBoolArg("-regtest", false);
    bool fTestNet = GetBoolArg("-testnet", false);

    if (fTestNet && fRegTest) {
        return false;
    }

    if (fRegTest) {
        SelectParams(CChainParams::REGTEST);
    } else if (fTestNet) {
        SelectParams(CChainParams::TESTNET);
    } else {
        SelectParams(CChainParams::MAIN);
    }
    return true;
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2016 The Auroracoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chainparams.h"

#include "assert.h"
#include "core.h"
#include "protocol.h"
#include "util.h"
#include "scrypt.h"

#include <boost/assign/list_of.hpp>

using namespace boost::assign;

//
// Main network
//

unsigned int pnSeed[] =
{
    0xA2F39055, 0x5EF2E56F, 0x57D54ADA, 0x50F812B0, 0x256187D5, 0x9FCBD468, 0x92B9AB35, 0x8AC586B4
};

class CMainParams : public CChainParams {
public:
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        pchMessageStart[0] = 0xfb;
        pchMessageStart[1] = 0xc0;
        pchMessageStart[2] = 0xb6;
        pchMessageStart[3] = 0xdb;
        vAlertPubKey = ParseHex("04d1832d7d0c59634d67d3023379403014c2878d0c2372d175219063a48fa06e6d429e09f36d3196ec544c2cfdd12d6fe510a399595f75ebb6da238eb5f70f2072");
        nDefaultPort = 11337;
        nRPCPort = 14242;

        bnProofOfWorkLimit[ALGO_SHA256D] = CBigNum(~uint256(0) >> 20); // 1.00000000
        bnProofOfWorkLimit[ALGO_SCRYPT]  = CBigNum(~uint256(0) >> 20);
        bnProofOfWorkLimit[ALGO_GROESTL] = CBigNum(~uint256(0) >> 20); // 0.00195311
        bnProofOfWorkLimit[ALGO_SKEIN]   = CBigNum(~uint256(0) >> 20); // 0.00195311
        bnProofOfWorkLimit[ALGO_QUBIT]   = CBigNum(~uint256(0) >> 20); // 0.00097655

        // Build the genesis block.
        const char* pszTimestamp = "NY Times 18/Aug/2014 Bitcoin's Price Falls 12%, to Lowest Value Since May";
        CTransaction txNew;
        txNew.vin.resize(1);
        txNew.vout.resize(1);
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        txNew.vout[0].nValue = 10000 * COIN;
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG;
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1408974288;
        genesis.nBits    = Params().ProofOfWorkLimit(ALGO_SCRYPT).GetCompact();
        //genesis.nBits = 0x1e0fffff;
        genesis.nNonce   = 386703170;

        hashGenesisBlock = genesis.GetHash();

        assert(hashGenesisBlock == uint256("0x660f734cf6c6d16111bde201bbd2122873f2f2c078b969779b9d4c99732354fd"));
        assert(genesis.hashMerkleRoot == uint256("0xe9441ec39c399c76ea734ea31827e1895a82c5a1f9b2c6252b5dacada768ec8b"));

        //vSeeds.push_back(CDNSSeedData("luxembourgh", "s1.smlyoraseed.net"));
        //vSeeds.push_back(CDNSSeedData("united-states-west", "smlyseed1.criptoe.com"));
        //vSeeds.push_back(CDNSSeedData("united-states-east", "s1.smlyoraseed.com"));
        //vSeeds.push_back(CDNSSeedData("iceland", "s1.smlyoraseed.org"));
        //vSeeds.push_back(CDNSSeedData("the-netherlands", "s1.smlyoraseed.eu"));
        //vSeeds.push_back(CDNSSeedData("electrum2", "electrum2.smlyorcoin.is"));
        //vSeeds.push_back(CDNSSeedData("electrum3", "electrum3.smileycoin.is"));
        //vSeeds.push_back(CDNSSeedData("electrum4", "electrum4.smileycoin.is"));

        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,23);
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,5);
        base58Prefixes[SECRET_KEY]     = std::vector<unsigned char>(1,176);
        base58Prefixes[SECRET_KEY_OLD] = std::vector<unsigned char>(1,151);
        base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >();
        base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >();
        // Convert the pnSeeds array into usable address objects.
        for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
        {
            const int64_t nOneWeek = 7*24*60*60;
            struct in_addr ip;
            memcpy(&ip, &pnSeed[i], sizeof(ip));
            CAddress addr(CService(ip, GetDefaultPort()));
            addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
            vFixedSeeds.push_back(addr);
        }
    }

    virtual const CBlock& GenesisBlock() const { return genesis; }
    virtual Network NetworkID() const { return CChainParams::MAIN; }

    virtual const vector<CAddress>& FixedSeeds() const {
        return vFixedSeeds;
    }
protected:
    CBlock genesis;
    vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;

static CChainParams *pCurrentParams = &mainParams;

const CChainParams &Params() {
    return *pCurrentParams;
}

void SelectParams(CChainParams::Network network) {
    switch (network) {
        case CChainParams::MAIN:
            pCurrentParams = &mainParams;
            break;
        default:
            assert(false && "Unimplemented network");
            return;
    }
}

bool SelectParamsFromCommandLine() {

    SelectParams(CChainParams::MAIN);
    return true;
}
<commit_msg>Changed some parameters<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2016 The Auroracoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chainparams.h"

#include "assert.h"
#include "core.h"
#include "protocol.h"
#include "util.h"
#include "scrypt.h"

#include <boost/assign/list_of.hpp>

using namespace boost::assign;

//
// Main network
//

unsigned int pnSeed[] =
{
    0xA2F39055, 0x5EF2E56F, 0x57D54ADA, 0x50F812B0, 0x256187D5, 0x9FCBD468, 0x92B9AB35, 0x8AC586B4
};

class CMainParams : public CChainParams {
public:
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        pchMessageStart[0] = 0xfb;
        pchMessageStart[1] = 0xc0;
        pchMessageStart[2] = 0xb6;
        pchMessageStart[3] = 0xdb;
        vAlertPubKey = ParseHex("04d1832d7d0c59634d67d3023379403014c2878d0c2372d175219063a48fa06e6d429e09f36d3196ec544c2cfdd12d6fe510a399595f75ebb6da238eb5f70f2072");
        nDefaultPort = 11337;
        nRPCPort = 14242;

        bnProofOfWorkLimit[ALGO_SHA256D] = CBigNum(~uint256(0) >> 20); // 1.00000000
        bnProofOfWorkLimit[ALGO_SCRYPT]  = CBigNum(~uint256(0) >> 20);
        bnProofOfWorkLimit[ALGO_GROESTL] = CBigNum(~uint256(0) >> 20); // 0.00195311
        bnProofOfWorkLimit[ALGO_SKEIN]   = CBigNum(~uint256(0) >> 20); // 0.00195311
        bnProofOfWorkLimit[ALGO_QUBIT]   = CBigNum(~uint256(0) >> 20); // 0.00097655

        // Build the genesis block.
        const char* pszTimestamp = "NY Times 18/Aug/2014 Bitcoin's Price Falls 12%, to Lowest Value Since May";
        CTransaction txNew;
        txNew.vin.resize(1);
        txNew.vout.resize(1);
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        txNew.vout[0].nValue = 10000 * COIN;
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG;
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1408974288;
        genesis.nBits    = Params().ProofOfWorkLimit(ALGO_SCRYPT).GetCompact();
        //genesis.nBits = 0x1e0fffff;
        genesis.nNonce   = 386703170;

        hashGenesisBlock = genesis.GetHash();

        assert(hashGenesisBlock == uint256("0x660f734cf6c6d16111bde201bbd2122873f2f2c078b969779b9d4c99732354fd"));
        assert(genesis.hashMerkleRoot == uint256("0xe9441ec39c399c76ea734ea31827e1895a82c5a1f9b2c6252b5dacada768ec8b"));

        vFixedSeeds.clear();
		vSeeds.clear();
        //vSeeds.push_back(CDNSSeedData("luxembourgh", "s1.smlyoraseed.net"));
        //vSeeds.push_back(CDNSSeedData("united-states-west", "smlyseed1.criptoe.com"));
        //vSeeds.push_back(CDNSSeedData("united-states-east", "s1.smlyoraseed.com"));
        //vSeeds.push_back(CDNSSeedData("iceland", "s1.smlyoraseed.org"));
        //vSeeds.push_back(CDNSSeedData("the-netherlands", "s1.smlyoraseed.eu"));
        //vSeeds.push_back(CDNSSeedData("electrum2", "electrum2.smlyorcoin.is"));
        //vSeeds.push_back(CDNSSeedData("electrum3", "electrum3.smileycoin.is"));
        //vSeeds.push_back(CDNSSeedData("electrum4", "electrum4.smileycoin.is"));

        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,86);
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,9);
        base58Prefixes[SECRET_KEY]     = std::vector<unsigned char>(1,198);
        base58Prefixes[SECRET_KEY_OLD] = std::vector<unsigned char>(1,151);
        base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x1E)(0x56)(0x2D)(0x9A).convert_to_container<std::vector<unsigned char> >();
        base58Prefixes[EXT_SECRET_KEY] = list_of(0x1E)(0x56)(0x31)(0xBC).convert_to_container<std::vector<unsigned char> >();
        // Convert the pnSeeds array into usable address objects.
        for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
        {
            const int64_t nOneWeek = 7*24*60*60;
            struct in_addr ip;
            memcpy(&ip, &pnSeed[i], sizeof(ip));
            CAddress addr(CService(ip, GetDefaultPort()));
            addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
            vFixedSeeds.push_back(addr);
        }
    }

    virtual const CBlock& GenesisBlock() const { return genesis; }
    virtual Network NetworkID() const { return CChainParams::MAIN; }

    virtual const vector<CAddress>& FixedSeeds() const {
        return vFixedSeeds;
    }
protected:
    CBlock genesis;
    vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;

static CChainParams *pCurrentParams = &mainParams;

const CChainParams &Params() {
    return *pCurrentParams;
}

void SelectParams(CChainParams::Network network) {
    switch (network) {
        case CChainParams::MAIN:
            pCurrentParams = &mainParams;
            break;
        default:
            assert(false && "Unimplemented network");
            return;
    }
}

bool SelectParamsFromCommandLine() {

    SelectParams(CChainParams::MAIN);
    return true;
}
<|endoftext|>


<commit_before>//
// Copyright (c) 2008-2015 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include "../Precompiled.h"

#include "../Core/Context.h"
#include "../Graphics/Graphics.h"
#include "../Graphics/Shader.h"
#include "../Graphics/ShaderVariation.h"
#include "../IO/Deserializer.h"
#include "../IO/FileSystem.h"
#include "../IO/Log.h"
#include "../Resource/ResourceCache.h"

#include "../DebugNew.h"

namespace Atomic
{

void CommentOutFunction(String& code, const String& signature)
{
    unsigned startPos = code.Find(signature);
    unsigned braceLevel = 0;
    if (startPos == String::NPOS)
        return;

    code.Insert(startPos, "/*");

    for (unsigned i = startPos + 2 + signature.Length(); i < code.Length(); ++i)
    {
        if (code[i] == '{')
            ++braceLevel;
        else if (code[i] == '}')
        {
            --braceLevel;
            if (braceLevel == 0)
            {
                code.Insert(i + 1, "*/");
                return;
            }
        }
    }
}

Shader::Shader(Context* context) :
    Resource(context),
    timeStamp_(0),
    numVariations_(0)
{
    RefreshMemoryUse();
}

Shader::~Shader()
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    cache->ResetDependencies(this);
}

void Shader::RegisterObject(Context* context)
{
    context->RegisterFactory<Shader>();
}

bool Shader::BeginLoad(Deserializer& source)
{
    Graphics* graphics = GetSubsystem<Graphics>();
    if (!graphics)
        return false;

    // Load the shader source code and resolve any includes
    timeStamp_ = 0;
    String shaderCode;
    if (!ProcessSource(shaderCode, source))
        return false;

    // Comment out the unneeded shader function
    vsSourceCode_ = shaderCode;
    psSourceCode_ = shaderCode;
    CommentOutFunction(vsSourceCode_, "void PS(");
    CommentOutFunction(psSourceCode_, "void VS(");

    // OpenGL: rename either VS() or PS() to main(), comment out vertex attributes in pixel shaders
#ifdef ATOMIC_OPENGL
    vsSourceCode_.Replace("void VS(", "void main(");
    psSourceCode_.Replace("void PS(", "void main(");
    // ATOMIC BEGIN - reported shader compiler error here: https://github.com/urho3d/Urho3D/issues/870
    psSourceCode_.Replace("attribute ", "// attribute ");
    // ATOMIC END
#endif

    RefreshMemoryUse();
    return true;
}

bool Shader::EndLoad()
{
    // If variations had already been created, release them and require recompile
    for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = vsVariations_.Begin(); i != vsVariations_.End(); ++i)
        i->second_->Release();
    for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = psVariations_.Begin(); i != psVariations_.End(); ++i)
        i->second_->Release();

    return true;
}

ShaderVariation* Shader::GetVariation(ShaderType type, const String& defines)
{
    return GetVariation(type, defines.CString());
}

ShaderVariation* Shader::GetVariation(ShaderType type, const char* defines)
{
    StringHash definesHash(defines);
    HashMap<StringHash, SharedPtr<ShaderVariation> >& variations(type == VS ? vsVariations_ : psVariations_);
    HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = variations.Find(definesHash);
    if (i == variations.End())
    {
        // If shader not found, normalize the defines (to prevent duplicates) and check again. In that case make an alias
        // so that further queries are faster
        String normalizedDefines = NormalizeDefines(defines);
        StringHash normalizedHash(normalizedDefines);

        i = variations.Find(normalizedHash);
        if (i != variations.End())
            variations.Insert(MakePair(definesHash, i->second_));
        else
        {
            // No shader variation found. Create new
            i = variations.Insert(MakePair(normalizedHash, SharedPtr<ShaderVariation>(new ShaderVariation(this, type))));
            if (definesHash != normalizedHash)
                variations.Insert(MakePair(definesHash, i->second_));

            i->second_->SetName(GetFileName(GetName()));
            i->second_->SetDefines(normalizedDefines);
            ++numVariations_;
            RefreshMemoryUse();
        }
    }

    return i->second_;
}

bool Shader::ProcessSource(String& code, Deserializer& source)
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();

    // If the source if a non-packaged file, store the timestamp
    File* file = dynamic_cast<File*>(&source);
    if (file && !file->IsPackaged())
    {
        FileSystem* fileSystem = GetSubsystem<FileSystem>();
        String fullName = cache->GetResourceFileName(file->GetName());
        unsigned fileTimeStamp = fileSystem->GetLastModifiedTime(fullName);
        if (fileTimeStamp > timeStamp_)
            timeStamp_ = fileTimeStamp;
    }

    // Store resource dependencies for includes so that we know to reload if any of them changes
    if (source.GetName() != GetName())
        cache->StoreResourceDependency(this, source.GetName());

    while (!source.IsEof())
    {
        String line = source.ReadLine();

        if (line.StartsWith("#include"))
        {
            String includeFileName = GetPath(source.GetName()) + line.Substring(9).Replaced("\"", "").Trimmed();

            SharedPtr<File> includeFile = cache->GetFile(includeFileName);
            if (!includeFile)
                return false;

            // Add the include file into the current code recursively
            if (!ProcessSource(code, *includeFile))
                return false;
        }
        else
        {
            code += line;
            code += "\n";
        }
    }

    // Finally insert an empty line to mark the space between files
    code += "\n";

    return true;
}

String Shader::NormalizeDefines(const String& defines)
{
    Vector<String> definesVec = defines.ToUpper().Split(' ');
    Sort(definesVec.Begin(), definesVec.End());
    return String::Joined(definesVec, " ");
}

void Shader::RefreshMemoryUse()
{
    SetMemoryUse(
        (unsigned)(sizeof(Shader) + vsSourceCode_.Length() + psSourceCode_.Length() + numVariations_ * sizeof(ShaderVariation)));
}

}
<commit_msg>Remove the mechanism to comment out "attribute"<commit_after>//
// Copyright (c) 2008-2015 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

#include "../Precompiled.h"

#include "../Core/Context.h"
#include "../Graphics/Graphics.h"
#include "../Graphics/Shader.h"
#include "../Graphics/ShaderVariation.h"
#include "../IO/Deserializer.h"
#include "../IO/FileSystem.h"
#include "../IO/Log.h"
#include "../Resource/ResourceCache.h"

#include "../DebugNew.h"

namespace Atomic
{

void CommentOutFunction(String& code, const String& signature)
{
    unsigned startPos = code.Find(signature);
    unsigned braceLevel = 0;
    if (startPos == String::NPOS)
        return;

    code.Insert(startPos, "/*");

    for (unsigned i = startPos + 2 + signature.Length(); i < code.Length(); ++i)
    {
        if (code[i] == '{')
            ++braceLevel;
        else if (code[i] == '}')
        {
            --braceLevel;
            if (braceLevel == 0)
            {
                code.Insert(i + 1, "*/");
                return;
            }
        }
    }
}

Shader::Shader(Context* context) :
    Resource(context),
    timeStamp_(0),
    numVariations_(0)
{
    RefreshMemoryUse();
}

Shader::~Shader()
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    cache->ResetDependencies(this);
}

void Shader::RegisterObject(Context* context)
{
    context->RegisterFactory<Shader>();
}

bool Shader::BeginLoad(Deserializer& source)
{
    Graphics* graphics = GetSubsystem<Graphics>();
    if (!graphics)
        return false;

    // Load the shader source code and resolve any includes
    timeStamp_ = 0;
    String shaderCode;
    if (!ProcessSource(shaderCode, source))
        return false;

    // Comment out the unneeded shader function
    vsSourceCode_ = shaderCode;
    psSourceCode_ = shaderCode;
    CommentOutFunction(vsSourceCode_, "void PS(");
    CommentOutFunction(psSourceCode_, "void VS(");

    // OpenGL: rename either VS() or PS() to main(), comment out vertex attributes in pixel shaders
#ifdef ATOMIC_OPENGL
    vsSourceCode_.Replace("void VS(", "void main(");
    psSourceCode_.Replace("void PS(", "void main(");
#endif

    RefreshMemoryUse();
    return true;
}

bool Shader::EndLoad()
{
    // If variations had already been created, release them and require recompile
    for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = vsVariations_.Begin(); i != vsVariations_.End(); ++i)
        i->second_->Release();
    for (HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = psVariations_.Begin(); i != psVariations_.End(); ++i)
        i->second_->Release();

    return true;
}

ShaderVariation* Shader::GetVariation(ShaderType type, const String& defines)
{
    return GetVariation(type, defines.CString());
}

ShaderVariation* Shader::GetVariation(ShaderType type, const char* defines)
{
    StringHash definesHash(defines);
    HashMap<StringHash, SharedPtr<ShaderVariation> >& variations(type == VS ? vsVariations_ : psVariations_);
    HashMap<StringHash, SharedPtr<ShaderVariation> >::Iterator i = variations.Find(definesHash);
    if (i == variations.End())
    {
        // If shader not found, normalize the defines (to prevent duplicates) and check again. In that case make an alias
        // so that further queries are faster
        String normalizedDefines = NormalizeDefines(defines);
        StringHash normalizedHash(normalizedDefines);

        i = variations.Find(normalizedHash);
        if (i != variations.End())
            variations.Insert(MakePair(definesHash, i->second_));
        else
        {
            // No shader variation found. Create new
            i = variations.Insert(MakePair(normalizedHash, SharedPtr<ShaderVariation>(new ShaderVariation(this, type))));
            if (definesHash != normalizedHash)
                variations.Insert(MakePair(definesHash, i->second_));

            i->second_->SetName(GetFileName(GetName()));
            i->second_->SetDefines(normalizedDefines);
            ++numVariations_;
            RefreshMemoryUse();
        }
    }

    return i->second_;
}

bool Shader::ProcessSource(String& code, Deserializer& source)
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();

    // If the source if a non-packaged file, store the timestamp
    File* file = dynamic_cast<File*>(&source);
    if (file && !file->IsPackaged())
    {
        FileSystem* fileSystem = GetSubsystem<FileSystem>();
        String fullName = cache->GetResourceFileName(file->GetName());
        unsigned fileTimeStamp = fileSystem->GetLastModifiedTime(fullName);
        if (fileTimeStamp > timeStamp_)
            timeStamp_ = fileTimeStamp;
    }

    // Store resource dependencies for includes so that we know to reload if any of them changes
    if (source.GetName() != GetName())
        cache->StoreResourceDependency(this, source.GetName());

    while (!source.IsEof())
    {
        String line = source.ReadLine();

        if (line.StartsWith("#include"))
        {
            String includeFileName = GetPath(source.GetName()) + line.Substring(9).Replaced("\"", "").Trimmed();

            SharedPtr<File> includeFile = cache->GetFile(includeFileName);
            if (!includeFile)
                return false;

            // Add the include file into the current code recursively
            if (!ProcessSource(code, *includeFile))
                return false;
        }
        else
        {
            code += line;
            code += "\n";
        }
    }

    // Finally insert an empty line to mark the space between files
    code += "\n";

    return true;
}

String Shader::NormalizeDefines(const String& defines)
{
    Vector<String> definesVec = defines.ToUpper().Split(' ');
    Sort(definesVec.Begin(), definesVec.End());
    return String::Joined(definesVec, " ");
}

void Shader::RefreshMemoryUse()
{
    SetMemoryUse(
        (unsigned)(sizeof(Shader) + vsSourceCode_.Length() + psSourceCode_.Length() + numVariations_ * sizeof(ShaderVariation)));
}

}
<|endoftext|>


<commit_before>#include "PILWindowSystem.h"
#include <string.h>

namespace PIL
{
	uint32 Window::sWindowCounter = 0;
	Display* Window::sDisplay = NULL;
	int32 Window::sDisplayRefCount = 0;

	Window::Window(std::string name, int32 x, int32 y, uint32 width, uint32 height, NameValue_Map *param)
	{
		mID = sWindowCounter++;
		mName = name;
		mTitle = name;
		mLeft = x;
		mTop = y;
		mWidth = width;
		mHeight = height;
		if(param) mParamList = *param;
		mWindowManager = NULL;
		mIsActive = false;
		mIsFullScreen = false;
		mStatus = WS_None;
		mWindow = 0L;
	}

	Window::~Window()
	{
		if (mStatus != WS_Destoryed)
		{
			Destory();
		}
	}

	HRESULT Window::Create()
	{
		if (mName.empty() || mWidth < 0 || mHeight < 0)
			return E_INVALIDARG;

		if (sDisplay == NULL)
		{
			sDisplay = XOpenDisplay(NULL);
			if (sDisplay == NULL)
				return E_FAIL;
		}
		Visual *visual = NULL;
		visual = DefaultVisual(sDisplay, 0);

		mWindow = XCreateWindow(sDisplay, DefaultRootWindow(sDisplay),
				mLeft, mTop, mWidth, mHeight,
				0, CopyFromParent, CopyFromParent, visual, 0, NULL);

		if(mWindow == 0L)
			return E_FAIL;

		XStoreName(sDisplay, mWindow, mTitle.c_str());

		XUnmapWindow(sDisplay, mWindow);
		mStatus = WS_Hide;

		sDisplayRefCount++;
		return S_OK;
	}

	HRESULT Window::Destory()
	{
		if(sDisplay != NULL && mWindow != 0L)
		{
			XDestroyWindow(sDisplay, mWindow);
			mWindow = 0L;
			sDisplayRefCount--;
			if(sDisplayRefCount == 0)
			{
				XCloseDisplay(sDisplay);
				sDisplay = NULL;
			}
		}
		mStatus = WS_Destoryed;
		mIsActive = false;
		mIsFullScreen = false;
		return S_OK;
	}

	bool Window::ShowWindow(bool bShow)
	{
		if(sDisplay == NULL || mWindow == 0L)
			return false;

		if (bShow)
		{
			XMapWindow(sDisplay, mWindow);
			mStatus = WS_Show;
		}
		else
		{
			XUnmapWindow(sDisplay, mWindow);
			mStatus = WS_Hide;
		}
		return true;
	}

	void Window::HandleMessage()
	{

		if(sDisplay == NULL || mWindow == 0)
			return ;

		XEvent event;

		while (XCheckWindowEvent(sDisplay, mWindow,
				StructureNotifyMask | ExposureMask,
				&event))
		{
			switch(event.type)
			{
			case Expose:
			{
				const char *msg = "Hello X11";
				XFillRectangle(sDisplay, mWindow, DefaultGC(sDisplay, DefaultScreen(sDisplay)), 20, 20, 10, 10);
				XDrawString(sDisplay, mWindow, DefaultGC(sDisplay, DefaultScreen(sDisplay)), 50, 50, msg, strlen(msg));
				break;
			}
			case DestroyNotify:
			{
				if(mWindowManager)
				{
					mWindowManager->DeleteWindow(this);
				}
				break;
			}
			case MapNotify:
			{
				if(mWindowManager)
				{
					mWindowManager->ChangeActiveWindow(this, true);
				}
				break;
			}
			case UnmapNotify:
			{	//win->setVisible( false );
				if(mWindowManager)
				{
					mWindowManager->ChangeActiveWindow(this, false);
				}
				break;
			}
			default:
				break;
			}
		}
	}

	HRESULT Window::SetWindowTitle(std::string title)
	{
		if(sDisplay == NULL || mWindow == 0L)
			return E_INVALIDARG;
		mTitle = title;
		XStoreName(sDisplay, mWindow, mTitle.c_str());
		return S_OK;
	}

	void Window::OnActiveChange(Window* w, bool bActive)
	{
		if (w == this)
		{
			SetActive(bActive);
		}
	}

	void Window::SetActive(bool bActive)
	{
		if (bActive)
		{
			mStatus = WS_Show;
			printf("%s Active\n", mName.c_str());
		}
		mIsActive = bActive;
	}

	void Window::OnMoveOrResize(Window *w)
	{

	}

}
<commit_msg>更新Linux window system<commit_after>#include "PILWindowSystem.h"
#include <string.h>

namespace PIL
{
	uint32 Window::sWindowCounter = 0;
	Display* Window::sDisplay = NULL;
	int32 Window::sDisplayRefCount = 0;

	Window::Window(std::string name, int32 x, int32 y, uint32 width, uint32 height, NameValue_Map *param)
	{
		mID = sWindowCounter++;
		mName = name;
		mTitle = name;
		mLeft = x;
		mTop = y;
		mWidth = width;
		mHeight = height;
		if(param) mParamList = *param;
		mWindowManager = NULL;
		mIsActive = false;
		mIsFullScreen = false;
		mStatus = WS_None;
		mWindow = 0L;
	}

	Window::~Window()
	{
		if (mStatus != WS_Destoryed)
		{
			Destory();
		}
	}

	HRESULT Window::Create()
	{
		if (mName.empty() || mWidth < 0 || mHeight < 0)
			return E_INVALIDARG;

		if (sDisplay == NULL)
		{
			sDisplay = XOpenDisplay(NULL);
			if (sDisplay == NULL)
				return E_FAIL;
		}
		Visual *visual = NULL;
		visual = DefaultVisual(sDisplay, 0);

		mWindow = XCreateWindow(sDisplay, DefaultRootWindow(sDisplay),
				mLeft, mTop, mWidth, mHeight,
				0, CopyFromParent, CopyFromParent, visual, 0, NULL);

		if(mWindow == 0L)
			return E_FAIL;

		XStoreName(sDisplay, mWindow, mTitle.c_str());

		XSelectInput(sDisplay, mWindow, StructureNotifyMask | VisibilityChangeMask | FocusChangeMask | ExposureMask);

		XUnmapWindow(sDisplay, mWindow);
		mStatus = WS_Hide;

		sDisplayRefCount++;
		return S_OK;
	}

	HRESULT Window::Destory()
	{
		if(sDisplay != NULL && mWindow != 0L)
		{
			XDestroyWindow(sDisplay, mWindow);
			mWindow = 0L;
			sDisplayRefCount--;
			if(sDisplayRefCount == 0)
			{
				XCloseDisplay(sDisplay);
				sDisplay = NULL;
			}
		}
		mStatus = WS_Destoryed;
		mIsActive = false;
		mIsFullScreen = false;
		return S_OK;
	}

	bool Window::ShowWindow(bool bShow)
	{
		if(sDisplay == NULL || mWindow == 0L)
			return false;

		if (bShow)
		{
			XMapWindow(sDisplay, mWindow);
			mStatus = WS_Show;
		}
		else
		{
			XUnmapWindow(sDisplay, mWindow);
			mStatus = WS_Hide;
		}
		return true;
	}

	void Window::HandleMessage()
	{

		if(sDisplay == NULL || mWindow == 0)
			return ;

		XEvent event;

		while (XCheckWindowEvent(sDisplay, mWindow,
				StructureNotifyMask | VisibilityChangeMask | FocusChangeMask | ExposureMask,
				&event))
		{
			switch(event.type)
			{
			case Expose:
			{
				const char *msg = "Hello X11";
				XFillRectangle(sDisplay, mWindow, DefaultGC(sDisplay, DefaultScreen(sDisplay)), 20, 20, 10, 10);
				XDrawString(sDisplay, mWindow, DefaultGC(sDisplay, DefaultScreen(sDisplay)), 50, 50, msg, strlen(msg));
				break;
			}
			case DestroyNotify:
			{
				if(mWindowManager)
				{
					mWindowManager->DeleteWindow(this);
				}
				break;
			}
			case MapNotify:
			{
				if(mWindowManager)
				{
					mWindowManager->ChangeActiveWindow(this, true);
				}
				break;
			}
			case UnmapNotify:
			{	//win->setVisible( false );
				if(mWindowManager)
				{
					mWindowManager->ChangeActiveWindow(this, false);
				}
				break;
			}
			case FocusIn:
			{
				if(mWindowManager)
				{
					mWindowManager->ChangeActiveWindow(this, true);
				}
			}
			case FocusOut:
			{
				if(mWindowManager)
				{
					mWindowManager->ChangeActiveWindow(this, false);
				}
			}
			case ConfigureNotify:
			{
				if(mWindowManager)
				{
					mWindowManager->MoveOrResizeWindow(this);
				}
			}
			default:
				break;
			}
		}
	}

	HRESULT Window::SetWindowTitle(std::string title)
	{
		if(sDisplay == NULL || mWindow == 0L)
			return E_INVALIDARG;
		mTitle = title;
		XStoreName(sDisplay, mWindow, mTitle.c_str());
		return S_OK;
	}

	void Window::OnActiveChange(Window* w, bool bActive)
	{
		if (w == this)
		{
			SetActive(bActive);
		}
	}

	void Window::SetActive(bool bActive)
	{
		if (bActive)
		{
			mStatus = WS_Show;
		}
		mIsActive = bActive;
	}

	void Window::OnMoveOrResize(Window *w)
	{
		if(this == w)
		{
			XWindowAttributes attr;
			::Window root, parent, *pchild = NULL, child;
			uint32 nchild = 0;
			int ox = 0, oy = 0;
			XQueryTree(sDisplay, mWindow, &root, &parent, &pchild, &nchild);
			XTranslateCoordinates(sDisplay, mWindow, root, 0, 0, &ox, &oy, &child);
			if(XGetWindowAttributes(sDisplay, mWindow, &attr))
			{
				mLeft = ox - attr.x;
				mTop = oy - attr.y;
				mWidth = attr.width;
				mHeight = attr.height;
			}
		}
	}

}
<|endoftext|>


<commit_before>#include "scene.h"

Scene::Scene(Camera* _camera, std::vector<Surface*> _surfaces, std::vector<Light*> _lights, int width, int height, int _recursive_depth) {
	camera = _camera;
	surfaces = _surfaces;
	lights = _lights;
	recursive_depth = _recursive_depth;

	float focal_length = 1;

	camera->focal_length = focal_length;
	sampler = new Sampler(width, height, camera->fov, focal_length);
	tracer = new RayTracer(surfaces, lights);
}

ThreeDVector* Scene::get_color(int x,int y) {

	return this->get_color_helper(x, y, 1);
}

ThreeDVector* Scene::get_color_helper(int x, int y, int grid_size) {
	vector<ThreeDVector*> samples = sampler->get_sample(x, y, grid_size);
	ThreeDVector* color_summation = new ThreeDVector(0, 0, 0);
	for(vector<ThreeDVector*>::iterator it = samples.begin(); it != samples.end(); ++it) {
    	Ray* view_ray = this->camera->get_view_ray(*it);
    	ThreeDVector* color_sample = this->tracer->trace(view_ray, this->recursive_depth, NULL);
    	color_summation->vector_add_bang(color_sample);
    	delete color_sample;
	}

	//Average out colors by number of samples
	color_summation->scalar_multiply_bang(1.0 / (grid_size * grid_size));
	return color_summation;
}

Scene::~Scene(){
	delete camera;
	delete sampler;
}<commit_msg>free memory lines added<commit_after>#include "scene.h"

Scene::Scene(Camera* _camera, std::vector<Surface*> _surfaces, std::vector<Light*> _lights, int width, int height, int _recursive_depth) {
	camera = _camera;
	surfaces = _surfaces;
	lights = _lights;
	recursive_depth = _recursive_depth;

	float focal_length = 1;

	camera->focal_length = focal_length;
	sampler = new Sampler(width, height, camera->fov, focal_length);
	tracer = new RayTracer(surfaces, lights);
}

ThreeDVector* Scene::get_color(int x,int y) {

	return this->get_color_helper(x, y, 1);
}

ThreeDVector* Scene::get_color_helper(int x, int y, int grid_size) {
	vector<ThreeDVector*> samples = sampler->get_sample(x, y, grid_size);
	ThreeDVector* color_summation = new ThreeDVector(0, 0, 0);
	for(vector<ThreeDVector*>::iterator it = samples.begin(); it != samples.end(); ++it) {
    	Ray* view_ray = this->camera->get_view_ray(*it);
    	ThreeDVector* color_sample = this->tracer->trace(view_ray, this->recursive_depth, NULL);
    	color_summation->vector_add_bang(color_sample);
    	delete color_sample;
	}

	//Average out colors by number of samples
	color_summation->scalar_multiply_bang(1.0 / (grid_size * grid_size));
	return color_summation;
}

Scene::~Scene(){
	delete camera;
	delete sampler;
	delete tracer;
}<|endoftext|>