text:
**NEW**: [Improved version](http://agilul.github.io/slot-phaser/) with [Phaser](http://phaser.io/).

A simple slot machine HTML5 game. [Try it](https://agilul.github.io/slotmachine/) in your browser.

[Source code](https://github.com/agilul/slotmachine).

## Audio Visualization

![Audio Visualization](images/audiovis.png)

An audio visualizer with FFT analysis and shader rendering.

Written in C++ with [SFML](http://www.sfml-dev.org/) and GLSL. The shader uses a ray marching algorithm to render geometric primitives.

[[Source](https://github.com/agilul/audio-visualization), [YouTube](https://www.youtube.com/watch?v=bYk8sEuPvlk)]

## Game of Life

![Game of Life](images/life.png)

An implementation of Conway's Game of Life in OpenGL Shading Language.

[[Source](https://github.com/agilul/game-of-life), [Shadertoy](https://www.shadertoy.com/view/XdtXRX)]

## Jumper

![Jumper](images/jumper.png)

A simple jumper game with powerups and enemies.

Made with [Unity3D](https://unity3d.com/).

[[Source](https://github.com/agilul/jumper-unity3d), [GIF](images/jumper.gif)]

## Love2D Demos

All demos are written in Lua with [LÖVE](https://love2d.org/) 0.10.1.

### Raycaster in a maze

![Raycaster](images/raycaster.png)

A simulated 3D environment with raycasting in a 2D randomly generated maze.
Using a fixed number of raycasts it determines the distance of walls from the player and draws them accordingly.

The maze is generated with the recursive backtracking algorithm and then converted to a format suitable for the renderer.

The raycaster subsystem is a partial port from http://www.playfuljs.com/a-first-person-engine-in-265-lines/

[[Source](https://github.com/agilul/raycaster-maze-love2d), [GIF](images/raycaster.gif)]

### Software Renderer

![Renderer](images/renderer.png)

A simple 3D renderer for a set of points using transformation matrices and perspective projection.
It doesn't use OpenGL functions, instead it calculates through matrix operations the final positions of 3D vertices to a 2D scene.

[[Source](https://github.com/agilul/software-renderer-love2d), [GIF](images/renderer.gif)]

### Space Shooter

![Space Shooter](images/spaceshooter.png)

A top-down space shooter with physics and dynamic steering behaviours.
It uses simple physics integration with movement governed by AI modifying linear and angular accelerations.

Helper libraries in lib/ from http://hump.readthedocs.org/en/latest/

[[Source](https://github.com/agilul/spaceshooter-love2d), [GIF](images/spaceshooter.gif)]


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EggFarmSystem.Models
{
    public class EmployeeCost : Entity
    {
        public EmployeeCost()
        {
            Details = new List<EmployeeCostDetail>();
        }

        public DateTime Date { get; set; }

        public long Total { get; set; }

        public List<EmployeeCostDetail> Details { get; set; }

        public override IList<ErrorInfo> Validate()
        {
            var errorList = new List<ErrorInfo>();

            if(Date == DateTime.MaxValue || Date == DateTime.MinValue)
                errorList.Add(new ErrorInfo("Date","EmployeeCost_InvalidDate"));

            if (Details == null || Details.Count == 0)
            {
                errorList.Add(new ErrorInfo("Details", "EmployeeCost_RequireDetails"));
            }
            else
            {
                if (Details.GroupBy(d => d.EmployeeId).Any(g => g.Count() > 1))
                    errorList.Add(new ErrorInfo("Details", "EmployeeCost_DuplicateEmployee"));

                for (var i = 0; i < Details.Count; i++)
                {
                    var detailErrors = Details[i].Validate();
                    if (detailErrors != null && detailErrors.Count > 0)
                    {
                        errorList.AddRange(detailErrors.Select(detailError => new ErrorInfo("Details[" + i + "]." + detailError.PropertyName, detailError.Message)));
                    }
                }
            }

            return errorList;
        }
    }

    public class EmployeeCostDetail : IValidatable
    {
        public Guid EmployeeId { get; set; }

        public bool Present { get; set; }

        public long Salary { get; set; }

        public string Description { get; set; }

        public IList<ErrorInfo> Validate()
        {
            var errors = new List<ErrorInfo>();

            if(EmployeeId == Guid.Empty)
                errors.Add(new ErrorInfo("EmployeeId","EmployeeCostDetail_RequireEmployee"));

            return errors;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using namespace Windows::Storage;
using namespace Windows::Foundation;
#endif
#endif

using namespace ApplicationInsights::core;

/// <summary>
/// Initializes a new instance of the <see cref="TelemetryClient"/> class.
/// </summary>
/// <param name="iKey">The ikey.</param>
TelemetryClient::TelemetryClient(std::wstring& iKey)
{
	m_config = new TelemetryClientConfig(iKey);
	m_context = new TelemetryContext(iKey);
	m_context->InitContext();
	m_channel = new TelemetryChannel(*m_config);
}

/// <summary>
/// Initializes a new instance of the <see cref="TelemetryClient"/> class.
/// </summary>
/// <param name="config">The configuration.</param>
/// <param name="context">The context.</param>
TelemetryClient::TelemetryClient(TelemetryClientConfig &config,	TelemetryContext &context)
	: m_config(&config), m_context(&context)
{
}

/// <summary>
/// Finalizes an instance of the <see cref="TelemetryClient"/> class.
/// </summary>
TelemetryClient::~TelemetryClient()
{
	// Flush any pending data
	Flush();

	// Free allocated memory
	Utils::SafeDelete(m_channel);
	Utils::SafeDelete(m_context);
	Utils::SafeDelete(m_config);
}

/// <summary>
/// Tracks the event.
/// </summary>
/// <param name="eventName">Name of the event.</param>
void TelemetryClient::TrackEvent(const std::wstring& eventName)
{
	wstring_wstring_map props;
	std::map<std::wstring, double> measurements;
	TrackEvent(eventName, props, measurements);
}

/// <summary>
/// Tracks the event.
/// </summary>
/// <param name="eventName">Name of the event.</param>
/// <param name="properties">The properties.</param>
void TelemetryClient::TrackEvent(const std::wstring& eventName, const wstring_wstring_map& properties)
{
	std::map<std::wstring, double> measurements;
	TrackEvent(eventName, properties, measurements);
}

/// <summary>
/// Tracks the event.
/// </summary>
/// <param name="eventName">Name of the event.</param>
/// <param name="properties">The properties.</param>
/// <param name="measurements">The measurements.</param>
void TelemetryClient::TrackEvent(const std::wstring& eventName, const wstring_wstring_map& properties, const std::map<std::wstring, double>& measurements)
{
	EventData telemetry;
	telemetry.SetName(eventName);
	if (properties.size() > 0)
	{
		telemetry.SetProperties(properties);
	}
	if (measurements.size() > 0)
	{
		telemetry.SetMeasurements(measurements);
	}

	Track(telemetry);
}

/// <summary>
/// Tracks the trace.
/// </summary>
/// <param name="message">The message.</param>
void TelemetryClient::TrackTrace(const std::wstring& message)
{
	wstring_wstring_map properties;
	TrackTrace(message, properties);
}

/// <summary>
/// Tracks the trace.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="properties">The properties.</param>
void TelemetryClient::TrackTrace(const std::wstring& message, const wstring_wstring_map& properties)
{
	MessageData telemetry;
	telemetry.SetMessage(message);
	if (properties.size() > 0)
	{
		telemetry.SetProperties(properties);
	}

	Track(telemetry);
}

/// <summary>
/// Tracks the metric.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
void TelemetryClient::TrackMetric(const std::wstring& name, const double& value)
{
	MetricData telemetry;
	DataPoint data;
	data.SetCount(1);
	data.SetKind(Measurement);
	data.SetMax(value);
	data.SetMax(value);
	data.SetName(name);
	data.SetValue(value);
	std::vector<DataPoint*> metricsList;
	metricsList.push_back(&data);

	telemetry.SetMetrics(metricsList);
	Track(telemetry);
}

/// <summary>
/// Tracks the page view.
/// </summary>
/// <param name="pageName">Name of the page.</param>
void TelemetryClient::TrackPageView(const std::wstring& pageName)
{
	wstring_wstring_map properties;
	std::map<std::wstring, double> measurements;
	std::wstring duration = L"";
	TrackPageView(pageName, duration, properties, measurements);
}

/// <summary>
/// Tracks the page view.
/// </summary>
/// <param name="pageName">Name of the page.</param>
/// <param name="duration">The duration.</param>
void TelemetryClient::TrackPageView(const std::wstring& pageName, const std::wstring& duration)
{
	wstring_wstring_map properties;
	std::map<std::wstring, double> measurements;

	TrackPageView(pageName, duration, properties, measurements);
}

/// <summary>
/// Tracks the page view.
/// </summary>
/// <param name="pageName">Name of the page.</param>
/// <param name="duration">The duration.</param>
/// <param name="properties">The properties.</param>
void TelemetryClient::TrackPageView(const std::wstring& pageName, const std::wstring& duration, const wstring_wstring_map& properties)
{
	std::map<std::wstring, double> measurements;
	TrackPageView(pageName, duration, properties, measurements);
}

/// <summary>
/// Tracks the page view.
/// </summary>
/// <param name="pageName">Name of the page.</param>
/// <param name="duration">The duration.</param>
/// <param name="properties">The properties.</param>
/// <param name="measurements">The measurements.</param>
void TelemetryClient::TrackPageView(const std::wstring& pageName, const std::wstring& duration, const wstring_wstring_map& properties, const std::map<std::wstring, double>& measurements)
{
	PageViewData telemetry;
	telemetry.SetName(pageName);
	telemetry.SetUrl(pageName);
	if (duration.length() != 0)
	{
		telemetry.SetDuration(duration);
	}

	if (properties.size() > 0)
	{
		telemetry.SetProperties(properties);
	}
	if (measurements.size() > 0)
	{
		telemetry.SetMeasurements(measurements);
	}

	Track(telemetry);
}

/// <summary>
/// Tracks the session start.
/// </summary>
void TelemetryClient::TrackSessionStart()
{
	SessionStateData session;
	session.SetState(SessionState::Start);

	Track(session);
}

/// <summary>
/// Tracks the specified telemetry.
/// </summary>
/// <param name="telemetry">The telemetry.</param>
void TelemetryClient::Track(Domain& telemetry)
{
	if (IsTrackingEnabled())
	{
		m_channel->Enqueue(*m_context, telemetry);
	}
}

/// <summary>
/// Flushes this instance.
/// </summary>
void TelemetryClient::Flush()
{
	if (m_channel)
	{
		m_channel->Send();
	}
}

/// <summary>
/// Disables all tracking.
/// </summary>
void TelemetryClient::DisableTracking()
{
#ifdef WINAPI_FAMILY_PARTITION // it's SOME kind of Windows
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) // Win32, no store, no phone
	//Use registry settings
	HKEY hKey;
	if (Utils::OpenRegKey(hKey, m_config->GetIKey()))
	{
		DWORD disable = 1;
		if (RegSetValueEx(hKey, TEXT("DisableTracking"), 0, REG_DWORD, (const BYTE *)&disable, sizeof(disable)) != ERROR_SUCCESS)
		{
			//Unable to set registry value
			Utils::WriteDebugLine(L"ERROR: Failed to set reg key for disable tracking");
		}
		RegCloseKey(hKey);
	}

#else  //Windows phone or store
	auto values = Utils::GetLocalSettingsContainer();

	values->Insert("Tracking", dynamic_cast<PropertyValue^>(PropertyValue::CreateString("Disable")));

#endif
#endif
}

/// <summary>
/// Enables all tracking.
/// </summary>
void TelemetryClient::EnableTracking()
{
#ifdef WINAPI_FAMILY_PARTITION // it's SOME kind of Windows
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) // Win32, no store, no phone
	//Use registry settings
	HKEY hKey;
	if (Utils::OpenRegKey(hKey, m_config->GetIKey()))
	{
		if (RegDeleteValue(hKey, TEXT("DisableTracking")) != ERROR_SUCCESS)
		{
			//Unable to set registry value
			Utils::WriteDebugLine(L"ERROR: Failed to remove reg key for disable tracking");
		}
		RegCloseKey(hKey);
	}
#else  //Windows phone or store
	auto values = Utils::GetLocalSettingsContainer();
	values->Remove("Tracking");

#endif
#endif
}

/// <summary>
/// Determines whether [is tracking enabled].
/// </summary>
/// <returns>True if the tracking is enabled, otherwise false</returns>
bool TelemetryClient::IsTrackingEnabled()
{
#if defined(WINAPI_FAMILY_PARTITION) // it's SOME kind of Windows
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) // Win32, no store, no phone
	//Use registry settings
	HKEY hKey;

	DWORD szBuffer = 0;
	DWORD dwBufferSize = sizeof(szBuffer);
	bool trackingEnabled = true;

	if (Utils::OpenRegKey(hKey, m_config->GetIKey()))
	{
		if (RegQueryValueEx(hKey, TEXT("DisableTracking"), nullptr, nullptr, (LPBYTE)szBuffer, &dwBufferSize) == ERROR_SUCCESS)
		{
			trackingEnabled = false;
		}
		RegCloseKey(hKey);
	}
	return trackingEnabled;
#else  //Windows phone or store
	bool enabled = true;

	auto values = Utils::GetLocalSettingsContainer();

	enabled = !(values->HasKey("Tracking"));

	return enabled;
#endif
#endif
}


text: export_token_macro! {[await]}


text:
@implementation QMReplaceViewControllerSegue

- (void)perform {

    // Grab Variables for readability
    UIViewController *sourceViewController = self.sourceViewController;
    UIViewController *destinationController = self.destinationViewController;
    UINavigationController *navigationController = sourceViewController.navigationController;

    if (navigationController.viewControllers != nil) {

        // Get a changeable copy of the stack
        NSMutableArray *controllerStack = [navigationController.viewControllers mutableCopy];

        // Replace the source controller with the destination controller, wherever the source may be
        NSUInteger index = [controllerStack indexOfObject:sourceViewController];
        controllerStack[index] = destinationController;

        // Assign the updated stack with animation
        [navigationController setViewControllers:[controllerStack copy] animated:YES];
    }
}

@end


text:
#include "CAPI_GL_HSWDisplay.h"
#include "CAPI_GL_DistortionShaders.h"
#include "../../OVR_CAPI_GL.h"
#include "../../Kernel/OVR_File.h"
#include "../../Kernel/OVR_Math.h"
#include "../../Kernel/OVR_Allocator.h"
#include "../../Kernel/OVR_Color.h"

OVR_DISABLE_MSVC_WARNING(4996) // "This function or variable may be unsafe..."

namespace OVR { namespace CAPI {

// Loads the TGA data from the File as an array of width * height 32 bit Texture_RGBA values.
// Returned pointer must be freed with OVR_FREE.
uint8_t* LoadTextureTgaData(OVR::File* f, uint8_t alpha, int& width, int& height)
{
    // See http://www.fileformat.info/format/tga/egff.htm for format details.
    // TGA files are stored with little-endian data.
    uint8_t* pRGBA  = NULL;

    f->SeekToBegin();

    const int desclen = f->ReadUByte();
    const int palette = f->ReadUByte();
    OVR_UNUSED(palette);
    const int imgtype = f->ReadUByte();
    f->ReadUInt16(); // Skip bytes
    int palCount = f->ReadUInt16();
    int palSize = f->ReadUByte();
    f->ReadUInt16();
    f->ReadUInt16();
    width = f->ReadUInt16();
    height = f->ReadUInt16();
    int bpp = f->ReadUByte();
    f->ReadUByte();

    const int ImgTypeBGRAUncompressed = 2;
    const int ImgTypeBGRARLECompressed = 10;

    OVR_ASSERT(((imgtype == ImgTypeBGRAUncompressed) || (imgtype == ImgTypeBGRARLECompressed)) && ((bpp == 24) || (bpp == 32)));

    // imgType 2 is uncompressed true-color image.
    // imgType 10 is run-length encoded true-color image.
    if(((imgtype == ImgTypeBGRAUncompressed) || (imgtype == ImgTypeBGRARLECompressed)) && ((bpp == 24) || (bpp == 32)))
    {
        int imgsize = width * height * 4;
        pRGBA = (uint8_t*) OVR_ALLOC(imgsize);
        f->Skip(desclen);
        f->Skip(palCount * (palSize + 7) >> 3);
        int strideBytes = width * 4; // This is the number of bytes between successive rows.

        unsigned char buf[4] = { 0, 0, 0, alpha }; // If bpp is 24 then this alpha will be unmodified below.

        switch (imgtype)
        {
        case ImgTypeBGRAUncompressed:
            switch (bpp)
            {
            case 24:
            case 32:
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        f->Read(buf, bpp / 8); // Data is stored as B, G, R
                        pRGBA[y*strideBytes + x*4 + 0] = buf[2];
                        pRGBA[y*strideBytes + x*4 + 1] = buf[1];
                        pRGBA[y*strideBytes + x*4 + 2] = buf[0];
                        pRGBA[y*strideBytes + x*4 + 3] = buf[3];
                    }
                }
                break;
            }
            break;

        case ImgTypeBGRARLECompressed:
            switch (bpp)
            {
            case 24:
            case 32:
                for (int y = 0; y < height; y++) // RLE spans don't cross successive rows.
                {
                    int x = 0;

                    while(x < width)
                    {
                        uint8_t rleByte;
                        f->Read(&rleByte, 1);

                        if(rleByte & 0x80) // If the high byte is set then what follows are RLE bytes.
                        {
                            size_t rleCount = ((rleByte & 0x7f) + 1);
                            f->Read(buf, bpp / 8); // Data is stored as B, G, R, A

                            for (; rleCount; --rleCount, ++x)
                            {
                                pRGBA[y*strideBytes + x*4 + 0] = buf[2];
                                pRGBA[y*strideBytes + x*4 + 1] = buf[1];
                                pRGBA[y*strideBytes + x*4 + 2] = buf[0];
                                pRGBA[y*strideBytes + x*4 + 3] = buf[3];
                            }
                        }
                        else // Else what follows are regular bytes of a count indicated by rleByte
                        {
                            for (size_t rleCount = (rleByte + 1); rleCount; --rleCount, ++x)
                            {
                                f->Read(buf, bpp / 8); // Data is stored as B, G, R, A
                                pRGBA[y*strideBytes + x*4 + 0] = buf[2];
                                pRGBA[y*strideBytes + x*4 + 1] = buf[1];
                                pRGBA[y*strideBytes + x*4 + 2] = buf[0];
                                pRGBA[y*strideBytes + x*4 + 3] = buf[3];
                            }
                        }
                    }
                }
                break;
            }
            break;
        }
    }

    return pRGBA;
} // LoadTextureTgaData

namespace GL {

// To do: This needs to be promoted to a central version, possibly in CAPI_HSWDisplay.h
struct HASWVertex
{
    Vector3f  Pos;
    Color     C;
    float     U, V;

    HASWVertex(const Vector3f& p, const Color& c = Color(64,0,0,255), float u = 0, float v = 0)
        : Pos(p), C(c), U(u), V(v)
    {}

    HASWVertex(float x, float y, float z, const Color& c = Color(64,0,0,255), float u = 0, float v = 0)
        : Pos(x,y,z), C(c), U(u), V(v)
    {}

    bool operator==(const HASWVertex& b) const
    {
        return (Pos == b.Pos) && (C == b.C) && (U == b.U) && (V == b.V);
    }
};

// This is a temporary function implementation, and it functionality needs to be implemented in a more generic way.
Texture* LoadTextureTga(RenderParams& rParams, int samplerMode, OVR::File* f, uint8_t alpha)
{
    OVR::CAPI::GL::Texture* pTexture = NULL;

    int width, height;
    const uint8_t* pRGBA = LoadTextureTgaData(f, alpha, width, height);

    if (pRGBA)
    {
        pTexture = new OVR::CAPI::GL::Texture(&rParams, width, height);

        // SetSampleMode forces the use of mipmaps through GL_LINEAR_MIPMAP_LINEAR.
        pTexture->SetSampleMode(samplerMode); // Calls glBindTexture internally.

        // We are intentionally not using mipmaps. We need to use this because Texture::SetSampleMode unilaterally uses GL_LINEAR_MIPMAP_LINEAR.
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
        OVR_ASSERT(glGetError() == 0);

        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pRGBA);
        OVR_ASSERT(glGetError() == 0);

        // With OpenGL 4.2+ we can use this instead of glTexImage2D:
        // glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, width, height);
        // glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pRGBA);

        OVR_FREE(const_cast<uint8_t*>(pRGBA));
    }

    return pTexture;
}

// Loads a texture from a memory image of a TGA file.
Texture* LoadTextureTga(RenderParams& rParams, int samplerMode, const uint8_t* pData, int dataSize, uint8_t alpha)
{
    MemoryFile memoryFile("", pData, dataSize);

    return LoadTextureTga(rParams, samplerMode, &memoryFile, alpha);
}

// The texture below may conceivably be shared between HSWDisplay instances. However,
// beware that sharing may not be possible if two HMDs are using different locales
// simultaneously. As of this writing it's not clear if that can occur in practice.

HSWDisplay::HSWDisplay(ovrRenderAPIType api, ovrHmd hmd, const HMDRenderState& renderState)
  : OVR::CAPI::HSWDisplay(api, hmd, renderState)
  , RenderParams()
  , GLMajorVersion(0)
  , GLMinorVersion(0)
  , SupportsVao(false)
  , FrameBuffer(0)
  , pTexture()
  , pShaderSet()
  , pVertexShader()
  , pFragmentShader()
  , pVB()
  , VAO(0)
  , VAOInitialized(false)
  , OrthoProjection()
{
}

bool HSWDisplay::Initialize(const ovrRenderAPIConfig* apiConfig)
{
    const ovrGLConfig* config = (const ovrGLConfig*)apiConfig;

    if(config)
    {
        // The following is essentially copied from CAPI_GL_DistortionRender.cpp's
        // Initialize function. To do: Merge this to a central location.
        RenderParams.Multisample = config->OGL.Header.Multisample;
        RenderParams.RTSize      = config->OGL.Header.RTSize;

        #if defined(OVR_OS_WIN32)
            RenderParams.Window = (config->OGL.Window) ? config->OGL.Window : GetActiveWindow();
            RenderParams.DC     = config->OGL.DC;
        #elif defined(OVR_OS_LINUX)
            if (config->OGL.Disp)
                RenderParams.Disp = config->OGL.Disp;
            if (!RenderParams.Disp)
                RenderParams.Disp = XOpenDisplay(NULL);
            if (!RenderParams.Disp)
            {
                OVR_DEBUG_LOG(("XOpenDisplay failed."));
                return false;
            }

            if (config->OGL.Win)
                RenderParams.Win= config->OGL.Win;
            if (!RenderParams.Win)
            {
                int unused;
                RenderParams.Win = glXGetCurrentDrawable();
            }
            if (!RenderParams.Win)
            {
                OVR_DEBUG_LOG(("XGetInputFocus failed."));
                return false;
            }
        #endif
    }
    else
    {
        UnloadGraphics();
    }

    return true;
}

void HSWDisplay::Shutdown()
{
    UnloadGraphics();
}

void HSWDisplay::DisplayInternal()
{
    HSWDISPLAY_LOG(("[HSWDisplay GL] DisplayInternal()"));
    // We may want to call LoadGraphics here instead of within Render.
}

void HSWDisplay::DismissInternal()
{
    HSWDISPLAY_LOG(("[HSWDisplay GL] DismissInternal()"));
    UnloadGraphics();
}

void HSWDisplay::UnloadGraphics()
{
    // RenderParams: No need to clear.
    if(FrameBuffer != 0)
    {
        glDeleteFramebuffers(1, &FrameBuffer);
        FrameBuffer = 0;
    }
    pTexture.Clear();
    pShaderSet.Clear();
    pVertexShader.Clear();
    pFragmentShader.Clear();
    pVB.Clear();
    if(VAO)
    {
        #ifdef OVR_OS_MAC
    		if(GLMajorVersion >= 3)
			{
				glDeleteVertexArrays(1, &VAO);
        	}
			else
			{
        	    glDeleteVertexArraysAPPLE(1, &VAO);
			}
		#else
            glDeleteVertexArrays(1, &VAO);
        #endif
        VAO = 0;
        VAOInitialized = false;
    }
    // OrthoProjection: No need to clear.
}

void HSWDisplay::LoadGraphics()
{
    const char* glVersionString = (const char*)glGetString(GL_VERSION);

    OVR_ASSERT(glVersionString);
    if (glVersionString)
    {
        int fieldCount = sscanf(glVersionString, isdigit(*glVersionString) ? "%d.%d" : "%*[^0-9]%d.%d", &GLMajorVersion, &GLMinorVersion); // Skip all leading non-digits before reading %d. Example glVersionStrings: "1.5 ATI-1.4.18", "OpenGL ES-CM 3.2"

        if(fieldCount != 2)
        {
            static_assert(sizeof(GLMajorVersion) == sizeof(GLint), "type mis-match");
            glGetIntegerv(GL_MAJOR_VERSION, &GLMajorVersion);
        }
    }

    // SupportsVao
    if(GLMajorVersion >= 3)
        SupportsVao = true;
    else
    {
        const char* extensions = (const char*)glGetString(GL_EXTENSIONS);
        SupportsVao = (strstr(extensions, "GL_ARB_vertex_array_object") || strstr(extensions, "GL_APPLE_vertex_array_object"));
    }

    if (FrameBuffer == 0)
        glGenFramebuffers(1, &FrameBuffer);

    if (!pTexture) // To do: Add support for .dds files, which would be significantly smaller than the size of the tga.
    {
        size_t textureSize;
        const uint8_t* TextureData = GetDefaultTexture(textureSize);
        pTexture = *LoadTextureTga(RenderParams, Sample_Linear | Sample_Clamp, TextureData, (int)textureSize, 255);
    }

    if(!pShaderSet)
        pShaderSet = *new ShaderSet();

    if(!pVertexShader)
    {
        OVR::String strShader((GLMajorVersion >= 3) ? glsl3Prefix : glsl2Prefix);
        strShader += SimpleTexturedQuad_vs;

        pVertexShader = *new VertexShader(&RenderParams, const_cast<char*>(strShader.ToCStr()), strShader.GetLength(), SimpleTexturedQuad_vs_refl, OVR_ARRAY_COUNT(SimpleTexturedQuad_vs_refl));
        pShaderSet->SetShader(pVertexShader);
    }

    if(!pFragmentShader)
    {
        OVR::String strShader((GLMajorVersion >= 3) ? glsl3Prefix : glsl2Prefix);
        strShader += SimpleTexturedQuad_ps;

        pFragmentShader = *new FragmentShader(&RenderParams, const_cast<char*>(strShader.ToCStr()), strShader.GetLength(), SimpleTexturedQuad_ps_refl, OVR_ARRAY_COUNT(SimpleTexturedQuad_ps_refl));
        pShaderSet->SetShader(pFragmentShader);
    }

    if(!pVB)
    {
        pVB = *new Buffer(&RenderParams);

        pVB->Data(Buffer_Vertex, NULL, 4 * sizeof(HASWVertex));
        HASWVertex* pVertices = (HASWVertex*)pVB->Map(0, 4 * sizeof(HASWVertex), Map_Discard);
        OVR_ASSERT(pVertices);

        if(pVertices)
        {
            const bool  flip   = ((RenderState.DistortionCaps & ovrDistortionCap_FlipInput) != 0);
            const float left   = -1.0f; // We currently draw this in normalized device coordinates with an stereo translation
            const float top    = -1.1f; // applied as a vertex shader uniform. In the future when we have a more formal graphics
            const float right  =  1.0f; // API abstraction we may move this draw to an overlay layer or to a more formal
            const float bottom =  0.9f; // model/mesh scheme with a perspective projection.

            pVertices[0] = HASWVertex(left,  top,    0.f, Color(255, 255, 255, 255), 0.f, flip ? 1.f : 0.f);
            pVertices[1] = HASWVertex(left,  bottom, 0.f, Color(255, 255, 255, 255), 0.f, flip ? 0.f : 1.f);
            pVertices[2] = HASWVertex(right, top,    0.f, Color(255, 255, 255, 255), 1.f, flip ? 1.f : 0.f);
            pVertices[3] = HASWVertex(right, bottom, 0.f, Color(255, 255, 255, 255), 1.f, flip ? 0.f : 1.f);

            pVB->Unmap(pVertices);
        }
    }

    // We don't generate the vertex arrays here
    if(!VAO && SupportsVao)
    {
        OVR_ASSERT(!VAOInitialized);
        #ifdef OVR_OS_MAC
    		if(GLMajorVersion >= 3)
			{
				glGenVertexArrays(1, &VAO);
        	}
			else
			{
	            glGenVertexArraysAPPLE(1, &VAO);
			}
        #else
            glGenVertexArrays(1, &VAO);
        #endif
    }
}

void HSWDisplay::RenderInternal(ovrEyeType eye, const ovrTexture* eyeTexture)
{
    if(RenderEnabled && eyeTexture)
    {
        // Hack - Clear previous errors.
        glGetError();

        // We need to render to the eyeTexture with the texture viewport.
        // Setup rendering to the texture.
        ovrGLTexture* eyeTextureGL = const_cast<ovrGLTexture*>(reinterpret_cast<const ovrGLTexture*>(eyeTexture));
        OVR_ASSERT(eyeTextureGL->Texture.Header.API == ovrRenderAPI_OpenGL);

        const GLuint kVertexAttribCount = 3;
        const GLuint kSavedVertexAttribCount = 8;

        // Save state
        // To do: Converge this with the state setting/restoring functionality present in the distortion renderer.
        // Note that the glGet functions below will block until command buffer has completed.
        // glPushAttrib is deprecated, so we use glGet* to save/restore fixed-function settings.
        // https://www.opengl.org/sdk/docs/man/docbook4/xhtml/glGet.xml
        //
        GLint RenderModeSaved;
        glGetIntegerv(GL_RENDER_MODE, &RenderModeSaved);
        OVR_ASSERT(glGetError() == 0);
        OVR_ASSERT(RenderModeSaved == GL_RENDER); // Make sure it's not GL_SELECT or GL_FEEDBACK.

        GLint FrameBufferBindingSaved; // OpenGL renamed GL_FRAMEBUFFER_BINDING to GL_DRAW_FRAMEBUFFER_BINDING and adds GL_READ_FRAMEBUFFER_BINDING.
        glGetIntegerv(GL_FRAMEBUFFER_BINDING, &FrameBufferBindingSaved);
        OVR_ASSERT(glGetError() == 0);

        GLint TextureBinding2DSaved;
        glGetIntegerv(GL_TEXTURE_BINDING_2D, &TextureBinding2DSaved);
        OVR_ASSERT(glGetError() == 0);

        GLint ViewportSaved[4];
        glGetIntegerv(GL_VIEWPORT, ViewportSaved);
        OVR_ASSERT(glGetError() == 0);

        GLint PolygonModeSaved[2]; // Will be two (e.g. GL_FILL) values, one for the front mode and one for the mode.
        glGetIntegerv(GL_POLYGON_MODE, PolygonModeSaved);
        OVR_ASSERT(glGetError() == 0);

        GLdouble DepthRangeSaved[2];
        #if defined(OVR_OS_MAC)
            // Using glDepthRange as a conditional will always evaluate to true on Mac.
            glGetDoublev(GL_DEPTH_RANGE, DepthRangeSaved);
        #else
            GLfloat DepthRangefSaved[2];
            if(glDepthRange) // If we can use the double version (glDepthRangef may not be available)...
                glGetDoublev(GL_DEPTH_RANGE, DepthRangeSaved);
            else
                glGetFloatv(GL_DEPTH_RANGE, DepthRangefSaved);
        #endif
        OVR_ASSERT(glGetError() == 0);

        GLint DepthWriteMaskSaved;
        glGetIntegerv(GL_DEPTH_WRITEMASK, &DepthWriteMaskSaved);
        OVR_ASSERT(glGetError() == 0);

        GLint DepthTestSaved;
        glGetIntegerv(GL_DEPTH_TEST, &DepthTestSaved);
        OVR_ASSERT(glGetError() == 0);

        // No need to save/restore depth offset because we are neither testing nor writing depth.

        GLint CullFaceSaved;
        glGetIntegerv(GL_CULL_FACE, &CullFaceSaved);
        OVR_ASSERT(glGetError() == 0);

        GLint FrontFaceSaved;
        glGetIntegerv(GL_FRONT_FACE, &FrontFaceSaved);
        OVR_ASSERT(glGetError() == 0);

        GLint BlendSaved;
        glGetIntegerv(GL_BLEND, &BlendSaved);
        OVR_ASSERT(glGetError() == 0);

        GLint BlendSrcRGBSaved, BlendSrcAlphaSaved, BlendDstRGBSaved, BlendDstAlphaSaved;
        glGetIntegerv(GL_BLEND_SRC_RGB,   &BlendSrcRGBSaved);
        glGetIntegerv(GL_BLEND_SRC_ALPHA, &BlendSrcAlphaSaved);
        glGetIntegerv(GL_BLEND_DST_RGB,   &BlendDstRGBSaved);
        glGetIntegerv(GL_BLEND_DST_ALPHA, &BlendDstAlphaSaved);

        GLint DitherSaved;
        glGetIntegerv(GL_DITHER, &DitherSaved);
        OVR_ASSERT(glGetError() == 0);

        GLint RasterizerDiscardSaved;
        glGetIntegerv(GL_RASTERIZER_DISCARD, &RasterizerDiscardSaved);
        OVR_ASSERT(glGetError() == 0);

        GLint ScissorTestSaved;
        glGetIntegerv(GL_SCISSOR_TEST, &ScissorTestSaved);
        OVR_ASSERT(glGetError() == 0);

        GLint SampleMaskSaved = 0;
        if(((GLMajorVersion * 100) + GLMinorVersion) >= 302) // OpenGL 3.2 or later
        {
            glGetIntegerv(GL_SAMPLE_MASK, &SampleMaskSaved);
            OVR_ASSERT(glGetError() == 0);
        }

        GLint ColorWriteMaskSaved[4];
        glGetIntegerv(GL_COLOR_WRITEMASK, ColorWriteMaskSaved);

        GLint ArrayBufferBindingSaved;
        glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &ArrayBufferBindingSaved);
        OVR_ASSERT(glGetError() == 0);

        GLint ProgramSaved;
        glGetIntegerv(GL_CURRENT_PROGRAM, &ProgramSaved);
        OVR_ASSERT(glGetError() == 0);

        GLint ActiveTextureSaved;
        glGetIntegerv(GL_ACTIVE_TEXTURE, &ActiveTextureSaved);
        OVR_ASSERT(glGetError() == 0);

        GLint TextureBindingSaved;
        glGetIntegerv(GL_TEXTURE_BINDING_2D, &TextureBindingSaved);
        OVR_ASSERT(glGetError() == 0);

        // https://www.opengl.org/sdk/docs/man/docbook4/xhtml/glVertexAttribPointer.xml
        GLint   VertexAttribEnabledSaved[kSavedVertexAttribCount];
        GLint   VertexAttribSizeSaved[kSavedVertexAttribCount];
        GLint   VertexAttribTypeSaved[kSavedVertexAttribCount];
        GLint   VertexAttribNormalizedSaved[kSavedVertexAttribCount];
        GLint   VertexAttribStrideSaved[kSavedVertexAttribCount];
        GLvoid* VertexAttribPointerSaved[kSavedVertexAttribCount];
        for(GLuint i = 0; i < kSavedVertexAttribCount; i++)
        {
            glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &VertexAttribEnabledSaved[i]);

            glGetVertexAttribiv(i,       GL_VERTEX_ATTRIB_ARRAY_SIZE,       &VertexAttribSizeSaved[i]);
            glGetVertexAttribiv(i,       GL_VERTEX_ATTRIB_ARRAY_TYPE,       &VertexAttribTypeSaved[i]);
            glGetVertexAttribiv(i,       GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &VertexAttribNormalizedSaved[i]);
            glGetVertexAttribiv(i,       GL_VERTEX_ATTRIB_ARRAY_STRIDE,     &VertexAttribStrideSaved[i]);
            glGetVertexAttribPointerv(i, GL_VERTEX_ATTRIB_ARRAY_POINTER,    &VertexAttribPointerSaved[i]);

            OVR_ASSERT(glGetError() == 0);
        }

        GLint VertexArrayBindingSaved = 0;
        if (SupportsVao)
            glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &VertexArrayBindingSaved);

        //
        // End of save state

        // Load the graphics if not loaded already.
        if (!pTexture)
            LoadGraphics();

        // Calculate ortho projection.
        GetOrthoProjection(RenderState, OrthoProjection);

        // Set the rendering to be to the eye texture.
        glBindFramebuffer(GL_FRAMEBUFFER, FrameBuffer);
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, eyeTextureGL->OGL.TexId, 0);
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0); // We aren't using depth, as we currently want this to overwrite everything.
        // GLenum DrawBuffers[1] = { GL_COLOR_ATTACHMENT0 };
        // glDrawBuffers(OVR_ARRAY_COUNT(DrawBuffers), DrawBuffers);
        GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
        OVR_ASSERT(status == GL_FRAMEBUFFER_COMPLETE); OVR_UNUSED(status);
        OVR_ASSERT(glGetError() == 0);

        // Set up the viewport
        const GLint   x = (GLint)eyeTextureGL->Texture.Header.RenderViewport.Pos.x;
        const GLint   y = (GLint)eyeTextureGL->Texture.Header.RenderViewport.Pos.y; // Note that GL uses bottom-up coordinates.
        const GLsizei w = (GLsizei)eyeTextureGL->Texture.Header.RenderViewport.Size.w;
        const GLsizei h = (GLsizei)eyeTextureGL->Texture.Header.RenderViewport.Size.h;
        glViewport(x, y, w, h);
        OVR_ASSERT(glGetError() == 0);

        // Set fixed-function render states
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
        OVR_ASSERT(glGetError() == 0);
        #if defined(OVR_OS_MAC) // On Mac we are directly using OpenGL functions instead of function pointers.
            glDepthRange(0.0,  1.0);
        #else
            if(glDepthRange) // If we can use the double version (glDepthRangef may not be available)...
                glDepthRange(0.0,  1.0);
            else
                glDepthRangef(0.f,  1.f);
        #endif
        glDepthMask(GL_FALSE);
        glDisable(GL_DEPTH_TEST); // Disabling depth test should also have the effect of glDepthMask(GL_FALSE).
        glDisable(GL_CULL_FACE);
        glFrontFace(GL_CW);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glDisable(GL_DITHER);
        glDisable(GL_RASTERIZER_DISCARD);
        glDisable(GL_SCISSOR_TEST);
        if(((GLMajorVersion * 100) + GLMinorVersion) >= 302) // OpenGL 3.2 or later
            glDisable(GL_SAMPLE_MASK);
        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE);
        OVR_ASSERT(glGetError() == 0);

        // Enable the buffer and shaders we use.
        ShaderFill fill(pShaderSet);
        if(pTexture)
        {
            fill.SetTexture(0, pTexture);
            OVR_ASSERT(glGetError() == 0);
        }

        // Set shader uniforms.
        const float scale  = HSWDISPLAY_SCALE * ((RenderState.OurHMDInfo.HmdType == HmdType_DK1) ? 0.70f : 1.f);
        pShaderSet->SetUniform2f("Scale", scale, scale / 2.f); // X and Y scale. Y is a fixed proportion to X in order to give a certain aspect ratio.
        pShaderSet->SetUniform2f("PositionOffset", OrthoProjection[eye].GetTranslation().x, 0.0f);
        OVR_ASSERT(glGetError() == 0);

        // Set vertex attributes
        // To do: We must add support for vertext array objects (VAOs) here. When using an OpenGL 3.2+ core profile,
        // the application is required to use vertex array objects and glVertexAttribPointer will fail otherwise.

        if(SupportsVao)
        {
            OVR_ASSERT(VAO != 0);
            #ifdef OVR_OS_MAC
    			if(GLMajorVersion >= 3)
				{
					glBindVertexArray(VAO);
        		}
				else
				{
					glBindVertexArrayAPPLE(VAO);
				}
            #else
		    	glBindVertexArray(VAO);
            #endif
        }

        if(!VAOInitialized) // This executes for the case that VAO isn't supported.
        {
            glBindBuffer(GL_ARRAY_BUFFER, pVB->GLBuffer); // This must be called before glVertexAttribPointer is called below.
            OVR_ASSERT(glGetError() == 0);

            const GLuint shaderProgram = pShaderSet->Prog;
            GLint attributeLocationArray[kVertexAttribCount];

            attributeLocationArray[0] = glGetAttribLocation(shaderProgram, "Position");
            glVertexAttribPointer(attributeLocationArray[0], sizeof(Vector3f)/sizeof(float), GL_FLOAT,         false, sizeof(HASWVertex), reinterpret_cast<char*>(offsetof(HASWVertex, Pos)));

            attributeLocationArray[1] = glGetAttribLocation(shaderProgram, "Color");
            glVertexAttribPointer(attributeLocationArray[1], sizeof(Color)/sizeof(uint8_t),  GL_UNSIGNED_BYTE,  true, sizeof(HASWVertex), reinterpret_cast<char*>(offsetof(HASWVertex, C)));  // True because we want it to convert [0,255] to [0,1] for us.

            attributeLocationArray[2] = glGetAttribLocation(shaderProgram, "TexCoord");
            glVertexAttribPointer(attributeLocationArray[2], sizeof(float[2])/sizeof(float), GL_FLOAT,         false, sizeof(HASWVertex), reinterpret_cast<char*>(offsetof(HASWVertex, U)));
            OVR_ASSERT(glGetError() == 0);

            for (size_t i = 0; i < kVertexAttribCount; i++)
                glEnableVertexAttribArray((GLuint)i);
            OVR_ASSERT(glGetError() == 0);

            for (size_t i = kVertexAttribCount; i < kSavedVertexAttribCount; i++)
                glDisableVertexAttribArray((GLuint)i);
            OVR_ASSERT(glGetError() == 0);
        }

        fill.Set(Prim_TriangleStrip);
        OVR_ASSERT(glGetError() == 0);

        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
        OVR_ASSERT(glGetError() == 0);

        if(SupportsVao)
        {
            VAOInitialized = true;

            #ifdef OVR_OS_MAC
            	if(GLMajorVersion >= 3)
            	{
            	    glBindVertexArray(0);
            	}
            	else
            	{
            	    glBindVertexArrayAPPLE(0);
            	}
            #else
		    	glBindVertexArray(0);
            #endif
        }

        // Restore state
        // We restore the state in the reverse order that we saved it.
        // To do: Make the code below avoid changes that are effectively no-ops.
        //
        if (SupportsVao)
        {
#ifdef OVR_OS_MAC
            if(GLMajorVersion >= 3)
            {
                glBindVertexArray(VertexArrayBindingSaved);
            }
            else
            {
                glBindVertexArrayAPPLE(VertexArrayBindingSaved);
            }
#else
            glBindVertexArray(VertexArrayBindingSaved);
#endif
        }

        for (GLuint i = 0; i < kSavedVertexAttribCount; i++)
        {
            // We have a problem here: if the GL context was initialized with a core profile version 3.x or later, calls to glVertexAttribPointer can fail when there is no Vertex Array Object
            // in place. That case is possible here, and we don't have an easy means to detect that a core profile was specified and thus that the glVertexAttribPointer call below could fail.
            // Our current solution is to call glVertexAttribPointer only if vertex array objects are not supported. We cannot simply decide based on whether the given vertex attrib was enabled
            // or if there was a vertex array object installed. With our solution below a problem can occur when using OpenGL 3.x+ which supports VAOs, the user has vertex attrib pointers installed,
            // the currently installed VAO is 0, and the user is somehow dependent on us returning to the user with those vertex attrib pointers reinstalled.

            if (!SupportsVao || (VertexArrayBindingSaved != 0)) // If the OpenGL version is older or in core profile compatibility mode, or if there's a VAO currently installed...
            {
                glVertexAttribPointer(i, VertexAttribSizeSaved[i], VertexAttribTypeSaved[i], (GLboolean)VertexAttribNormalizedSaved[i], VertexAttribStrideSaved[i], VertexAttribPointerSaved[i]);

                if(VertexAttribEnabledSaved[i])
                    glEnableVertexAttribArray(i);
                else
                    glDisableVertexAttribArray(i);

                OVR_ASSERT(glGetError() == 0);
            }
        }

        glBindTexture(GL_TEXTURE_2D, TextureBindingSaved);
        glActiveTexture(ActiveTextureSaved);
        glUseProgram(ProgramSaved);
        glBindBuffer(GL_ARRAY_BUFFER, ArrayBufferBindingSaved);
        glColorMask((GLboolean)ColorWriteMaskSaved[0], (GLboolean)ColorWriteMaskSaved[1], (GLboolean)ColorWriteMaskSaved[2], (GLboolean)ColorWriteMaskSaved[3]);

        if(((GLMajorVersion * 100) + GLMinorVersion) >= 302) // OpenGL 3.2 or later
        {
            if(SampleMaskSaved)
                glEnable(GL_SAMPLE_MASK);
            else
                glDisable(GL_SAMPLE_MASK);
        }

        if(ScissorTestSaved)
            glEnable(GL_SCISSOR_TEST);
        else
            glDisable(GL_SCISSOR_TEST);

        if(RasterizerDiscardSaved)
            glEnable(GL_RASTERIZER_DISCARD);
        else
            glDisable(GL_RASTERIZER_DISCARD);

        if(DitherSaved)
            glEnable(GL_DITHER);
        else
            glDisable(GL_DITHER);

        glBlendFunc(BlendSrcRGBSaved, BlendDstRGBSaved); // What about BlendSrcAlphaSaved / BlendDstAlphaSaved?

        if(BlendSaved)
            glEnable(GL_BLEND);
        else
            glDisable(GL_BLEND);

        glFrontFace(FrontFaceSaved);

        if(CullFaceSaved)
            glEnable(GL_CULL_FACE);
        else
            glDisable(GL_CULL_FACE);

        if(DepthTestSaved)
            glEnable(GL_DEPTH_TEST);
        else
            glDisable(GL_DEPTH_TEST);

        glDepthMask(DepthWriteMaskSaved ? GL_TRUE : GL_FALSE);
        #if defined(OVR_OS_MAC) // On Mac we are directly using OpenGL functions instead of function pointers.
            glDepthRange(DepthRangeSaved[0], DepthRangeSaved[1]);
        #else
            if(glDepthRange) // If we can use the double version (glDepthRangef may not be available)...
                glDepthRange(DepthRangeSaved[0], DepthRangeSaved[1]);
            else
                glDepthRangef(DepthRangefSaved[0], DepthRangefSaved[1]);
        #endif
        // For OpenGL 3.x+ core profile mode, glPolygonMode allows only GL_FRONT_AND_BACK and not separate GL_FRONT and GL_BACK.
        glPolygonMode(GL_FRONT_AND_BACK, PolygonModeSaved[0]);
        glViewport(ViewportSaved[0], ViewportSaved[1], ViewportSaved[2], ViewportSaved[3]);
        glBindTexture(GL_TEXTURE_2D, TextureBinding2DSaved);
        glBindFramebuffer(GL_FRAMEBUFFER, FrameBufferBindingSaved);
        //glRenderMode(RenderModeSaved);

        OVR_ASSERT(glGetError() == 0);
        //
        // End of restore state
    }
}

}}} // namespace OVR::CAPI::GL


text:
package javolution.xml.internal.stream;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

import javolution.io.UTF8StreamWriter;
import javolution.lang.Realtime;
import javolution.text.CharArray;
import javolution.text.TextBuilder;
import javolution.xml.stream.XMLOutputFactory;
import javolution.xml.stream.XMLStreamException;
import javolution.xml.stream.XMLStreamWriter;

/**
 *
 This class represents an implementation of {@link XMLStreamWriter}.

 *
 *
 The writeCharacters methods will escape & , < and
 *     >. For attribute values, the writeAttribute methods will
 *     escape the above characters plus " and control characters.

 *
 * @author  Jean-Marie Dautelle
 * @version 4.0, September 4, 2006
 */
@Realtime
public final class XMLStreamWriterImpl implements XMLStreamWriter {

    /**
     * Holds the length of intermediate buffer.
     */
    private static final int BUFFER_LENGTH = 2048;

    /**
     * Holds the current nesting level.
     */
    private int _nesting = 0;

    /**
     * Holds the element qualified name (indexed per nesting level)
     */
    private TextBuilder[] _qNames = new TextBuilder[16];

    /**
     * Indicates if the current element is open.
     */
    private boolean _isElementOpen;

    /**
     * Indicates if the current element is an empty element.
     */
    private boolean _isEmptyElement;

    /**
     * Holds intermediate buffer.
     */
    private final char[] _buffer = new char[BUFFER_LENGTH];

    /**
     * Holds the namespace stack.
     */
    private final NamespacesImpl _namespaces = new NamespacesImpl();

    /**
     * Holds the buffer current index.
     */
    private int _index;

    /**
     * Holds repairing namespace property.
     */
    private boolean _isRepairingNamespaces;

    /**
     * Holds repairing prefix property.
     */
    private String _repairingPrefix = "ns";

    /**
     * Holds indentation property.
     */
    private String _indentation;

    /**
     * Holds line separator property.
     */
    private String _lineSeparator = "\n";

    /**
     * Holds current indentation level.
     */
    private int _indentationLevel;

    /**
     * Holds automatic empty elements  property.
     */
    private boolean _automaticEmptyElements;

    /**
     * Holds no empty element tag property.
     */
    private boolean _noEmptyElementTag;

    /**
     * Holds counter for automatic namespace generation.
     */
    private int _autoNSCount;

    /**
     * Indicates if the current object written is an attribute value.
     */
    private boolean _isAttributeValue;

    ////////////////////////
    // Temporary Settings //
    ////////////////////////

    /**
     * Holds the writer destination (null when unused).
     */
    private Writer _writer;

    /**
     * Holds the encoding  (null if N/A).
     */
    private String _encoding;

    /**
     * Holds the default writer for output streams.
     */
    private final UTF8StreamWriter _utf8StreamWriter = new UTF8StreamWriter();

    /**
     * Holds the factory (if any)
     */
    private final XMLOutputFactoryImpl _factory;

    /**
     * Default constructor.
     */
    public XMLStreamWriterImpl() {
        this(null);
    }

    /**
     * Factory-based constructor.
     */
    XMLStreamWriterImpl(XMLOutputFactoryImpl factory) {
        _factory = factory;
        for (int i = 0; i < _qNames.length;) {
            _qNames[i++] = new TextBuilder();
        }
    }

    /**
     * Sets the output stream destination for this XML stream writer
     * (UTF-8 encoding).
     *
     * @param out the output source with utf-8 encoding.
     */
    public void setOutput(OutputStream out) throws XMLStreamException {
        _utf8StreamWriter.setOutput(out);
        _encoding = "UTF-8";
        setOutput(_utf8StreamWriter);
    }

    /**
     * Sets the output stream destination and encoding for this XML stream
     * writer.
     *
     * @param out the output source.
     * @param encoding the associated encoding.
     * @throws XMLStreamException if the specified encoding is not supported.
     */
    public void setOutput(OutputStream out, String encoding)
            throws XMLStreamException {
        if (encoding.equals("UTF-8") || encoding.equals("utf-8")
                || encoding.equals("ASCII")) {
            setOutput(out); // Default encoding.
        } else {
            try {
                _encoding = encoding;
                setOutput(new OutputStreamWriter(out, encoding));
            } catch (UnsupportedEncodingException e) {
                throw new XMLStreamException(e);
            }
        }
    }

    /**
     * Sets the writer output destination for this XML stream writer.
     *
     * @param  writer the output destination writer.
     * @see    javolution.io.UTF8StreamWriter
     * @see    javolution.io.UTF8ByteBufferWriter
     * @see    javolution.io.AppendableWriter
     */
    public void setOutput(Writer writer) throws XMLStreamException {
        if (_writer != null)
            throw new IllegalStateException("Writer not closed or reset");
        _writer = writer;
    }

    /**
     * Requires this writer to create a new prefix when a namespace has none
     * (default false).
     *
     * @param isRepairingNamespaces true if namespaces
     *        are repaired; false otherwise.
     */
    public void setRepairingNamespaces(boolean isRepairingNamespaces) {
        _isRepairingNamespaces = isRepairingNamespaces;
    }

    /**
     * Specifies the prefix to be append by a trailing part
     * (a sequence number) in order to make it unique to be usable as
     * a temporary non-colliding prefix when repairing namespaces
     * (default "ns").
     *
     * @param repairingPrefix the prefix root.
     */
    public void setRepairingPrefix(String repairingPrefix) {
        _repairingPrefix = repairingPrefix;
    }

    /**
     * Specifies the indentation string; non-null indentation
     * forces the writer to write elements into separate lines
     * (default null).
     *
     * @param indentation the indentation string.
     */
    public void setIndentation(String indentation) {
        _indentation = indentation;
    }

    /**
     * Specifies the line separator (default "\n").
     *
     * @param lineSeparator the line separator string.
     */
    public void setLineSeparator(String lineSeparator) {
        _lineSeparator = lineSeparator;
    }

    /**
     * Requires this writer to automatically output empty elements when a
     * start element is immediately followed by matching end element
     * (default false).
     *
     * @param automaticEmptyElements true if start element
     *        immediately followed by end element results in an empty element
     *        beign written; false otherwise.
     */
    public void setAutomaticEmptyElements(boolean automaticEmptyElements) {
        _automaticEmptyElements = automaticEmptyElements;
    }

    /**
     * Prevent this writer from using empty element tags
     * (default false).
     *
     * @param noEmptyElementTag true if empty element tags
     *        are replaced by start/end elements with no content;
     *        false otherwise.
     */
    public void setNoEmptyElementTag(boolean noEmptyElementTag) {
        _noEmptyElementTag = noEmptyElementTag;
    }

    // Implements reusable.
    public void reset() {
        _automaticEmptyElements = false;
        _autoNSCount = 0;
        _encoding = null;
        _indentation = null;
        _indentationLevel = 0;
        _index = 0;
        _isAttributeValue = false;
        _isElementOpen = false;
        _isEmptyElement = false;
        _isRepairingNamespaces = false;
        _namespaces.reset();
        _nesting = 0;
        _noEmptyElementTag = false;
        _repairingPrefix = "ns";
        _utf8StreamWriter.reset();
        _writer = null;

        if (_factory != null)
            _factory.recycle(this);
    }

    // Implements XMLStreamWriter interface.
    public void writeStartElement(CharSequence localName)
            throws XMLStreamException {
        if (localName == null)
            throw new XMLStreamException("Local name cannot be null");
        writeNewElement(null, localName, null);
    }

    // Implements XMLStreamWriter interface.
    public void writeStartElement(CharSequence namespaceURI,
            CharSequence localName) throws XMLStreamException {
        if (localName == null)
            throw new XMLStreamException("Local name cannot be null");
        if (namespaceURI == null)
            throw new XMLStreamException("Namespace URI cannot be null");
        writeNewElement(null, localName, namespaceURI);
    }

    // Implements XMLStreamWriter interface.
    public void writeStartElement(CharSequence prefix, CharSequence localName,
            CharSequence namespaceURI) throws XMLStreamException {
        if (localName == null)
            throw new XMLStreamException("Local name cannot be null");
        if (namespaceURI == null)
            throw new XMLStreamException("Namespace URI cannot be null");
        if (prefix == null)
            throw new XMLStreamException("Prefix cannot be null");
        writeNewElement(prefix, localName, namespaceURI);
    }

    // Implements XMLStreamWriter interface.
    public void writeEmptyElement(CharSequence localName)
            throws XMLStreamException {
        writeStartElement(localName);
        _isEmptyElement = true;
    }

    // Implements XMLStreamWriter interface.
    public void writeEmptyElement(CharSequence namespaceURI,
            CharSequence localName) throws XMLStreamException {
        writeStartElement(namespaceURI, localName);
        _isEmptyElement = true;
    }

    // Implements XMLStreamWriter interface.
    public void writeEmptyElement(CharSequence prefix, CharSequence localName,
            CharSequence namespaceURI) throws XMLStreamException {
        writeStartElement(prefix, localName, namespaceURI);
        _isEmptyElement = true;
    }

    // Implements XMLStreamWriter interface.
    public void writeEndElement() throws XMLStreamException {
        if (_isElementOpen) { // Empty element.
            if (_isEmptyElement) { // Closes the empty element tag.
                closeOpenTag();
            } else { // Start element open.
                if (_automaticEmptyElements) { // Do as if empty element written.
                    _isEmptyElement = true;
                    closeOpenTag();
                    return;
                } else { // Closes the start element tag.
                    closeOpenTag();
                }
            }
        }
        if ((_indentation != null) && (_indentationLevel != _nesting - 1)) {
            // Do not indent if no change in indentation level
            // to avoid interfering with text only elements.
            writeNoEscape(_lineSeparator);
            for (int i = 1; i < _nesting; i++) {
                writeNoEscape(_indentation);
            }
        }

        write('<');
        write('/');
        writeNoEscape(_qNames[_nesting--]);
        write('>');
        _namespaces.pop();
    }

    // Implements XMLStreamWriter interface.
    public void writeEndDocument() throws XMLStreamException {
        if (_isElementOpen)
            closeOpenTag();
        while (_nesting > 0) { // Implicits closing of all elements.
            writeEndElement();
        }
        flush(); // Not mandatory but safer.
    }

    // Implements XMLStreamWriter interface.
    public void close() throws XMLStreamException {
        if (_writer != null) {
            if (_nesting != 0) { // Closes all elements.
                writeEndDocument();
            }
            flush();
        }
        reset(); // Explicit reset.
    }

    // Implements XMLStreamWriter interface.
    public void flush() throws XMLStreamException {
        flushBuffer();
        try {
            _writer.flush();
        } catch (IOException e) {
            throw new XMLStreamException(e);
        }
    }

    // Implements XMLStreamWriter interface.
    public void writeAttribute(CharSequence localName, CharSequence value)
            throws XMLStreamException {
        if (localName == null)
            throw new XMLStreamException("Local name cannot be null");
        if (value == null)
            throw new XMLStreamException("Value cannot be null");
        writeAttributeOrNamespace(null, null, localName, value);
    }

    // Implements XMLStreamWriter interface.
    public void writeAttribute(CharSequence namespaceURI,
            CharSequence localName, CharSequence value)
            throws XMLStreamException {
        if (localName == null)
            throw new XMLStreamException("Local name cannot be null");
        if (value == null)
            throw new XMLStreamException("Value cannot be null");
        if (namespaceURI == null)
            throw new XMLStreamException("Namespace URI cannot be null");
        writeAttributeOrNamespace(null, namespaceURI, localName, value);
    }

    // Implements XMLStreamWriter interface.
    public void writeAttribute(CharSequence prefix, CharSequence namespaceURI,
            CharSequence localName, CharSequence value)
            throws XMLStreamException {
        if (localName == null)
            throw new XMLStreamException("Local name cannot be null");
        if (value == null)
            throw new XMLStreamException("Value cannot be null");
        if (namespaceURI == null)
            throw new XMLStreamException("Namespace URI cannot be null");
        if (prefix == null)
            throw new XMLStreamException("Prefix cannot be null");
        writeAttributeOrNamespace(prefix, namespaceURI, localName, value);
    }

    // Implements XMLStreamWriter interface.
    public void writeNamespace(CharSequence prefix, CharSequence namespaceURI)
            throws XMLStreamException {
        if ((prefix == null) || (prefix.length() == 0)
                || _namespaces._xmlns.equals(prefix)) {
            prefix = _namespaces._defaultNsPrefix;
        }
        if (!_isElementOpen) // Check now as the actual writting is queued.
            throw new IllegalStateException("No open start element");
        _namespaces.setPrefix(prefix,
                (namespaceURI == null) ? _namespaces._nullNsURI : namespaceURI,
                true);
    }

    // Implements XMLStreamWriter interface.
    public void writeDefaultNamespace(CharSequence namespaceURI)
            throws XMLStreamException {
        writeNamespace(_namespaces._defaultNsPrefix, namespaceURI);
    }

    // Implements XMLStreamWriter interface.
    public void writeComment(CharSequence data) throws XMLStreamException {
        if (_isElementOpen)
            closeOpenTag();
        writeNoEscape("");
    }

    // Implements XMLStreamWriter interface.
    public void writeProcessingInstruction(CharSequence target)
            throws XMLStreamException {
        writeProcessingInstruction(target, _noChar);
    }

    private final CharArray _noChar = new CharArray("");

    // Implements XMLStreamWriter interface.
    public void writeProcessingInstruction(CharSequence target,
            CharSequence data) throws XMLStreamException {
        if (target == null)
            throw new XMLStreamException("Target cannot be null");
        if (data == null)
            throw new XMLStreamException("Data cannot be null");
        if (_isElementOpen)
            closeOpenTag();
        writeNoEscape("<?");
        writeNoEscape(target);
        write(' ');
        writeNoEscape(data);
        writeNoEscape(" ?>");
    }

    // Implements XMLStreamWriter interface.
    public void writeCData(CharSequence data) throws XMLStreamException {
        if (data == null)
            throw new XMLStreamException("Data cannot be null");
        if (_isElementOpen)
            closeOpenTag();
        writeNoEscape("<![CDATA[");
        writeNoEscape(data);
        writeNoEscape("]]>");
    }

    // Implements XMLStreamWriter interface.
    public void writeDTD(CharSequence dtd) throws XMLStreamException {
        if (dtd == null)
            throw new XMLStreamException("DTD cannot be null");
        if (_nesting > 0)
            throw new XMLStreamException(
                    "DOCTYPE declaration (DTD) when not in document root (prolog)");
        writeNoEscape(dtd);
    }

    // Implements XMLStreamWriter interface.
    public void writeEntityRef(CharSequence name) throws XMLStreamException {
        write('&');
        writeNoEscape(name);
        write(';');
    }

    // Implements XMLStreamWriter interface.
    public void writeStartDocument() throws XMLStreamException {
        writeStartDocument(null, null);
    }

    // Implements XMLStreamWriter interface.
    public void writeStartDocument(CharSequence version)
            throws XMLStreamException {
        writeStartDocument(null, version);
    }

    // Implements XMLStreamWriter interface.
    public void writeStartDocument(CharSequence encoding, CharSequence version)
            throws XMLStreamException {
        if (_nesting > 0)
            throw new XMLStreamException("Not in document root");
        writeNoEscape("<?xml version=\"");
        if (version != null) {
            writeNoEscape(version);
            write('"');
        } else { // Default to 1.0
            writeNoEscape("1.0\"");
        }
        if (encoding != null) {
            writeNoEscape(" encoding=\"");
            writeNoEscape(encoding);
            write('"');
        } else if (_encoding != null) { // Use init encoding (if any).
            writeNoEscape(" encoding=\"");
            writeNoEscape(_encoding);
            write('"');
        }
        writeNoEscape(" ?>");
    }

    // Implements XMLStreamWriter interface.
    public void writeCharacters(CharSequence text) throws XMLStreamException {
        if (_isElementOpen)
            closeOpenTag();
        if (text == null)
            return;
        writeEscape(text);
    }

    // Implements XMLStreamWriter interface.
    public void writeCharacters(char[] text, int start, int length)
            throws XMLStreamException {
        _tmpCharArray.setArray(text, start, length);
        writeCharacters(_tmpCharArray);
    }

    private final CharArray _tmpCharArray = new CharArray();

    // Implements XMLStreamWriter interface.
    public CharSequence getPrefix(CharSequence uri) throws XMLStreamException {
        return _namespaces.getPrefix(uri);
    }

    // Implements XMLStreamWriter interface.
    public void setPrefix(CharSequence prefix, CharSequence uri)
            throws XMLStreamException {
        _namespaces.setPrefix(prefix, (uri == null) ? _namespaces._nullNsURI
                : uri, false);
    }

    // Implements XMLStreamWriter interface.
    public void setDefaultNamespace(CharSequence uri) throws XMLStreamException {
        setPrefix(_namespaces._defaultNsPrefix, uri);
    }

    // Implements XMLStreamWriter interface.
    public Object getProperty(String name) throws IllegalArgumentException {
        if (name.equals(XMLOutputFactory.IS_REPAIRING_NAMESPACES)) {
            return new Boolean(_isRepairingNamespaces);
        } else if (name.equals(XMLOutputFactory.REPAIRING_PREFIX)) {
            return _repairingPrefix;
        } else if (name.equals(XMLOutputFactory.AUTOMATIC_EMPTY_ELEMENTS)) {
            return new Boolean(_automaticEmptyElements);
        } else if (name.equals(XMLOutputFactory.NO_EMPTY_ELEMENT_TAG)) {
            return new Boolean(_noEmptyElementTag);
        } else if (name.equals(XMLOutputFactory.INDENTATION)) {
            return _indentation;
        } else if (name.equals(XMLOutputFactory.LINE_SEPARATOR)) {
            return _lineSeparator;
        } else {
            throw new IllegalArgumentException("Property: " + name
                    + " not supported");
        }
    }

    // Writes a new start or empty element.
    private void writeNewElement(CharSequence prefix, CharSequence localName,
            CharSequence namespaceURI) throws XMLStreamException {

        // Close any open element and gets ready to write a new one.
        if (_isElementOpen)
            closeOpenTag();
        if (_indentation != null) {
            writeNoEscape(_lineSeparator);
            _indentationLevel = _nesting;
            for (int i = 0; i < _indentationLevel; i++) {
                writeNoEscape(_indentation);
            }
        }
        write('<');
        _isElementOpen = true;

        // Enters a new local scope.
        if (++_nesting >= _qNames.length)
            resizeElemStack();
        _namespaces.push();

        // Constructs qName.
        TextBuilder qName = _qNames[_nesting].clear();

        // Writes prefix if any.
        if ((namespaceURI != null)
                && (!_namespaces._defaultNamespace.equals(namespaceURI))) {
            if (_isRepairingNamespaces) { // Repairs prefix.
                prefix = getRepairedPrefix(prefix, namespaceURI);
            } else if (prefix == null) { // Retrieves prefix.
                prefix = getPrefix(namespaceURI);
                if (prefix == null)
                    throw new XMLStreamException("URI: " + namespaceURI
                            + " not bound and repairing namespaces disabled");
            }
            if (prefix.length() > 0) {
                qName.append(prefix);
                qName.append(':');
            }
        }
        qName.append(localName);
        writeNoEscape(qName);
    }

    // Writes a new attribute.
    private void writeAttributeOrNamespace(CharSequence prefix,
            CharSequence namespaceURI, CharSequence localName,
            CharSequence value) throws XMLStreamException {
        if (!_isElementOpen)
            throw new IllegalStateException("No open start element");
        write(' ');

        // Writes prefix if any.
        if ((namespaceURI != null)
                && (!_namespaces._defaultNamespace.equals(namespaceURI))) {
            if (_isRepairingNamespaces) { // Repairs prefix if current prefix is not correct.
                prefix = getRepairedPrefix(prefix, namespaceURI);
            } else if (prefix == null) {
                prefix = getPrefix(namespaceURI);
                if (prefix == null)
                    throw new XMLStreamException("URI: " + namespaceURI
                            + " not bound and repairing namespaces disabled");
            }
            if (prefix.length() > 0) {
                writeNoEscape(prefix);
                write(':');
            }
        }

        writeNoEscape(localName);
        write('=');
        write('"');
        _isAttributeValue = true;
        writeEscape(value);
        _isAttributeValue = false;
        write('"');
    }

    // Closes the current element (scope if empty element).
    private void closeOpenTag() throws XMLStreamException {

        // Writes namespaces now.
        writeNamespaces();

        // Closes the tag.
        _isElementOpen = false;
        if (_isEmptyElement) {
            if (_noEmptyElementTag) {
                write('<');
                write('/');
                writeNoEscape(_qNames[_nesting]);
                write('>');
            } else { // Use empty element tag.
                write('/');
                write('>');
            }
            _nesting--;
            _namespaces.pop();
            _isEmptyElement = false;
        } else {
            write('>');
        }
    }

    // Writes all namespaces, these include namespaces set but
    // not written in outer scope.
    private void writeNamespaces() throws XMLStreamException {
        int i0 = (_nesting > 1) ? _namespaces._namespacesCount[_nesting - 2]
                : NamespacesImpl.NBR_PREDEFINED_NAMESPACES;
        int i1 = _namespaces._namespacesCount[_nesting - 1];
        int i2 = _namespaces._namespacesCount[_nesting];
        for (int i = i0; i < i2; i++) {
            if (((_isRepairingNamespaces && (i < i1) && !_namespaces._prefixesWritten[i]))
                    || ((i >= i1) && _namespaces._prefixesWritten[i])) { // Write namespace.

                // In repairing mode, removes redondancy.
                if (_isRepairingNamespaces) {
                    CharArray prefix = _namespaces.getPrefix(
                            _namespaces._namespaces[i], i);
                    if (_namespaces._prefixes[i].equals(prefix))
                        continue; // Not necessary.
                } // Direct mode, just write them as requested (no check).

                // Writes namespace.
                if (_namespaces._prefixes[i].length() == 0) { // Default namespace.
                    writeAttributeOrNamespace(null, null, _namespaces._xmlns,
                            _namespaces._namespaces[i]);
                } else {
                    writeAttributeOrNamespace(_namespaces._xmlns,
                            _namespaces._xmlnsURI, _namespaces._prefixes[i],
                            _namespaces._namespaces[i]);
                }
            }
        }
    }

    // Returns the prefix for the specified namespace.
    private CharSequence getRepairedPrefix(CharSequence prefix,
            CharSequence namespaceURI) throws XMLStreamException {
        CharArray prefixForURI = _namespaces.getPrefix(namespaceURI);
        if ((prefixForURI != null)
                && ((prefix == null) || prefixForURI.equals(prefix)))
            return prefixForURI; // No repair needed.
        if ((prefix == null) || (prefix.length() == 0)) { // Creates new prefix.
            prefix = _autoPrefix.clear().append(_repairingPrefix)
                    .append(_autoNSCount++);
        }
        _namespaces.setPrefix(prefix, namespaceURI, true); // Map to namespace URI.
        return prefix;
    }

    private final TextBuilder _autoPrefix = new TextBuilder();

    // Resizes element stack  (same memory area as the writer).
    private void resizeElemStack() {
        final int oldLength = _qNames.length;
        final int newLength = oldLength * 2;

        // Resizes elements qNames stack.
        TextBuilder[] tmp = new TextBuilder[newLength];
        System.arraycopy(_qNames, 0, tmp, 0, oldLength);
        _qNames = tmp;
        for (int i = oldLength; i < newLength; i++) {
            _qNames[i] = new TextBuilder();
        }
    }

    // Writes methods.
    //

    private final void writeNoEscape(String str) throws XMLStreamException {
        write(str, 0, str.length(), false);
    }

    private final void writeNoEscape(TextBuilder tb) throws XMLStreamException {
        write(tb, 0, tb.length(), false);
    }

    private final void writeNoEscape(CharSequence csq)
            throws XMLStreamException {
        write(csq, 0, csq.length(), false);
    }

    private final void writeEscape(CharSequence csq) throws XMLStreamException {
        write(csq, 0, csq.length(), true);
    }

    private final void write(Object csq, int start, int length,
            boolean escapeMarkup) throws XMLStreamException {
        if (_index + length <= BUFFER_LENGTH) { // Enough buffer space.
            if (csq instanceof String) {
                ((String) csq).getChars(start, start + length, _buffer, _index);
            } else if (csq instanceof javolution.text.Text) {
                ((javolution.text.Text) csq).getChars(start, start + length,
                        _buffer, _index);
            } else if (csq instanceof javolution.text.TextBuilder) {
                ((javolution.text.TextBuilder) csq).getChars(start, start
                        + length, _buffer, _index);
            } else if (csq instanceof javolution.text.CharArray) {
                ((javolution.text.CharArray) csq).getChars(start, start
                        + length, _buffer, _index);
            } else {
                getChars((CharSequence) csq, start, start + length, _buffer,
                        _index);
            }
            if (escapeMarkup) {
                int end = _index + length;
                for (int i = _index; i < end; i++) {
                    char c = _buffer[i];
                    if ((c >= '?') || !isEscaped(c))
                        continue;
                    // Found character to escape.
                    _index = i;
                    flushBuffer();
                    writeDirectEscapedCharacters(_buffer, i, end);
                    return; // Done (buffer is empty).
                }
            }
            _index += length;

        } else { // Not enough remaining space.
            if (length <= BUFFER_LENGTH) { // Enough space if buffer emptied.
                flushBuffer();
                write(csq, start, length, escapeMarkup);
            } else {
                int half = length >> 1;
                write(csq, start, half, escapeMarkup);
                write(csq, start + half, length - half, escapeMarkup);
            }
        }
    }

    private static void getChars(CharSequence csq, int start, int end,
            char dest[], int destPos) {
        for (int i = start, j = destPos; i < end;) {
            dest[j++] = csq.charAt(i++);
        }
    }

    // The buffer must have been flushed prior to calling this method.
    private final void writeDirectEscapedCharacters(char[] chars, int start,
            int end) throws XMLStreamException {
        try {
            int blockStart = start;
            for (int i = start; i < end;) {
                char c = chars[i++];
                if ((c >= '?') || !isEscaped(c))
                    continue;
                // Flush already read characters (excluding escaped one).
                int blockLength = i - blockStart - 1;
                if (blockLength > 0) {
                    _writer.write(_buffer, blockStart, blockLength);
                }
                blockStart = i;
                switch (c) {
                    case '<':
                        _writer.write("<");
                        break;
                    case '>':
                        _writer.write(">");
                        break;
                    case '\'':
                        _writer.write("'");
                        break;
                    case '"':
                        _writer.write(""");
                        break;
                    case '&':
                        _writer.write("&");
                        break;
                    default:
                        _writer.write("&#");
                        _writer.write((char) ('0' + c / 10));
                        _writer.write((char) ('0' + c % 10));
                        _writer.write(';');
                }
            }
            // Flush the current block.
            int blockLength = end - blockStart;
            if (blockLength > 0) {
                _writer.write(_buffer, blockStart, blockLength);
            }
        } catch (IOException e) {
            throw new XMLStreamException(e);
        }
    }

    private boolean isEscaped(char c) {
        return ((c < ' ') && _isAttributeValue)
                || (c == '"' && _isAttributeValue) || (c == '<') || (c == '>')
                || (c == '&');
    }

    private final void write(char c) throws XMLStreamException {
        if (_index == BUFFER_LENGTH) {
            flushBuffer();
        }
        _buffer[_index++] = c;
    }

    private void flushBuffer() throws XMLStreamException {
        try {
            _writer.write(_buffer, 0, _index);
        } catch (IOException e) {
            throw new XMLStreamException(e);
        } finally {
            _index = 0;
        }
    }

}


text:
import {connect} from 'react-redux';
import ConfiguredScreen from '../components/ConfiguredScreen';
import {getClusterState} from '../reducers';

const mapStateToProps = ({setup}) => {
  return {
    clusterState: getClusterState(setup),
  };
};

export default connect(
  mapStateToProps
)(ConfiguredScreen);


text:
using System;

namespace System.Web.Util
{
	public class WorkItem
	{
		public WorkItem ()
		{
		}

		public static void Post (WorkItemCallback callback)
		{
			throw new PlatformNotSupportedException ("Not supported on mono");
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE markables SYSTEM "markables.dtd">
<markables xmlns="www.eml.org/NameSpaces/source">
<markable id="markable_100500312" span="word_789" mmax_level="source"  anaphref="empty"  sentiment_ref="empty" />
<markable id="markable_100500276" span="word_1058" mmax_level="source"  anaphref="markable_100500277"  sentiment_ref="empty" />
<markable id="markable_100500289" span="word_1105" mmax_level="source"  anaphref="empty"  sentiment_ref="empty" />
<markable id="markable_100500293" span="word_1210..word_1211" mmax_level="source"  anaphref="empty"  sentiment_ref="empty" />
<markable id="markable_100500296" span="word_1253..word_1258" mmax_level="source"  anaphref="empty"  sentiment_ref="empty" />
<markable id="markable_100500277" span="word_1056" mmax_level="source"  anaphref="empty"  sentiment_ref="empty" />
<markable id="markable_55" span="word_1094" mmax_level="source"  anaphref="empty"  sentiment_ref="empty" />
<markable id="markable_100500260" span="word_2062" mmax_level="source"  anaphref="empty"  sentiment_ref="empty" />
<markable id="markable_100500290" span="word_1105" mmax_level="source"  anaphref="empty"  sentiment_ref="sentiment:markable_100500283" />
<markable id="markable_100500303" span="word_702" mmax_level="source"  anaphref="empty"  sentiment_ref="empty" />
<markable id="markable_73" span="word_1611" mmax_level="source"  anaphref="empty"  sentiment_ref="empty" />
<markable id="markable_100500249" span="word_236" mmax_level="source"  anaphref="empty"  sentiment_ref="empty" />
<markable id="markable_21" span="word_341" mmax_level="source"  anaphref="empty"  sentiment_ref="empty" />
<markable id="markable_42" span="word_902" mmax_level="source"  anaphref="empty"  sentiment_ref="empty" />
</markables>


text:
package com.tristanpenman.chordial.core.shared

import java.net.InetSocketAddress

import akka.actor.ActorRef

final case class NodeInfo(id: Long, addr: InetSocketAddress, ref: ActorRef)


text:
Project: /_project.yaml
Book: /_book.yaml

# Rules

The Bazel ecosystem has a growing and evolving set of rules to support popular
languages and packages. Much of Bazel's strength comes from the ability to
[define new rules](/rules/concepts) that can be used by others.

This page describes the recommended, native, and non-native Bazel rules.

## Recommended rules {:#recommended-rules}

Here is a selection of recommended rules:

* [Android](/docs/bazel-and-android)
* [Boost](https://github.com/nelhage/rules_boost){: .external}
* [C / C++](/docs/bazel-and-cpp)
* [Docker](https://github.com/bazelbuild/rules_docker){: .external}
* [Go](https://github.com/bazelbuild/rules_go){: .external}
* [Haskell](https://github.com/tweag/rules_haskell){: .external}
* [Java](/docs/bazel-and-java)
* [JavaScript / NodeJS](https://github.com/bazelbuild/rules_nodejs){: .external}
* [Kubernetes](https://github.com/bazelbuild/rules_k8s){: .external}
* [Maven dependency management](https://github.com/bazelbuild/rules_jvm_external){: .external}
* [Objective C](/docs/bazel-and-apple)
* [Package building](https://github.com/bazelbuild/rules_pkg){: .external}
* [Protocol Buffers](https://github.com/bazelbuild/rules_proto#protobuf-rules-for-bazel){: .external}
* [Python](https://github.com/bazelbuild/rules_python){: .external}
* [Scala](https://github.com/bazelbuild/rules_scala){: .external}
* [Shell](/reference/be/shell)
* [Webtesting](https://github.com/bazelbuild/rules_webtesting){: .external} (Webdriver)

The repository [Skylib](https://github.com/bazelbuild/bazel-skylib){: .external} contains
additional functions that can be useful when writing new rules and new
macros.

The rules above were reviewed and follow our
[requirements for recommended rules](/contribute/recommended-rules){: .external}.
Contact the respective rule set's maintainers regarding issues and feature
requests.

To find more Bazel rules, use a search engine, take a look on
[awesomebazel.com](https://awesomebazel.com/){: .external}, or search on
[GitHub](https://github.com/search?o=desc&q=bazel+rules&s=stars&type=Repositories){: .external}.

## Native rules that do not apply to a specific programming language

Native rules are shipped with the Bazel binary, they are always available in
BUILD files without a `load` statement.

* Extra actions
  - [`extra_action`](/reference/be/extra-actions#extra_action)
  - [`action_listener`](/reference/be/extra-actions#action_listener)
* General
  - [`filegroup`](/reference/be/general#filegroup)
  - [`genquery`](/reference/be/general#genquery)
  - [`test_suite`](/reference/be/general#test_suite)
  - [`alias`](/reference/be/general#alias)
  - [`config_setting`](/reference/be/general#config_setting)
  - [`genrule`](/reference/be/general#genrule)
* Platform
  - [`constraint_setting`](/reference/be/platform#constraint_setting)
  - [`constraint_value`](/reference/be/platform#constraint_value)
  - [`platform`](/reference/be/platform#platform)
  - [`toolchain`](/reference/be/platform#toolchain)
  - [`toolchain_type`](/reference/be/platform#toolchain_type)
* Workspace
  - [`bind`](/reference/be/workspace#bind)
  - [`local_repository`](/reference/be/workspace#local_repository)
  - [`new_local_repository`](/reference/be/workspace#new_local_repository)
  - [`xcode_config`](/reference/be/objective-c#xcode_config)
  - [`xcode_version`](/reference/be/objective-c#xcode_version)

## Embedded non-native rules {:#embedded-rules}

Bazel also embeds additional rules written in [Starlark](/rules/language). Those can be loaded from
the `@bazel_tools` built-in external repository.

* Repository rules
  - [`git_repository`](/rules/lib/repo/git#git_repository)
  - [`new_git_repository`](/rules/lib/repo/git#new_git_repository)
  - [`http_archive`](/rules/lib/repo/http#http_archive)
  - [`http_file`](/rules/lib/repo/http#http_archive)
  - [`http_jar`](/rules/lib/repo/http#http_jar)
  - [Utility functions on patching](/rules/lib/repo/utils)


text:
.. spelling::

    chardet

.. index::
  single: python ; pip_chardet

.. _pkg.pip_chardet:

pip_chardet
===========

- `Official <https://chardet.readthedocs.io>`__
- `Official GitHub <https://github.com/chardet/chardet>`__
- `PyPI <https://pypi.org/project/chardet>`__
- `Example <https://github.com/ruslo/hunter/blob/master/examples/pip_chardet/CMakeLists.txt>`__

.. literalinclude:: /../examples/pip_chardet/CMakeLists.txt
  :language: cmake
  :start-after: # DOCUMENTATION_START {
  :end-before: # DOCUMENTATION_END }


text:
namespace device {
namespace internal {

template <class T>
struct ScopedGenericArObject {
  static T InvalidValue() { return nullptr; }

  // Implementation not provided by design - this will cause linker errors if a
  // ScopedArCoreObject<T> is used for T that does not have a template
  // specialization defining the Free() method.
  static void Free(T object);
};

template <>
void inline ScopedGenericArObject<ArSession*>::Free(ArSession* ar_session) {
  ArSession_destroy(ar_session);
}

template <>
void inline ScopedGenericArObject<ArFrame*>::Free(ArFrame* ar_frame) {
  ArFrame_destroy(ar_frame);
}

template <>
void inline ScopedGenericArObject<ArConfig*>::Free(ArConfig* ar_config) {
  ArConfig_destroy(ar_config);
}

template <>
void inline ScopedGenericArObject<ArCameraConfig*>::Free(
    ArCameraConfig* ar_camera_config) {
  ArCameraConfig_destroy(ar_camera_config);
}

template <>
void inline ScopedGenericArObject<ArCameraConfigFilter*>::Free(
    ArCameraConfigFilter* ar_camera_config_filter) {
  ArCameraConfigFilter_destroy(ar_camera_config_filter);
}

template <>
void inline ScopedGenericArObject<ArCameraConfigList*>::Free(
    ArCameraConfigList* ar_camera_config_list) {
  ArCameraConfigList_destroy(ar_camera_config_list);
}

template <>
void inline ScopedGenericArObject<ArPose*>::Free(ArPose* ar_pose) {
  ArPose_destroy(ar_pose);
}

template <>
void inline ScopedGenericArObject<ArTrackable*>::Free(
    ArTrackable* ar_trackable) {
  ArTrackable_release(ar_trackable);
}

template <>
void inline ScopedGenericArObject<ArPlane*>::Free(ArPlane* ar_plane) {
  // ArPlane itself doesn't have a method to decrease refcount, but it is an
  // instance of ArTrackable & we have to use ArTrackable_release.
  ArTrackable_release(ArAsTrackable(ar_plane));
}

template <>
void inline ScopedGenericArObject<ArImage*>::Free(ArImage* ar_image) {
  ArImage_release(ar_image);
}

template <>
void inline ScopedGenericArObject<ArAugmentedImageDatabase*>::Free(
    ArAugmentedImageDatabase* ar_augmented_image_database) {
  ArAugmentedImageDatabase_destroy(ar_augmented_image_database);
}

template <>
void inline ScopedGenericArObject<ArLightEstimate*>::Free(
    ArLightEstimate* ar_light_estimate) {
  ArLightEstimate_destroy(ar_light_estimate);
}

template <>
void inline ScopedGenericArObject<ArAnchorList*>::Free(
    ArAnchorList* ar_anchor_list) {
  ArAnchorList_destroy(ar_anchor_list);
}

template <>
void inline ScopedGenericArObject<ArCameraIntrinsics*>::Free(
    ArCameraIntrinsics* ar_camera_intrinsics) {
  ArCameraIntrinsics_destroy(ar_camera_intrinsics);
}

template <>
void inline ScopedGenericArObject<ArAnchor*>::Free(ArAnchor* ar_anchor) {
  ArAnchor_release(ar_anchor);
}

template <>
void inline ScopedGenericArObject<ArTrackableList*>::Free(
    ArTrackableList* ar_trackable_list) {
  ArTrackableList_destroy(ar_trackable_list);
}

template <>
void inline ScopedGenericArObject<ArCamera*>::Free(ArCamera* ar_camera) {
  // Do nothing - ArCamera has no destroy method and is managed by ArCore.
}

template <>
void inline ScopedGenericArObject<ArHitResultList*>::Free(
    ArHitResultList* ar_hit_result_list) {
  ArHitResultList_destroy(ar_hit_result_list);
}

template <>
void inline ScopedGenericArObject<ArHitResult*>::Free(
    ArHitResult* ar_hit_result) {
  ArHitResult_destroy(ar_hit_result);
}

template <class T>
using ScopedArCoreObject = base::ScopedGeneric<T, ScopedGenericArObject<T>>;

}  // namespace internal
}  // namespace device

#endif  // DEVICE_VR_ANDROID_ARCORE_SCOPED_ARCORE_OBJECTS_H_


text:
@interface StatusTableViewController : UITableViewController
@property TCPConnection* tcpConnection;
@end


text:
<?php

namespace Sonata\ClassificationBundle\Document;

use Sonata\ClassificationBundle\Model\Context as ModelContext;

abstract class BaseContext extends ModelContext
{
    public function prePersist()
    {
        $this->setCreatedAt(new \DateTime());
        $this->setUpdatedAt(new \DateTime());
    }
}


text:
import * as React from 'react'

interface DelayProps {
  ms?: number
  alwaysRender?: boolean
  children: (ready?: boolean) => JSX.Element
}

export default function Delay({ ms = 1000, alwaysRender = false, children }: DelayProps) {
  const [ready, setReady] = React.useState(false)
  React.useEffect(() => {
    const timeout = setTimeout(() => setReady(true), ms)
    return () => clearTimeout(timeout)
    // run this only once with initial `ms` value, ignore changes
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  // eslint-disable-next-line no-nested-ternary
  return alwaysRender ? children(ready) : ready ? children() : null
}


text:
namespace SuccincT.Unions
{
    /// <summary>
    /// valueless struct that encapsulates the "none" literal used by various Succinct types.
    /// </summary>
    public readonly struct None
    {
        // ReSharper disable once InconsistentNaming
        public static None none { get; } = default;

        public override string ToString() => "!none!";

        public override bool Equals(object obj) => obj is None;

        public override int GetHashCode() => 0;

        public static bool operator ==(None left, None right) => true;

        public static bool operator !=(None left, None right) => false;
    }
}


text:
RSpec.describe ROM::Changeset::Update do
  include_context "changeset / database"
  include_context "changeset / relations"

  subject(:changeset) do
    users.by_pk(jane[:id]).changeset(:update, data)
  end

  let(:data) do
    {name: "Jane Doe"}
  end

  let!(:jane) do
    users.command(:create).call(name: "Jane")
  end

  let!(:joe) do
    users.command(:create).call(name: "Joe")
  end

  it "has data" do
    expect(changeset.to_h).to eql(name: "Jane Doe")
  end

  it "has diff" do
    expect(changeset.diff).to eql(name: "Jane Doe")
  end

  it "has relation" do
    expect(changeset.relation.one).to eql(users.by_pk(jane[:id]).one)
  end

  it "can be commited" do
    expect(changeset.commit.to_h).to eql(id: 1, name: "Jane Doe")
    expect(users.by_pk(joe[:id]).one).to eql(joe)
  end
end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace WebApplication.Entities
{
    public class Category
    {
      [Key]
      public int id_category { get; set; }

      public  string categoryName { get; set; }

    }
}


text:
package com.spun.util;

import com.spun.util.logger.SimpleLogger;

import javax.swing.RepaintManager;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintUtils implements Printable
{
  private Component componentToBePrinted;
  public static void printComponent(Component c)
  {
    printComponent(c, true);
  }
  public static void printComponent(Component c, boolean prompt)
  {
    new PrintUtils(c).print(prompt);
  }
  public PrintUtils(Component componentToBePrinted)
  {
    this.componentToBePrinted = componentToBePrinted;
  }
  public void print(boolean prompt)
  {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    PageFormat format = printJob.defaultPage();
    Paper paper = format.getPaper();
    paper.setImageableArea(18, 0, 180, 840);// Paper format for receipt printer
    format.setPaper(paper);
    printJob.setPrintable(this, format);
    if (!prompt || printJob.printDialog())
    {
      try
      {
        printJob.print();
      }
      catch (PrinterException pe)
      {
        SimpleLogger.variable("Error printing: " + pe);
      }
    }
  }
  public int print(Graphics g, PageFormat pageFormat, int pageIndex)
  {
    if (pageIndex > 0)
    {
      return NO_SUCH_PAGE;
    }
    else
    {
      Graphics2D g2d = (Graphics2D) g;
      SimpleLogger.variable("width = " + pageFormat.getWidth());
      SimpleLogger.variable("image width = " + pageFormat.getImageableWidth());
      SimpleLogger.variable("getHeight() = " + pageFormat.getHeight());
      g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
      disableDoubleBuffering(componentToBePrinted);
      componentToBePrinted.paint(g2d);
      enableDoubleBuffering(componentToBePrinted);
      return PAGE_EXISTS;
    }
  }
  public static void disableDoubleBuffering(Component c)
  {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
  }
  public static void enableDoubleBuffering(Component c)
  {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);
  }
}


text:
namespace Global.Contracts.Actions
{
    using Statistics;

    public interface IPass
    {
        bool Pass(IDefenseStats enemy);
    }
}


text:
namespace RedBlackAvl.Common
{
    public enum Color
    {
        Red,

        Black
    }
}


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

<title>Uses of Class org.apache.cassandra.utils.CounterId (apache-cassandra API)</title>
<meta name="date" content="2016-04-09">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.cassandra.utils.CounterId

Packages that use CounterId

Package
Description

org.apache.cassandra.db.context

org.apache.cassandra.utils

Uses of CounterId in org.apache.cassandra.db.context

Methods in org.apache.cassandra.db.context that return CounterId

Modifier and Type
Method and Description

CounterId
CounterContext.ContextState.getCounterId()

Methods in org.apache.cassandra.db.context with parameters of type CounterId

Modifier and Type
Method and Description

java.nio.ByteBuffer
CounterContext.createGlobal(CounterId id,
            long clock,
            long count)

Creates a counter context with a single global, 2.1+ shard (a result of increment).

java.nio.ByteBuffer
CounterContext.createRemote(CounterId id,
            long clock,
            long count)

Creates a counter context with a single remote shard.

int
CounterContext.findPositionOf(java.nio.ByteBuffer context,
              CounterId id)

Finds the position of a shard with the given id within the context (via binary search).

ClockAndCount
CounterContext.getClockAndCountOf(java.nio.ByteBuffer context,
                  CounterId id)

Returns the clock and the count associated with the given counter id, or (0, 0) if no such shard is present.

void
CounterContext.ContextState.writeGlobal(CounterId id,
           long clock,
           long count)

void
CounterContext.ContextState.writeLocal(CounterId id,
          long clock,
          long count)

void
CounterContext.ContextState.writeRemote(CounterId id,
           long clock,
           long count)

Uses of CounterId in org.apache.cassandra.utils

Methods in org.apache.cassandra.utils that return CounterId

Modifier and Type
Method and Description

static CounterId
CounterId.fromInt(int n)

Function for test purposes, do not use otherwise.

static CounterId
CounterId.generate()

static CounterId
CounterId.getLocalId()

static CounterId
CounterId.wrap(java.nio.ByteBuffer id)

static CounterId
CounterId.wrap(java.nio.ByteBuffer bb,
    int offset)

Methods in org.apache.cassandra.utils with parameters of type CounterId

Modifier and Type
Method and Description

int
CounterId.compareTo(CounterId o)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2016 The Apache Software Foundation


text:
package com.sksamuel.scapegoat.inspections.collections

import com.sksamuel.scapegoat._

/** @author Stephen Samuel */
class FilterDotHeadOption extends Inspection {

  def inspector(context: InspectionContext): Inspector = new Inspector(context) {
    override def postTyperTraverser = Some apply new context.Traverser {

      import context.global._

      override def inspect(tree: Tree): Unit = {
        tree match {
          case Select(Apply(Select(_, TermName("filter")), _), TermName("headOption")) =>
            context.warn("filter().headOption instead of find()", tree.pos, Levels.Info,
              ".filter(x => Bool).headOption can be replaced with find(x => Bool): " + tree.toString().take(500), FilterDotHeadOption.this)
          case _ => continue(tree)
        }
      }
    }
  }
}


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef CONF_PMC_CLOCK_SWITCHING_EXAMPLE_H_INCLUDED
#define CONF_PMC_CLOCK_SWITCHING_EXAMPLE_H_INCLUDED

#define BUTTON_NAME  "USRPB1"

#endif /* CONF_PMC_CLOCK_SWITCHING_EXAMPLE_H_INCLUDED */