text:
var shared = require('./lib/shared');
var TweetFilter = require('../lib/filter')
var filter = new TweetFilter(TweetFilter.getFiltersFromFiles("filters/english"))

var matches = [
    'help me go vegan',
    'help me become vegan',
    'help me be vegan',
    'i want to go vegan',
    'i want to become vegan',
    'i want to be vegan',
    'i wanna go vegan',
    'i wanna be vegan',
    "I would like to go vegan",
    "I want to be a vegan",
    "I wanna become vegan",
    "I wanna be a vegan",
    "I really wanna be vegan",
    "I should go vegan",
    "I probably should go vegan",
    "I need help going vegan",
    "I want help going vegan",
    "I really need help staying vegan",
    "I think that i want to go vegan",
    "I think i should go vegan",
    "i will need help going vegan",
    "i do need help going vegan",
    "i definitely want to go vegan",
    "i definately want to go vegan",
    "i honestly would like to go vegan",
    "i truly want to try going vegan",
    "i wanna try becoming a vegan",
    "i'm thinking about going vegan",
    "i'm thinking of going vegan",
    "im thinking about becoming vegan",
    "i am considering being a vegan",
    "i'm mulling over becoming vegan",
    "i want to go #vegan",
    "i. want. to. go. vegan.",
    "i.. want  to go ... vegan",
    "i wish i was vegan",
    "i wish i were vegan",
    "i can see myself becoming a vegan someday",
    "i could definitely picture myself going vegan",
    "\"i like to quote\" but i want to go vegan and \"stuff\"",
    "i'm planning on going vegan",
    "i'm totally thinking about becoming a vegan",
];

var falsePositives = [
    "I do not want to go vegan",
    "I should be a vegan", // this phrasing more than likely isn't about going vegan long-term (e.g. I should be a vegan for Halloween)
    "Don't tell me I should go vegan",
    "\"I want to go vegan\"",
    "\"stuff\" \"I want to go vegan\" \"stuff\"",
    "\"stuff\" \" I want to go vegan \" \"stuff\"",
    "\"unbalanced\"\" but i want to go vegan and \"quotes\"",
];

exports.matches = function(test) {
    shared.testMatches(test, matches, filter);
    test.done();
}

exports.falsePositives = function(test) {
    shared.testFalsePositives(test, falsePositives, filter);
    // matching phrases with the word 'vegetarian' subbed for 'vegan' should not match
    matches.forEach(function(match) {
        var falsePositive = match.replace(/vegan/g, 'vegetarian');
        test.ok(!filter.matches(falsePositive), "'" + falsePositive + "' should not match");
    })
    test.done();
}


text:
//
//  SettingsViewController.m
//  FontViewer
//
//  Created by Victor Wibisono on 28/09/13.
//  Copyright (c) 2013 Victor Wibisono. All rights reserved.
//

#import "SettingsViewController.h"
#import "AppDelegate.h"

@interface SettingsViewController ()

@property (nonatomic, strong) NSString *currentAlignmentSettingObject;
@property (nonatomic, strong) NSString *currentSortByObject;
@property (nonatomic, strong) UISwitch *reverseCharacterSwitch;
@property (nonatomic, strong) UISwitch *ascendingSwitch;
@property (nonatomic, strong) NSMutableDictionary *settingsDictionary;

@property NSInteger textAlignmentIndex;
@property NSInteger sortByIndex;
@property BOOL reverseCharacterBool;
@property BOOL ascendingBool;

@end

@implementation SettingsViewController

NSString *_textAlignmentString = @"Text alignment";
NSString *_characterString = @"Characters";
NSString *_sortByString = @"Sort by";
NSString *_ascendingString = @"Sort type";
NSString *_revertString = @"Revert";

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadDataFromUserDefaults];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return [[self getSections] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger numberOfRows = 0;

    if ([self tableView:self.tableView titleForHeaderInSection:section] == _textAlignmentString) {
        numberOfRows = [[self getAlignmentRows] count];
    } else if ([self tableView:self.tableView titleForHeaderInSection:section] == _characterString) {
        numberOfRows = [[self getCharacterRows] count];
    } else if ([self tableView:self.tableView titleForHeaderInSection:section] == _sortByString) {
        numberOfRows = [[self getSortByRows] count];
    } else if ([self tableView:self.tableView titleForHeaderInSection:section] == _ascendingString) {
        numberOfRows = [[self getSortingRows] count];
    } else if ([self tableView:self.tableView titleForHeaderInSection:section] == _revertString) {
        numberOfRows = [[self getRevertRows] count];
    }

    // Return the number of rows in the section.
    return numberOfRows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    NSString *labelString;
    if ([self tableView:self.tableView titleForHeaderInSection:indexPath.section] == _textAlignmentString) {
        // Get text alignment index value from NSUserDefaults.
        // If there is none then left is the default.
        // Put that into an integer somewhere.
        labelString = [[self getAlignmentRows] objectAtIndex:indexPath.row];
    } else if ([self tableView:self.tableView titleForHeaderInSection:indexPath.section] == _characterString) {
        labelString = [[self getCharacterRows] objectAtIndex:indexPath.row];
    } else if ([self tableView:self.tableView titleForHeaderInSection:indexPath.section] == _sortByString) {
        labelString = [[self getSortByRows] objectAtIndex:indexPath.row];
    } else if ([self tableView:self.tableView titleForHeaderInSection:indexPath.section] == _ascendingString) {
        labelString = [[self getSortingRows] objectAtIndex:indexPath.row];
    } else if ([self tableView:self.tableView titleForHeaderInSection:indexPath.section] == _revertString) {
        labelString = [[self getRevertRows] objectAtIndex:indexPath.row];
    }

    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // Setting the label of the cell
    // This has to be out of the cell == nil if clause so that the label will be set even if they can reuse existing cell.
    cell.textLabel.text = labelString;

    if ([cell.textLabel.text isEqualToString: @"Reverse characters"]) {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        _reverseCharacterSwitch = [[UISwitch alloc] init];
        _reverseCharacterSwitch.on = _reverseCharacterBool;
        [_reverseCharacterSwitch addTarget:self action:@selector(reverseCharacterSwitchSelected:) forControlEvents:UIControlEventValueChanged];
        cell.accessoryView = _reverseCharacterSwitch;

    } else if ([cell.textLabel.text isEqualToString:@"Ascending"]) {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        _ascendingSwitch = [[UISwitch alloc] init];
        _ascendingSwitch.on = _ascendingBool;
        [_ascendingSwitch addTarget:self action:@selector(ascendingSwitchSelected:) forControlEvents:UIControlEventValueChanged];
        cell.accessoryView = _ascendingSwitch;
    }

    [self configureCell:cell atIndexPath:indexPath];

    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [[self getSections] objectAtIndex:section];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - UISwitch Selection

- (void)reverseCharacterSwitchSelected:(UISwitch *)sender
{
    [[NSUserDefaults standardUserDefaults] setBool:sender.on forKey:@"ReverseCharacterBool"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)ascendingSwitchSelected:(UISwitch *)sender
{
    [[NSUserDefaults standardUserDefaults] setBool:sender.on forKey:@"SortAscendingBool"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (indexPath.section == 0) {
        // Section: Text alignment
        // Behaviour: Exclusive list checkmark.
        NSInteger textAlignmentIndex = [[self getAlignmentRows] indexOfObject:_currentAlignmentSettingObject];
        if (textAlignmentIndex == indexPath.row) {
            return;
        }

        NSIndexPath *oldIndexPath = [NSIndexPath indexPathForRow:textAlignmentIndex inSection:indexPath.section];
        UITableViewCell *newCell = [self.tableView cellForRowAtIndexPath:indexPath];
        if (newCell.accessoryType == UITableViewCellAccessoryNone) {
            newCell.accessoryType = UITableViewCellAccessoryCheckmark;
            _currentAlignmentSettingObject = [[self getAlignmentRows] objectAtIndex:indexPath.row];

            // Saves currently selected text alignment index to NSUserDefaults.
            [[NSUserDefaults standardUserDefaults] setInteger:indexPath.row forKey:@"TextAlignmentIndex"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }

        UITableViewCell *oldCell = [self.tableView cellForRowAtIndexPath:oldIndexPath];
        if (oldCell.accessoryType == UITableViewCellAccessoryCheckmark) {
            oldCell.accessoryType = UITableViewCellAccessoryNone;
        }

    } else if (indexPath.section == 2) {
        // Section: Sort by
        // Behaviour: Exclusive list checkmark.
        NSInteger sortByIndex = [[self getSortByRows] indexOfObject:self.currentSortByObject];
        if (sortByIndex == indexPath.row) {
            return;
        }

        NSIndexPath *oldIndexPath = [NSIndexPath indexPathForRow:sortByIndex inSection:indexPath.section];
        UITableViewCell *newCell = [self.tableView cellForRowAtIndexPath:indexPath];
        if (newCell.accessoryType == UITableViewCellAccessoryNone) {
            newCell.accessoryType = UITableViewCellAccessoryCheckmark;
            self.currentSortByObject = [[self getSortByRows] objectAtIndex:indexPath.row];

            // Saves currently selected sort by index to NSUserDefaults.
            [[NSUserDefaults standardUserDefaults] setInteger:indexPath.row forKey:@"SortByIndex"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }

        UITableViewCell *oldCell = [self.tableView cellForRowAtIndexPath:oldIndexPath];
        if (oldCell.accessoryType == UITableViewCellAccessoryCheckmark) {
            oldCell.accessoryType = UITableViewCellAccessoryNone;
        }

    } else if (indexPath.section == 4) {
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
        [AppDelegate setDefaultSettings];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}

// Configuring cells based on data from NSUserDefaults
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;

    _textAlignmentIndex = [[NSUserDefaults standardUserDefaults] integerForKey:@"TextAlignmentIndex"];

    // Section 0: Text Alignment
    if (section == 0) {
        if (row == _textAlignmentIndex) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            _currentAlignmentSettingObject = [[self getAlignmentRows] objectAtIndex:row];
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }

    } else if (section == 2) {
        // Section 2: Sort By
        if (row == _sortByIndex) {
            _currentSortByObject = [[self getSortByRows] objectAtIndex:row];
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    } else if (section == 4) {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
}

#pragma mark - Load data from user defaults

- (void)loadDataFromUserDefaults {
    // Load text alignment index value.
    _textAlignmentIndex = [[NSUserDefaults standardUserDefaults] integerForKey:@"TextAlignmentIndex"];

    // Load reverse character boolean value.
    _reverseCharacterBool = [[NSUserDefaults standardUserDefaults] boolForKey:@"ReverseCharacterBool"];

    // Load sort by index value.
    _sortByIndex = [[NSUserDefaults standardUserDefaults] integerForKey:@"SortByIndex"];

    // Load sort type ascending boolean value.
    _ascendingBool = [[NSUserDefaults standardUserDefaults] boolForKey:@"SortAscendingBool"];
}

#pragma mark - Data setup

- (NSArray*)getSections
{
    return [NSArray arrayWithObjects: _textAlignmentString, _characterString, _sortByString, _ascendingString, _revertString, nil];
}

- (NSArray*)getAlignmentRows
{
    return [NSArray arrayWithObjects:@"Left", @"Right", nil];
}

- (NSArray *)getCharacterRows
{
    return [NSArray arrayWithObjects:@"Reverse characters", nil];
}

- (NSArray *)getSortByRows
{
    return [NSArray arrayWithObjects:@"Alphabetical order", @"Character count", @"Display size", nil];
}

- (NSArray*)getSortingRows
{
    return [NSArray arrayWithObjects:@"Ascending", nil];
}

- (NSArray*)getRevertRows
{
    return [NSArray arrayWithObjects:@"Refresh to default state", nil];
}

@end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace CartExcel\BlogBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use CartExcel\BlogBundle\Entity\ArticleTag;
use CartExcel\BlogBundle\Form\ArticleTagType;

/**
 * ArticleTag controller.
 *
 */
class ArticleTagController extends Controller
{
    /**
     * Lists all ArticleTag entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('CartExcelBlogBundle:ArticleTag')->findAll();

        return $this->render('CartExcelBlogBundle:ArticleTag:index.html.twig', array(
            'entities' => $entities,
        ));
    }

    /**
     * Creates a new ArticleTag entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity  = new ArticleTag();
        $form = $this->createForm(new ArticleTagType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('articletag_edit', array('id' => $entity->getId())));
        }

        return $this->render('CartExcelBlogBundle:ArticleTag:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Displays a form to create a new ArticleTag entity.
     *
     */
    public function newAction()
    {
        $entity = new ArticleTag();
        $form   = $this->createForm(new ArticleTagType(), $entity);

        return $this->render('CartExcelBlogBundle:ArticleTag:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a ArticleTag entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('CartExcelBlogBundle:ArticleTag')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find ArticleTag entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('CartExcelBlogBundle:ArticleTag:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),        ));
    }

    /**
     * Displays a form to edit an existing ArticleTag entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('CartExcelBlogBundle:ArticleTag')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find ArticleTag entity.');
        }

        $editForm = $this->createForm(new ArticleTagType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('CartExcelBlogBundle:ArticleTag:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Edits an existing ArticleTag entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('CartExcelBlogBundle:ArticleTag')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find ArticleTag entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new ArticleTagType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('articletag_edit', array('id' => $id)));
        }

        return $this->render('CartExcelBlogBundle:ArticleTag:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a ArticleTag entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {

            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('CartExcelBlogBundle:ArticleTag')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find ArticleTag entity.');
            }

            $em->remove($entity);
            $em->flush();

        return $this->redirect($this->generateUrl('articletag'));
    }

    /**
     * Creates a form to delete a ArticleTag entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }

}


text:
Three things are required when CoreData is put in a Swift framework and this framework is shared between the main project and extension projects. Reference: https://www.andrewcbancroft.com/2015/08/25/sharing-a-core-data-model-with-a-swift-framework/

- Need to create a data model file in this Swift framework. You cannot move one from other projects.

- Create an app group for sqlite database
```swift
lazy var applicationDocumentsDirectory: NSURL = {
        let url = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.xxx.xxxxxx");
        return url!
    }()
```
- Use the framework bundle to get the data model file
```swift
lazy var managedObjectModel: NSManagedObjectModel = {
       let shareKitBundle = NSBundle(identifier: "com.xxx.xxxxxx")
       let modelURL = shareKitBundle!.URLForResource("DataModel", withExtension: "momd")!
       return NSManagedObjectModel(contentsOfURL: modelURL)!
   }()
```


text:
using namespace DirectX;

//--------------------------------------------------------------------------------------
// Project includes
//--------------------------------------------------------------------------------------
#include "..\inc\Resource.h"
#include "..\..\common\inc\Background.h"
#include "..\..\common\inc\Character.h"

#pragma warning( disable : 4127 ) // disable conditional expression is constant warnings
#pragma warning( disable : 4100 ) // disable unreference formal parameter warnings for /W4 builds

#define APPLICATION_TITLE L"AMD LiquidVR GPUAffinityControl v1.0.0"

//--------------------------------------------------------------------------------------
// application options
//--------------------------------------------------------------------------------------
static bool							g_bRenderHUD = true;
static bool							g_bPresentTimerStarted = false;
static bool							g_bDrawFoblinMeshes = true;

//--------------------------------------------------------------------------------------
// application objects
//--------------------------------------------------------------------------------------
static ApplicationContext			g_Context;
static Background					g_Background;
static Character					g_Character;

//--------------------------------------------------------------------------------------
// Global variables for UI
//--------------------------------------------------------------------------------------
static AMD::HUD						g_HUD;
static CDXUTDialogResourceManager	g_DialogResourceManager;    // manager for shared resources of dialogs
static CD3DSettingsDlg				g_SettingsDlg;              // Device settings dialog
static CDXUTTextHelper*				g_pTxtHelper = NULL;

//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
enum
{
	IDC_TOGGLEFULLSCREEN = 1,
	IDC_CHANGE_DEVICE,
	IDC_STATIC_FRAMERATE,
	IDC_CHECKBOX_ENABLE_MGPU,

    IDC_STATIC_SYNC_TYPE,
    IDC_RADIO_SYNC_TYPE,
    IDC_RADIO_SYNC_TYPE_AUTOMATIC,
    IDC_RADIO_SYNC_TYPE_MANUAL,
    IDC_RADIO_SYNC_TYPE_NONE,

	IDC_CHECKBOX_DRAW_FOBLINMESH,
	IDC_CHECKBOX_ALPHA_FOBLINMESH,
	IDC_CHECKBOX_CLEAR_FOBLINMESH,
	IDC_CHECKBOX_SHIFT_FOBLINMESH,
	IDC_SLIDER_NUM_DRAW_CALLS,
	IDC_STATIC_NUM_DRAW_CALLS,
	IDC_NUM_CONTROL_IDS
};

const int AMD::g_MaxApplicationControlID = IDC_NUM_CONTROL_IDS;

//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing,
                          void* pUserContext );
void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext );
void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext );
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext );
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext );

bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo,
                                       DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext );
HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc,
                                     void* pUserContext );
HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain,
                                         const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext );
void CALLBACK OnD3D11DestroyDevice( void* pUserContext );
void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime,
                                 float fElapsedTime, void* pUserContext );
HRESULT CALLBACK OnD3D11ContextCreated(ID3D11Device** ppd3dDevice, ID3D11DeviceContext** ppd3dImmediateContext);

//--------------------------------------------------------------------------------------
// helpers
//--------------------------------------------------------------------------------------
void InitApp();
void RenderText();

//--------------------------------------------------------------------------------------
// Entry point to the program. Initializes everything and goes into a message processing
// loop. Idle time is used to render the scene.
//--------------------------------------------------------------------------------------
int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
{
    // Enable run-time memory check for debug builds.
#if defined(DEBUG) || defined(_DEBUG)
    _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif

    // DXUT will create and use the best device (either D3D9 or D3D11)
    // that is available on the system depending on which D3D callbacks are set below

    // Set DXUT callbacks
    DXUTSetCallbackMsgProc( MsgProc );
    DXUTSetCallbackKeyboard( OnKeyboard );
    DXUTSetCallbackFrameMove( OnFrameMove );
    DXUTSetCallbackDeviceChanging( ModifyDeviceSettings );

    DXUTSetCallbackD3D11DeviceAcceptable( IsD3D11DeviceAcceptable );
    DXUTSetCallbackD3D11DeviceCreated( OnD3D11CreateDevice );
    DXUTSetCallbackD3D11SwapChainResized( OnD3D11ResizedSwapChain );
    DXUTSetCallbackD3D11SwapChainReleasing( OnD3D11ReleasingSwapChain );
    DXUTSetCallbackD3D11DeviceDestroyed( OnD3D11DestroyDevice );
    DXUTSetCallbackD3D11FrameRender( OnD3D11FrameRender );
	DXUTSetCallbackD3D11ContextCreated(OnD3D11ContextCreated);

    InitApp();

    DXUTInit( true, true, NULL ); // Parse the command line, show msgboxes on error, no extra command line params
    DXUTSetCursorSettings( true, true );
	DXUTCreateWindow(APPLICATION_TITLE);

    // Require D3D_FEATURE_LEVEL_11_0
    DXUTCreateDevice( D3D_FEATURE_LEVEL_11_0, true, 1920, 1080 );

    DXUTMainLoop(); // Enter into the DXUT render loop

	// Ensure the ShaderCache aborts if in a lengthy generation process
	g_Context.m_ShaderCache.Abort();

	if (g_bPresentTimerStarted)
	{
		TIMER_End() // Present
		TIMER_Destroy()
		g_bPresentTimerStarted = false;
	}

    return DXUTGetExitCode();
}
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
void InitApp()
{
    D3DCOLOR DlgColor = 0x88888888; // Semi-transparent background for the dialog

    g_SettingsDlg.Init( &g_DialogResourceManager );
    g_HUD.m_GUI.Init( &g_DialogResourceManager );
    g_HUD.m_GUI.SetBackgroundColors( DlgColor );
    g_HUD.m_GUI.SetCallback( OnGUIEvent );

    int iY = AMD::HUD::iElementDelta;

    g_HUD.m_GUI.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", AMD::HUD::iElementOffset, iY, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight );
	g_HUD.m_GUI.AddButton(IDC_CHANGE_DEVICE, L"Change device (F2)", AMD::HUD::iElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, VK_F2);

	iY += AMD::HUD::iGroupDelta / 3;

	CDXUTStatic* pFrameRateStatic = nullptr;
	g_HUD.m_GUI.AddStatic(IDC_STATIC_FRAMERATE, L"", AMD::HUD::iElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, false, &pFrameRateStatic);
	D3DCOLOR frameRateColor = D3DCOLOR_RGBA(0xFF, 0, 0, 0xFF);
	pFrameRateStatic->SetTextColor(frameRateColor);

	g_HUD.m_GUI.AddCheckBox(IDC_CHECKBOX_ENABLE_MGPU, L"Enable MGPU",               AMD::HUD::iElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, g_Context.m_Affinity.GetUseAffinity());

    g_HUD.m_GUI.AddStatic(IDC_STATIC_SYNC_TYPE, L"Transfer Sync", AMD::HUD::iElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight);

    g_HUD.m_GUI.AddRadioButton(IDC_RADIO_SYNC_TYPE_AUTOMATIC, IDC_RADIO_SYNC_TYPE, L"Automatic", AMD::HUD::iElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, g_Context.m_Affinity.GetSyncType() == TRANSFER_SYNC_AUTOMATIC);
    g_HUD.m_GUI.AddRadioButton(IDC_RADIO_SYNC_TYPE_MANUAL, IDC_RADIO_SYNC_TYPE, L"Manual", AMD::HUD::iElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, g_Context.m_Affinity.GetSyncType() == TRANSFER_SYNC_MANUAL);
    g_HUD.m_GUI.AddRadioButton(IDC_RADIO_SYNC_TYPE_NONE, IDC_RADIO_SYNC_TYPE, L"None", AMD::HUD::iElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, g_Context.m_Affinity.GetSyncType() == TRANSFER_SYNC_NONE);

	iY += AMD::HUD::iGroupDelta / 3;

	g_HUD.m_GUI.AddCheckBox(IDC_CHECKBOX_DRAW_FOBLINMESH, L"Draw Foblin(s)",        AMD::HUD::iElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, g_bDrawFoblinMeshes);
	g_HUD.m_GUI.AddCheckBox(IDC_CHECKBOX_ALPHA_FOBLINMESH, L"Alpha Foblin(s)",      AMD::HUD::iElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, g_Character.GetAlpha());
	g_HUD.m_GUI.AddCheckBox(IDC_CHECKBOX_CLEAR_FOBLINMESH, L"Clear Foblin(s) Bkgs", AMD::HUD::iElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, g_Character.GetClear());
	g_HUD.m_GUI.AddCheckBox(IDC_CHECKBOX_SHIFT_FOBLINMESH, L"Shift Foblin(s)",      AMD::HUD::iElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, g_Character.GetShift());

	int minParam;
	int maxParam;
	g_Character.GetDrawLimits(&minParam, &maxParam);
	int currentParam = g_Character.GetTodoDraw();
	WCHAR szTemp[256];
	swprintf_s(szTemp, L"Number of Draw Calls: %i", currentParam);
	g_HUD.m_GUI.AddStatic(IDC_STATIC_NUM_DRAW_CALLS, szTemp, AMD::HUD::iElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight);
	g_HUD.m_GUI.AddSlider(IDC_SLIDER_NUM_DRAW_CALLS, AMD::HUD::iElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, minParam, maxParam, currentParam, false);

	iY += AMD::HUD::iGroupDelta;

	g_Context.m_ShaderCache.SetShowShaderISAFlag(false);
	AMD::InitApp(g_Context.m_ShaderCache, g_HUD, iY, false);
}
//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
void RenderText()
{
    g_pTxtHelper->Begin();
    g_pTxtHelper->SetInsertionPos( 5, 5 );
    g_pTxtHelper->SetForegroundColor( XMFLOAT4( 1.0f, 0.0f, 0.0f, 1.0f ) );
    g_pTxtHelper->DrawTextLine( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) );
    g_pTxtHelper->DrawTextLine( DXUTGetDeviceStats() );

	double fTotal = TIMER_GetTime(Gpu, L"Total") * 1000.0f;
	double fFoblin = TIMER_GetTime(Gpu, L"Total|FoblinMesh") * 1000.0f;
	double fLeftEye = TIMER_GetTime(Gpu, L"Total|FoblinMesh|LeftEye") * 1000.0f;
	double fRightEye = TIMER_GetTime(Gpu, L"Total|FoblinMesh|RightEye") * 1000.0f;
	double fTransfer = TIMER_GetTime(Gpu, L"Total|Transfer") * 1000.0f;
	double fPresent = TIMER_GetTime(Gpu, L"Present") * 1000.0f;

	double fPerFoblin = fFoblin / (double)(g_Character.GetTodoDraw() * 2) * 1000.0f;

	fTotal += fPresent;
	double fOverhead = fFoblin - fLeftEye - fRightEye;
	WCHAR wcbuf[256];
	swprintf_s(wcbuf, 256, L"Cost in milliseconds( Total = %.2f, Left Eye = %.2f, Right Eye = %.2f, Transfer = %.2f, Present = %.2f, FoblinMesh = %.2f [each: %.2fus], Overhead = %.2f )",
		fTotal, fLeftEye, fRightEye, fTransfer, fPresent, fFoblin, fPerFoblin, fOverhead);
	g_pTxtHelper->DrawTextLine( wcbuf );

    g_pTxtHelper->SetInsertionPos( 5, DXUTGetDXGIBackBufferSurfaceDesc()->Height - AMD::HUD::iElementDelta );
	g_pTxtHelper->DrawTextLine( L"Toggle GUI    : F1" );

    g_pTxtHelper->End();

}

//--------------------------------------------------------------------------------------
// Reject any D3D11 devices that aren't acceptable by returning false
//--------------------------------------------------------------------------------------
bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo,
                                       DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext )
{
	if (DeviceInfo->DeviceType != D3D_DRIVER_TYPE_HARDWARE)
	{
		return false;
	}
    return true;
}

//--------------------------------------------------------------------------------------
// Create any D3D11 resources that aren't dependant on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc,
                                     void* pUserContext )
{
    HRESULT hr;

    hr = DXUTGetDXGIFactory()->MakeWindowAssociation(DXUTGetHWND(), DXGI_MWA_NO_ALT_ENTER);

    ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext();
    V_RETURN( g_DialogResourceManager.OnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) );
    V_RETURN( g_SettingsDlg.OnD3D11CreateDevice( pd3dDevice ) );
    g_pTxtHelper = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15 );

    // Create AMD_SDK resources here
    g_HUD.OnCreateDevice( pd3dDevice );

	g_Context.Init(pd3dDevice, pd3dImmediateContext);
	g_Background.Init(pd3dDevice, &g_Context);
	g_Character.Init(pd3dDevice, pd3dImmediateContext, &g_Context);

	TIMER_Init(pd3dDevice)

	// Generate shaders ( this is an async operation - call AMD::ShaderCache::ShadersReady() to find out if they are complete )
    static bool bFirstPass = true;
    if( bFirstPass )
    {
		// Add the applications shaders to the cache
		g_Context.m_ShaderCache.GenerateShaders(AMD::ShaderCache::CREATE_TYPE_COMPILE_CHANGES);    // Only compile shaders that have changed (development mode)
        bFirstPass = false;
    }
	g_Context.m_Affinity.SetUseAffinity(true);

	// Set toggle whether to render using Affinity MGPU
	g_HUD.m_GUI.GetCheckBox(IDC_CHECKBOX_ENABLE_MGPU)->SetChecked(g_Context.m_Affinity.GetUseAffinity());
	g_HUD.m_GUI.GetCheckBox(IDC_CHECKBOX_ENABLE_MGPU)->SetEnabled(g_Context.m_Affinity.IsEnabled());

    g_HUD.m_GUI.GetRadioButton(IDC_RADIO_SYNC_TYPE_AUTOMATIC)->SetEnabled(g_Context.m_Affinity.GetUseAffinity());
    g_HUD.m_GUI.GetRadioButton(IDC_RADIO_SYNC_TYPE_MANUAL)->SetEnabled(g_Context.m_Affinity.GetUseAffinity());
    g_HUD.m_GUI.GetRadioButton(IDC_RADIO_SYNC_TYPE_NONE)->SetEnabled(g_Context.m_Affinity.GetUseAffinity());

    wchar_t text[1000];
    swprintf_s(text, _countof(text), L"%s : %s", APPLICATION_TITLE, g_Context.m_Affinity.IsEnabled() ? L"MGPU available" : L"MGPU not available");
    ::SetWindowTextW(::DXUTGetHWND(), text);

    return S_OK;
}

//--------------------------------------------------------------------------------------
// Create any D3D11 resources that depend on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain,
                                         const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
{
    HRESULT hr;

    V_RETURN( g_DialogResourceManager.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );
    V_RETURN( g_SettingsDlg.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) );

    // Setup the camera's projection parameters
    float fAspectRatio = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height / 2;
	g_Context.m_Camera.SetProjParams(XM_PI / 4, fAspectRatio, 0.1f, 1000.0f);
//    g_Context.m_Camera.SetProjParams(XM_PI / 4, fAspectRatio, 0.1f, 10000.0f);

	g_Context.m_Light.SetRadius(10.0f);
	g_Context.m_Light.SetLightDirection(XMFLOAT3(0.6f, 0.4f, 0.3f));
	g_Context.m_Light.SetButtonMask(MOUSE_RIGHT_BUTTON);

	g_Context.m_fbWidth = (float)pBackBufferSurfaceDesc->Width;
	g_Context.m_fbHeight = (float)pBackBufferSurfaceDesc->Height;

    // Set the location and size of the AMD standard HUD
    g_HUD.m_GUI.SetLocation( pBackBufferSurfaceDesc->Width - AMD::HUD::iDialogWidth, 0 );
    g_HUD.m_GUI.SetSize( AMD::HUD::iDialogWidth, pBackBufferSurfaceDesc->Height );
    g_HUD.OnResizedSwapChain( pBackBufferSurfaceDesc );

	assert( D3D_OK == hr );

    return S_OK;
}

//--------------------------------------------------------------------------------------
// Render the scene using the D3D11 device
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime,
                                 float fElapsedTime, void* pUserContext )
{
    if (g_bPresentTimerStarted)
    {
        TIMER_End(); // Present
        // Reset the timer at start of frame
        TIMER_Reset();
        g_bPresentTimerStarted = false;
    }

    // If the settings dialog is being shown, then render it instead of rendering the app's scene
    if( g_SettingsDlg.IsActive() )
    {
        g_SettingsDlg.OnRender( fElapsedTime );
        return;
    }
	TIMER_Begin(0, L"Total");

	g_Context.m_Affinity.SetRenderGpuMask(GPUMASK_BOTH);

    DXUTSetupD3D11Views(pd3dImmediateContext);

    // Switch off alpha blending
    float BlendFactor[1] = { 0.0f };
	pd3dImmediateContext->OMSetBlendState(g_Context.m_pOpaqueState, BlendFactor, 0xffffffff);
    pd3dImmediateContext->OMSetDepthStencilState(g_Context.m_pDepthStateOpaque, 0);

    // Render objects here...
	if (g_Context.m_ShaderCache.ShadersReady())
	{
		float ClearColor[4] = { 0.0f, 0.0f, 0.3f, 1.0f }; // red,green,blue,alpha

		// RenderToDirectDisplay
		ID3D11RenderTargetView* pRtv = nullptr;
		pd3dImmediateContext->OMGetRenderTargets(1, &pRtv, nullptr);
		pd3dImmediateContext->ClearRenderTargetView(pRtv, ClearColor);
		pRtv->Release();

		auto pDSV = DXUTGetD3D11DepthStencilView();
		if (pDSV != NULL)
		{
            pd3dImmediateContext->ClearDepthStencilView(pDSV, D3D11_CLEAR_DEPTH, 1.0, 0);
        }

		g_Character.Time();

//		g_Context.m_Affinity.SetRenderGpuMask(GPUMASK_BOTH);
		g_Background.Render(pd3dImmediateContext, g_Context.m_fbWidth, g_Context.m_fbHeight);

		g_Context.m_Affinity.SetRenderGpuMask(GPUMASK_BOTH);
		pDSV = DXUTGetD3D11DepthStencilView();
		if (pDSV != NULL)
		{
			pd3dImmediateContext->ClearDepthStencilView(pDSV, D3D11_CLEAR_DEPTH, 1.0, 0);
		}

		if (g_HUD.m_GUI.GetCheckBox(IDC_CHECKBOX_DRAW_FOBLINMESH)->GetChecked())
		{
			g_Character.Render(pd3dImmediateContext, g_Context.m_fbWidth, g_Context.m_fbHeight);
		}
		TIMER_Begin(0, L"Transfer");
		g_Context.m_Affinity.TransferRightEye(pd3dImmediateContext, g_Context.m_fbWidth, g_Context.m_fbHeight);
		TIMER_End() // Transfer
	}
		// Only render the HUD once on GPU0
	g_Context.m_Affinity.SetRenderGpuMask(GPUMASK_LEFT);
	D3D11_VIEWPORT viewport;
	viewport.TopLeftX = 0;
	viewport.TopLeftY = 0;
	viewport.MinDepth = 0;
	viewport.MaxDepth = 1;
	viewport.Width = g_Context.m_fbWidth;
	viewport.Height = g_Context.m_fbHeight;
	pd3dImmediateContext->RSSetViewports(1, &viewport);

	// Switch off alpha blending
	pd3dImmediateContext->OMSetBlendState(g_Context.m_pOpaqueState, BlendFactor, 0xffffffff);
    pd3dImmediateContext->OMSetDepthStencilState(g_Context.m_pDepthStateOpaque, 0);

	TIMER_End() // Total

    DXUT_BeginPerfEvent( DXUT_PERFEVENTCOLOR, L"HUD / Stats" );

	AMD::ProcessUIChanges();

	if (g_Context.m_ShaderCache.ShadersReady())
	{
		// update frame rate
		WCHAR szTemp[256];
		swprintf_s(szTemp, L"%.1f FPS", DXUTGetFPS());
		g_HUD.m_GUI.GetStatic(IDC_STATIC_FRAMERATE)->SetText(szTemp);

        // Render the HUD
        if( g_bRenderHUD )
        {
            g_HUD.OnRender( fElapsedTime );
        }

        RenderText();

		AMD::RenderHUDUpdates( g_pTxtHelper );
    }
	else
    {
        // Render shader cache progress if still processing
		XMFLOAT4 f4( 1.0f, 1.0f, 0.0f, 1.0f );
		g_Context.m_ShaderCache.RenderProgress(g_pTxtHelper, 15, XMLoadFloat4(&f4));
    }

    DXUT_EndPerfEvent();

    static DWORD dwTimefirst = GetTickCount();
    if ( GetTickCount() - dwTimefirst > 5000 )
    {
        OutputDebugString( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) );
        OutputDebugString( L"\n" );
        dwTimefirst = GetTickCount();
    }

	TIMER_Begin(0, L"Present");
	g_bPresentTimerStarted = true;
}

//--------------------------------------------------------------------------------------
// Release D3D11 resources created in OnD3D11ResizedSwapChain
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext )
{
    g_DialogResourceManager.OnD3D11ReleasingSwapChain();

}

//--------------------------------------------------------------------------------------
// Release D3D11 resources created in OnD3D11CreateDevice
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D11DestroyDevice( void* pUserContext )
{

	g_Background.Terminate();
	g_Character.Terminate();

    g_DialogResourceManager.OnD3D11DestroyDevice();
    g_SettingsDlg.OnD3D11DestroyDevice();
    DXUTGetGlobalResourceCache().OnDestroyDevice();
    SAFE_DELETE( g_pTxtHelper );
    // Destroy AMD_SDK resources here
	g_HUD.OnDestroyDevice();
	if (g_bPresentTimerStarted)
	{
		TIMER_End() // Present
		TIMER_Destroy()
		g_bPresentTimerStarted = false;
	}
	g_Context.Terminate();
}

//--------------------------------------------------------------------------------------
// Called right before creating a D3D9 or D3D11 device, allowing the app to modify the device settings as needed
//--------------------------------------------------------------------------------------
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext )
{
	// need this to to match DirectToDisplay color space
	pDeviceSettings->d3d11.sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

    return true;
}

//--------------------------------------------------------------------------------------
// Handle updates to the scene.  This is called regardless of which D3D API is used
//--------------------------------------------------------------------------------------
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext )
{
    // Update the camera's position based on user input
	g_Context.m_Camera.FrameMove(fElapsedTime);
}

//--------------------------------------------------------------------------------------
// Handle messages to the application
//--------------------------------------------------------------------------------------
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing,
                          void* pUserContext )
{
    // Pass messages to dialog resource manager calls so GUI state is updated correctly
    *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam );
    if( *pbNoFurtherProcessing )
        return 0;

    // Pass messages to settings dialog if its active
    if( g_SettingsDlg.IsActive() )
    {
        g_SettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam );
        return 0;
    }

    // Give the dialogs a chance to handle the message first
    *pbNoFurtherProcessing = g_HUD.m_GUI.MsgProc( hWnd, uMsg, wParam, lParam );
    if( *pbNoFurtherProcessing )
        return 0;

    // Pass all remaining windows messages to camera so it can respond to user input
	g_Context.m_Camera.HandleMessages(hWnd, uMsg, wParam, lParam);

    // Pass all remaining windows messages to the light Object
	g_Context.m_Light.HandleMessages(hWnd, uMsg, wParam, lParam);

    return 0;
}

//--------------------------------------------------------------------------------------
// Handle key presses
//--------------------------------------------------------------------------------------
void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext )
{
    if( bKeyDown )
    {
        switch( nChar )
        {
			case VK_F1:
				g_bRenderHUD = !g_bRenderHUD;
				break;
			case VK_F2:
				g_SettingsDlg.SetActive(!g_SettingsDlg.IsActive());
				break;
            case VK_RETURN:
                if (bAltDown == true)
                {
                    DXUTToggleFullScreen();
                }
                break;
		}
    }
}

//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext )
{
    switch( nControlID )
    {
        case IDC_TOGGLEFULLSCREEN:
            DXUTToggleFullScreen();
            break;
		case IDC_CHANGE_DEVICE:
            g_SettingsDlg.SetActive( !g_SettingsDlg.IsActive() );
            break;
		case IDC_SLIDER_NUM_DRAW_CALLS:
		{
			int currentParam = ((CDXUTSlider*)pControl)->GetValue();
			WCHAR szTemp[256];
			swprintf_s(szTemp, L"Number of Draw Calls: %i", currentParam);
			g_HUD.m_GUI.GetStatic(IDC_STATIC_NUM_DRAW_CALLS)->SetText(szTemp);
			g_Character.SetTodoDraw(currentParam);
			break;
		}
		case IDC_CHECKBOX_ENABLE_MGPU:
			g_Context.m_Affinity.SetUseAffinity(((CDXUTCheckBox*)pControl)->GetChecked());

            g_HUD.m_GUI.GetRadioButton(IDC_RADIO_SYNC_TYPE_AUTOMATIC)->SetEnabled(g_Context.m_Affinity.GetUseAffinity());
            g_HUD.m_GUI.GetRadioButton(IDC_RADIO_SYNC_TYPE_MANUAL)->SetEnabled(g_Context.m_Affinity.GetUseAffinity());
            g_HUD.m_GUI.GetRadioButton(IDC_RADIO_SYNC_TYPE_NONE)->SetEnabled(g_Context.m_Affinity.GetUseAffinity());

			break;

        case IDC_RADIO_SYNC_TYPE_AUTOMATIC:
            g_Context.m_Affinity.SetSyncType(TRANSFER_SYNC_AUTOMATIC);
            break;
        case IDC_RADIO_SYNC_TYPE_MANUAL:
            g_Context.m_Affinity.SetSyncType(TRANSFER_SYNC_MANUAL);
			break;
        case IDC_RADIO_SYNC_TYPE_NONE:
            g_Context.m_Affinity.SetSyncType(TRANSFER_SYNC_NONE);
            break;

		case IDC_CHECKBOX_SHIFT_FOBLINMESH:
			g_Character.SetShift(((CDXUTCheckBox*)pControl)->GetChecked());
			break;
		case IDC_CHECKBOX_ALPHA_FOBLINMESH:
			g_Character.SetAlpha(((CDXUTCheckBox*)pControl)->GetChecked());
			break;
		case IDC_CHECKBOX_CLEAR_FOBLINMESH:
			g_Character.SetClear(((CDXUTCheckBox*)pControl)->GetChecked());
			break;
		default:
			AMD::OnGUIEvent( nEvent, nControlID, pControl, pUserContext );
			break;
    }
}
//--------------------------------------------------------------------------------------
// replaces context with a wrapper
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D11ContextCreated(ID3D11Device** ppd3dDevice, ID3D11DeviceContext** ppd3dImmediateContext)
{
    return g_Context.m_Affinity.Init(g_Context.m_pLiquidVRAffinity, ppd3dDevice, ppd3dImmediateContext);
}
//--------------------------------------------------------------------------------------
// EOF.
//--------------------------------------------------------------------------------------