<commit_before>// Hex math taken from the amazing Amit Patel @ http://www.redblobgames.com/grids/hexagons/

#include <SDL.h>
#include <SDL_ttf.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <math.h>

typedef int8_t int8;
typedef int16_t int16;
typedef int32_t int32;
typedef int64_t int64;

typedef uint8_t uint8;
typedef uint16_t uint16;
typedef uint32_t uint32;
typedef uint64_t uint64;

#define PI 3.1415927f

static bool running;

int gridOriginX = 30;
int gridOriginY = 30;
int gridWidth = 14;
int gridHeight = 14;
int hexSize = 30;
float hexWidth = (3.0f/2.0f) * hexSize;
float hexHeight = sqrt(3.0f) * hexSize;

int fontSize = 22;
TTF_Font* font;

struct Map
{
    int width;
    int height;
    void* data;
};

struct GameState
{
    Map map;

    int currentPlayer;
    int playerVelocity[2];
    SDL_Point playerLoc[2];
};

bool isDigit(int c)
{
    return c >= '0' && c <= '9';
}

int getUIntFromByteStream(FILE* inFile)
{
    int result = 0;
    int nextByte;
    while(isDigit(nextByte = fgetc(inFile)))
    {
        if(nextByte == EOF)
        {
            printf("Error reading map file, unexpected EOF\n");
            return -1;
        }
        result = (10*result+(nextByte-'0'));
    }
    return result;
}

void loadMap(char* filename, GameState* gameState)
{
    FILE* inFile;
    fopen_s(&inFile, filename, "r");

    // Load Map Data
    gameState->map.width = getUIntFromByteStream(inFile);
    gameState->map.height = getUIntFromByteStream(inFile);
    gameState->map.data = malloc(gameState->map.width * gameState->map.height);
    for(int y=0; y<gameState->map.height; ++y)
    {
        fread((void*)((char*)gameState->map.data + gameState->map.width*y), 1, gameState->map.width, inFile);
        fgetc(inFile); // Skip the newline byte
    }
	fclose(inFile);

    // Assign player start locations
    for(int y=0; y<gameState->map.height; ++y)
    {
        for(int x=0; x<gameState->map.width; ++x)
        {
            char c = *((char*)gameState->map.data + gameState->map.width*y + x);
            if(c == 'A')
            {
                gameState->playerLoc[0].x = x;
                gameState->playerLoc[0].y = y;
            }
            else if(c == 'B')
            {
                gameState->playerLoc[1].x = x;
                gameState->playerLoc[1].y = y;
            }
        }
    }
}

// TODO: Implement this properly (at the moment it's SUPER inefficient)
void text(SDL_Renderer* renderer, char* text, int x, int y)
{
    int textLength = 0;
    while(text[textLength] != 0)
    {
        ++textLength;
    }

    SDL_Color White = {255, 255, 255};
    SDL_Surface* surfaceMessage = TTF_RenderText_Solid(font, text, White);
    SDL_Texture* TextMessage = SDL_CreateTextureFromSurface(renderer, surfaceMessage);

    SDL_Rect Message_rect;
    Message_rect.x = x;
    Message_rect.y = y;
    Message_rect.w = (int)(fontSize*(3.0f/4.0f))*textLength;
    Message_rect.h = fontSize+5; // controls the height of the rect
    printf("%s\n", SDL_GetError());
    //Now since it's a texture, you have to put RenderCopy in your game loop area, the area where the whole code executes
    SDL_RenderCopy(renderer, TextMessage, NULL, &Message_rect); //you put the renderer's name first, the Message, the crop size(you can ignore this if you don't want to dabble with cropping), and the rect which is the size and coordinate of your texture
    SDL_FreeSurface(surfaceMessage);
    SDL_DestroyTexture(TextMessage);
}

int round(float x)
{
    return (int)(x+0.5f);
}

int screenToHexX(int screenX)
{
    return (int)round((screenX - gridOriginX)/hexWidth);
}

int screenToHexY(int screenX, int screenY)
{
    int hexX = screenToHexX(screenX);
    if(hexX%2 == 0)
    {
        screenY -= (int)(hexHeight/2.0f);
    }
    return (int)round((screenY - gridOriginY)/hexHeight);
}

int hexToScreenX(int hexX)
{
    return gridOriginX + (int)(hexWidth*hexX);
}

int hexToScreenY(int hexX, int hexY)
{
    int result = gridOriginY + (int)(hexHeight*hexY);
    if(hexX%2 == 0)
    {
        result += (int)(hexHeight/2.0f);
    }
    return result;
}

int drawRegularHex(SDL_Renderer* renderer, int centreX, int centreY, int radius)
{
    SDL_Point hexPoints[7];
    for(int i=0; i<7; ++i)
    {
        float angle = (60.0f*i);
        float angle_rad = (PI/180) * angle;

        hexPoints[i].x = (int)(centreX + radius*cosf(angle_rad));
        hexPoints[i].y = (int)(centreY + radius*sinf(angle_rad));
    }
    return SDL_RenderDrawLines(renderer, hexPoints, 7);
}

void fillRect(SDL_Renderer* renderer, int centreX, int centreY, int width, int height)
{
    SDL_Rect rect;
    rect.x = centreX-width/2;
    rect.y = centreY-height/2;
    rect.w = width;
    rect.h = height;
    SDL_RenderFillRect(renderer, &rect);
}

void render(SDL_Renderer* renderer, GameState* gameState)
{
    // Clear to black
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    SDL_RenderClear(renderer);
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);

    // Draw Hex Grid
    for(int y=0; y<gridHeight; ++y)
    {
        for(int x=0; x<gridWidth; ++x)
        {
            int centreX = (int)(gridOriginX + x*hexWidth);
            int centreY = (int)(gridOriginY + y*hexHeight);
            if(x%2 == 0)
            {
                centreY += (int)(hexHeight/2.0f);
            }
            drawRegularHex(renderer, centreX, centreY, hexSize);

            char hexType = *((char*)gameState->map.data + (y*gameState->map.width + x));
            if(hexType != 'X')
            {
                int screenX = hexToScreenX(x);
                int screenY = hexToScreenY(x, y);
                fillRect(renderer, screenX, screenY, (int)(hexWidth/2), (int)(hexHeight/2));
            }
        }
    }

    // Draw player hex's
    int playerScreenX;
    int playerScreenY;
    playerScreenX = hexToScreenX(gameState->playerLoc[0].x);
    playerScreenY = hexToScreenY(gameState->playerLoc[0].x, gameState->playerLoc[0].y);
    SDL_SetRenderDrawColor(renderer, 255, 105, 97, 255);
    fillRect(renderer, playerScreenX, playerScreenY, (int)(hexWidth/2), (int)(hexHeight/2));
    playerScreenX = hexToScreenX(gameState->playerLoc[1].x);
    playerScreenY = hexToScreenY(gameState->playerLoc[1].x, gameState->playerLoc[1].y);
    SDL_SetRenderDrawColor(renderer, 97, 168, 255, 255);
    fillRect(renderer, playerScreenX, playerScreenY, (int)(hexWidth/2), (int)(hexHeight/2));

    // Draw Mouseover'd Hex
    int mouseX;
    int mouseY;
    SDL_GetMouseState(&mouseX, &mouseY);
    int mouseHexX = screenToHexX(mouseX);
    int mouseHexY = screenToHexY(mouseX, mouseY);
    if(mouseHexX < 0)
    {
        mouseHexX = 0;
    }
    else if(mouseHexX >= gridWidth)
    {
        mouseHexX = gridWidth-1;
    }
    if(mouseHexY < 0)
    {
        mouseHexY = 0;
    }
    else if(mouseHexY >= gridHeight)
    {
        mouseHexY = gridHeight-1;
    }
    int roundedMouseX = hexToScreenX(mouseHexX);
    int roundedMouseY = hexToScreenY(mouseHexX, mouseHexY);
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    fillRect(renderer, roundedMouseX, roundedMouseY, (int)(hexWidth/2), (int)(hexHeight/2));

    // Draw Text
    text(renderer, "HexRacer!", 650, 10);
    char p1VeloStr[4];
    char p2VeloStr[4];
    _itoa_s(gameState->playerVelocity[0], p1VeloStr, 10);
    _itoa_s(gameState->playerVelocity[1], p2VeloStr, 10);
    text(renderer, "P1Spd:", 650, 50);
    text(renderer, p1VeloStr, 750, 50);
    text(renderer, "P2Spd:", 650, 100);
    text(renderer, p2VeloStr, 750, 100);

    SDL_RenderPresent(renderer);
}

void SDLHandleEvent(SDL_Event* event)
{
    switch(event->type)
    {
        case SDL_QUIT:
        {
            running = false;
        } break;
        case SDL_KEYDOWN:
        case SDL_KEYUP:
        {
            SDL_Keycode keyCode = event->key.keysym.sym;
            if(keyCode == SDLK_w && !event->key.repeat && event->key.state == SDL_PRESSED)
            {
                printf("W\n");
            }
            if(keyCode == SDLK_ESCAPE)
            {
                running = false;
            }
        } break;
        case SDL_WINDOWEVENT:
        {
            switch(event->window.event)
            {
                case SDL_WINDOWEVENT_RESIZED:
                {
                } break;
            }
        } break;
        default:
        {
        } break;
    }
}

int main(int argc, char** argv)
{
    if(SDL_Init(SDL_INIT_VIDEO) != 0)
    {
        // Couldn't load SDL
        SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Error", "Unable to load SDL!", 0);
        return 1;
    }

    if(TTF_Init()==-1)
    {
        printf("TTF_Init: %s\n", TTF_GetError());
        return 1;
    }

    SDL_Window* window  = SDL_CreateWindow("Hex Racing", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
                                           800, 800, SDL_WINDOW_RESIZABLE);
    if(window)
    {
        SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);
        if(renderer)
        {
            GameState gameState;
            loadMap("test.map", &gameState);

            gameState.currentPlayer = 0;
            gameState.playerVelocity[0] = 1;
            gameState.playerVelocity[1] = 1;

            font = TTF_OpenFont("ubuntumono.ttf", fontSize);

            running = true;
            while(running)
            {
                SDL_Event event;
                while(SDL_PollEvent(&event))
                {
                    SDLHandleEvent(&event);
                }

                render(renderer, &gameState);
            }

            free(gameState.map.data);
        }
        else
        {
            // Couldn't create renderer
        }
    }
    else
    {
        // Couldn't create window
    }

    SDL_Quit();
    return 0;
}
<commit_msg>Add initial basic acceleration/braking implementation<commit_after>// Hex math taken from the amazing Amit Patel @ http://www.redblobgames.com/grids/hexagons/

#include <SDL.h>
#include <SDL_ttf.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

typedef int8_t int8;
typedef int16_t int16;
typedef int32_t int32;
typedef int64_t int64;

typedef uint8_t uint8;
typedef uint16_t uint16;
typedef uint32_t uint32;
typedef uint64_t uint64;

#define PI 3.1415927f

static bool running;

int gridOriginX = 30;
int gridOriginY = 30;
int gridWidth = 14;
int gridHeight = 14;
int hexSize = 30;
float hexWidth = (3.0f/2.0f) * hexSize;
float hexHeight = sqrt(3.0f) * hexSize;

int fontSize = 22;
TTF_Font* font;

struct Map
{
    int width;
    int height;
    void* data;
};

struct GameState
{
    Map map;

    int currentPlayer;
    int playerVelocity[2];
    SDL_Point playerLoc[2];
};

bool isDigit(int c)
{
    return c >= '0' && c <= '9';
}

int getUIntFromByteStream(FILE* inFile)
{
    int result = 0;
    int nextByte;
    while(isDigit(nextByte = fgetc(inFile)))
    {
        if(nextByte == EOF)
        {
            printf("Error reading map file, unexpected EOF\n");
            return -1;
        }
        result = (10*result+(nextByte-'0'));
    }
    return result;
}

void loadMap(char* filename, GameState* gameState)
{
    FILE* inFile;
    fopen_s(&inFile, filename, "r");

    // Load Map Data
    gameState->map.width = getUIntFromByteStream(inFile);
    gameState->map.height = getUIntFromByteStream(inFile);
    gameState->map.data = malloc(gameState->map.width * gameState->map.height);
    for(int y=0; y<gameState->map.height; ++y)
    {
        fread((void*)((char*)gameState->map.data + gameState->map.width*y), 1, gameState->map.width, inFile);
        fgetc(inFile); // Skip the newline byte
    }
	fclose(inFile);

    // Assign player start locations
    for(int y=0; y<gameState->map.height; ++y)
    {
        for(int x=0; x<gameState->map.width; ++x)
        {
            char c = *((char*)gameState->map.data + gameState->map.width*y + x);
            if(c == 'A')
            {
                gameState->playerLoc[0].x = x;
                gameState->playerLoc[0].y = y;
            }
            else if(c == 'B')
            {
                gameState->playerLoc[1].x = x;
                gameState->playerLoc[1].y = y;
            }
        }
    }
}

// TODO: Implement this properly (at the moment it's SUPER inefficient)
void text(SDL_Renderer* renderer, char* text, int x, int y)
{
    int textLength = 0;
    while(text[textLength] != 0)
    {
        ++textLength;
    }

    SDL_Color White = {255, 255, 255};
    SDL_Surface* surfaceMessage = TTF_RenderText_Solid(font, text, White);
    SDL_Texture* TextMessage = SDL_CreateTextureFromSurface(renderer, surfaceMessage);

    SDL_Rect Message_rect;
    Message_rect.x = x;
    Message_rect.y = y;
    Message_rect.w = (int)(fontSize*(3.0f/4.0f))*textLength;
    Message_rect.h = fontSize+5; // controls the height of the rect
    printf("%s\n", SDL_GetError());
    //Now since it's a texture, you have to put RenderCopy in your game loop area, the area where the whole code executes
    SDL_RenderCopy(renderer, TextMessage, NULL, &Message_rect); //you put the renderer's name first, the Message, the crop size(you can ignore this if you don't want to dabble with cropping), and the rect which is the size and coordinate of your texture
    SDL_FreeSurface(surfaceMessage);
    SDL_DestroyTexture(TextMessage);
}

int round(float x)
{
    return (int)(x+0.5f);
}

int screenToHexX(int screenX)
{
    return (int)round((screenX - gridOriginX)/hexWidth);
}

int screenToHexY(int screenX, int screenY)
{
    int hexX = screenToHexX(screenX);
    if(hexX%2 == 0)
    {
        screenY -= (int)(hexHeight/2.0f);
    }
    return (int)round((screenY - gridOriginY)/hexHeight);
}

int hexToScreenX(int hexX)
{
    return gridOriginX + (int)(hexWidth*hexX);
}

int hexToScreenY(int hexX, int hexY)
{
    int result = gridOriginY + (int)(hexHeight*hexY);
    if(hexX%2 == 0)
    {
        result += (int)(hexHeight/2.0f);
    }
    return result;
}

int drawRegularHex(SDL_Renderer* renderer, int centreX, int centreY, int radius)
{
    SDL_Point hexPoints[7];
    for(int i=0; i<7; ++i)
    {
        float angle = (60.0f*i);
        float angle_rad = (PI/180) * angle;

        hexPoints[i].x = (int)(centreX + radius*cosf(angle_rad));
        hexPoints[i].y = (int)(centreY + radius*sinf(angle_rad));
    }
    return SDL_RenderDrawLines(renderer, hexPoints, 7);
}

void fillRect(SDL_Renderer* renderer, int centreX, int centreY, int width, int height)
{
    SDL_Rect rect;
    rect.x = centreX-width/2;
    rect.y = centreY-height/2;
    rect.w = width;
    rect.h = height;
    SDL_RenderFillRect(renderer, &rect);
}

void render(SDL_Renderer* renderer, GameState* gameState)
{
    // Clear to black
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    SDL_RenderClear(renderer);
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);

    // Draw Hex Grid
    for(int y=0; y<gridHeight; ++y)
    {
        for(int x=0; x<gridWidth; ++x)
        {
            int centreX = (int)(gridOriginX + x*hexWidth);
            int centreY = (int)(gridOriginY + y*hexHeight);
            if(x%2 == 0)
            {
                centreY += (int)(hexHeight/2.0f);
            }
            drawRegularHex(renderer, centreX, centreY, hexSize);

            char hexType = *((char*)gameState->map.data + (y*gameState->map.width + x));
            if(hexType != 'X')
            {
                int screenX = hexToScreenX(x);
                int screenY = hexToScreenY(x, y);
                fillRect(renderer, screenX, screenY, (int)(hexWidth/2), (int)(hexHeight/2));
            }
        }
    }

    // Draw player hex's
    int playerScreenX;
    int playerScreenY;
    playerScreenX = hexToScreenX(gameState->playerLoc[0].x);
    playerScreenY = hexToScreenY(gameState->playerLoc[0].x, gameState->playerLoc[0].y);
    SDL_SetRenderDrawColor(renderer, 255, 105, 97, 255);
    fillRect(renderer, playerScreenX, playerScreenY, (int)(hexWidth/2), (int)(hexHeight/2));
    playerScreenX = hexToScreenX(gameState->playerLoc[1].x);
    playerScreenY = hexToScreenY(gameState->playerLoc[1].x, gameState->playerLoc[1].y);
    SDL_SetRenderDrawColor(renderer, 97, 168, 255, 255);
    fillRect(renderer, playerScreenX, playerScreenY, (int)(hexWidth/2), (int)(hexHeight/2));

    // Draw Mouseover'd Hex
    int mouseX;
    int mouseY;
    SDL_GetMouseState(&mouseX, &mouseY);
    int mouseHexX = screenToHexX(mouseX);
    int mouseHexY = screenToHexY(mouseX, mouseY);
    if(mouseHexX < 0)
    {
        mouseHexX = 0;
    }
    else if(mouseHexX >= gridWidth)
    {
        mouseHexX = gridWidth-1;
    }
    if(mouseHexY < 0)
    {
        mouseHexY = 0;
    }
    else if(mouseHexY >= gridHeight)
    {
        mouseHexY = gridHeight-1;
    }
    int roundedMouseX = hexToScreenX(mouseHexX);
    int roundedMouseY = hexToScreenY(mouseHexX, mouseHexY);
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    fillRect(renderer, roundedMouseX, roundedMouseY, (int)(hexWidth/2), (int)(hexHeight/2));

    // Draw Text
    text(renderer, "HexRacer!", 650, 10);
    char p1VeloStr[4];
    char p2VeloStr[4];
    char toPlayStr[4];
    _itoa_s(gameState->playerVelocity[0], p1VeloStr, 10);
    _itoa_s(gameState->playerVelocity[1], p2VeloStr, 10);
    _itoa_s(gameState->currentPlayer+1, toPlayStr, 10);

    text(renderer, "P1Spd:", 650, 50);
    text(renderer, p1VeloStr, 750, 50);
    text(renderer, "P2Spd:", 650, 100);
    text(renderer, p2VeloStr, 750, 100);
    text(renderer, "To Play:", 650, 200);
    text(renderer, "Player ", 650, 230);
    text(renderer, toPlayStr, 760, 230);

    SDL_RenderPresent(renderer);
}

void SDLHandleEvent(SDL_Event* event, GameState* gameState)
{
    switch(event->type)
    {
        case SDL_QUIT:
        {
            running = false;
        } break;
        case SDL_KEYDOWN:
        case SDL_KEYUP:
        {
            SDL_Keycode keyCode = event->key.keysym.sym;
            if(keyCode == SDLK_a && !event->key.repeat && event->key.state == SDL_PRESSED)
            {
                printf("Accelerate\n");
                int deltaSpeed = (rand()%6)/2;
                gameState->playerVelocity[gameState->currentPlayer] += deltaSpeed;
                gameState->currentPlayer = (gameState->currentPlayer+1)%2;
            }
            else if(keyCode == SDLK_b && !event->key.repeat && event->key.state == SDL_PRESSED)
            {
                printf("Break\n");
                int deltaSpeed = (rand()%6)/2;
                gameState->playerVelocity[gameState->currentPlayer] -= deltaSpeed;
                if(gameState->playerVelocity[gameState->currentPlayer] < 1)
                {
                    gameState->playerVelocity[gameState->currentPlayer] = 1;
                }
                gameState->currentPlayer = (gameState->currentPlayer+1)%2;
            }
            if(keyCode == SDLK_ESCAPE)
            {
                running = false;
            }
        } break;
        case SDL_WINDOWEVENT:
        {
            switch(event->window.event)
            {
                case SDL_WINDOWEVENT_RESIZED:
                {
                } break;
            }
        } break;
        default:
        {
        } break;
    }
}

int main(int argc, char** argv)
{
    if(SDL_Init(SDL_INIT_VIDEO) != 0)
    {
        // Couldn't load SDL
        SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, "Error", "Unable to load SDL!", 0);
        return 1;
    }

    if(TTF_Init()==-1)
    {
        printf("TTF_Init: %s\n", TTF_GetError());
        return 1;
    }

    SDL_Window* window  = SDL_CreateWindow("Hex Racing", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
                                           800, 800, SDL_WINDOW_RESIZABLE);
    if(window)
    {
        SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);
        if(renderer)
        {
            srand((unsigned int)time(0));

            GameState gameState;
            loadMap("test.map", &gameState);

            gameState.currentPlayer = 0;
            gameState.playerVelocity[0] = 1;
            gameState.playerVelocity[1] = 1;

            font = TTF_OpenFont("ubuntumono.ttf", fontSize);

            running = true;
            while(running)
            {
                SDL_Event event;
                while(SDL_PollEvent(&event))
                {
                    SDLHandleEvent(&event, &gameState);
                }

                render(renderer, &gameState);
            }

            free(gameState.map.data);
        }
        else
        {
            // Couldn't create renderer
        }
    }
    else
    {
        // Couldn't create window
    }

    SDL_Quit();
    return 0;
}
<|endoftext|>


<commit_before><commit_msg>fix bad assertion<commit_after><|endoftext|>


<commit_before><commit_msg>Adding stdlib to CsvFile<commit_after><|endoftext|>


<commit_before><commit_msg>Bugfix for when last line is a comment<commit_after><|endoftext|>


<commit_before><commit_msg>Fix illegal variable name<commit_after><|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file LexPS.cxx
 ** Lexer for PostScript
 **
 ** Written by Nigel Hathaway <nigel@bprj.co.uk>.
 ** The License.txt file describes the conditions under which this software may be distributed.
 **/

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

static inline bool IsASelfDelimitingChar(const int ch) {
    return (ch == '[' || ch == ']' || ch == '{' || ch == '}' ||
            ch == '/' || ch == '<' || ch == '>' ||
            ch == '(' || ch == ')' || ch == '%');
}

static inline bool IsAWhitespaceChar(const int ch) {
    return (ch == ' '  || ch == '\t' || ch == '\r' ||
            ch == '\n' || ch == '\f' || ch == '\0');
}

static bool IsABaseNDigit(const int ch, const int base) {
    int maxdig = '9';
    int letterext = -1;

    if (base <= 10)
        maxdig = '0' + base - 1;
    else
        letterext = base - 11;

    return ((ch >= '0' && ch <= maxdig) ||
            (ch >= 'A' && ch <= ('A' + letterext)) ||
            (ch >= 'a' && ch <= ('a' + letterext)));
}

static inline bool IsABase85Char(const int ch) {
    return ((ch >= '!' && ch <= 'u') || ch == 'z');
}

static void ColourisePSDoc(
    unsigned int startPos,
    int length,
    int initStyle,
    WordList *keywordlists[],
    Accessor &styler) {

    WordList &keywords1 = *keywordlists[0];
    WordList &keywords2 = *keywordlists[1];
    WordList &keywords3 = *keywordlists[2];
    WordList &keywords4 = *keywordlists[3];
    WordList &keywords5 = *keywordlists[4];

    StyleContext sc(startPos, length, initStyle, styler);

    bool tokenizing = styler.GetPropertyInt("ps.tokenize") != 0;
    int pslevel = styler.GetPropertyInt("ps.level", 3);
    int lineCurrent = styler.GetLine(startPos);
    int nestTextCurrent = 0;
    if (lineCurrent > 0 && initStyle == SCE_PS_TEXT)
        nestTextCurrent = styler.GetLineState(lineCurrent - 1);
    int numRadix = 0;
    bool numHasPoint = false;
    bool numHasExponent = false;
    bool numHasSign = false;

    // Clear out existing tokenization
    if (tokenizing && length > 0) {
        styler.StartAt(startPos, static_cast<char>(INDIC2_MASK));
        styler.ColourTo(startPos + length-1, 0);
        styler.Flush();
        styler.StartAt(startPos);
        styler.StartSegment(startPos);
    }

    for (; sc.More(); sc.Forward()) {
        if (sc.atLineStart)
            lineCurrent = styler.GetLine(sc.currentPos);

        // Determine if the current state should terminate.
        if (sc.state == SCE_PS_COMMENT || sc.state == SCE_PS_DSC_VALUE) {
            if (sc.atLineEnd) {
                sc.SetState(SCE_C_DEFAULT);
            }
        } else if (sc.state == SCE_PS_DSC_COMMENT) {
            if (sc.ch == ':') {
                sc.Forward();
                if (!sc.atLineEnd)
                    sc.SetState(SCE_PS_DSC_VALUE);
                else
                    sc.SetState(SCE_C_DEFAULT);
            } else if (sc.atLineEnd) {
                sc.SetState(SCE_C_DEFAULT);
            } else if (IsAWhitespaceChar(sc.ch)) {
                sc.ChangeState(SCE_PS_COMMENT);
            }
        } else if (sc.state == SCE_PS_NUMBER) {
            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) {
                if ((sc.chPrev == '+' || sc.chPrev == '-' ||
                     sc.chPrev == 'E' || sc.chPrev == 'e') && numRadix == 0)
                    sc.ChangeState(SCE_PS_NAME);
                sc.SetState(SCE_C_DEFAULT);
            } else if (sc.ch == '#') {
                if (numHasPoint || numHasExponent || numHasSign || numRadix != 0) {
                    sc.ChangeState(SCE_PS_NAME);
                } else {
                    char szradix[5];
                    sc.GetCurrent(szradix, 4);
                    numRadix = atoi(szradix);
                    if (numRadix < 2 || numRadix > 36)
                        sc.ChangeState(SCE_PS_NAME);
                }
            } else if ((sc.ch == 'E' || sc.ch == 'e') && numRadix == 0) {
                if (numHasExponent) {
                    sc.ChangeState(SCE_PS_NAME);
                } else {
                    numHasExponent = true;
                    if (sc.chNext == '+' || sc.chNext == '-')
                        sc.Forward();
                }
            } else if (sc.ch == '.') {
                if (numHasPoint || numHasExponent || numRadix != 0) {
                    sc.ChangeState(SCE_PS_NAME);
                } else {
                    numHasPoint = true;
                }
            } else if (numRadix == 0) {
                if (!IsABaseNDigit(sc.ch, 10))
                    sc.ChangeState(SCE_PS_NAME);
            } else {
                if (!IsABaseNDigit(sc.ch, numRadix))
                    sc.ChangeState(SCE_PS_NAME);
            }
        } else if (sc.state == SCE_PS_NAME || sc.state == SCE_PS_KEYWORD) {
            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) {
                char s[100];
                sc.GetCurrent(s, sizeof(s));
                if ((pslevel >= 1 && keywords1.InList(s)) ||
                    (pslevel >= 2 && keywords2.InList(s)) ||
                    (pslevel >= 3 && keywords3.InList(s)) ||
                    keywords4.InList(s) || keywords5.InList(s)) {
                    sc.ChangeState(SCE_PS_KEYWORD);
                }
                sc.SetState(SCE_C_DEFAULT);
            }
        } else if (sc.state == SCE_PS_LITERAL || sc.state == SCE_PS_IMMEVAL) {
            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch))
                sc.SetState(SCE_C_DEFAULT);
        } else if (sc.state == SCE_PS_PAREN_ARRAY || sc.state == SCE_PS_PAREN_DICT ||
                   sc.state == SCE_PS_PAREN_PROC) {
            sc.SetState(SCE_C_DEFAULT);
        } else if (sc.state == SCE_PS_TEXT) {
            if (sc.ch == '(') {
                nestTextCurrent++;
            } else if (sc.ch == ')') {
                if (--nestTextCurrent == 0)
                   sc.ForwardSetState(SCE_PS_DEFAULT);
            } else if (sc.ch == '\\') {
                sc.Forward();
            }
        } else if (sc.state == SCE_PS_HEXSTRING) {
            if (sc.ch == '>') {
                sc.ForwardSetState(SCE_PS_DEFAULT);
            } else if (!IsABaseNDigit(sc.ch, 16) && !IsAWhitespaceChar(sc.ch)) {
                sc.SetState(SCE_PS_HEXSTRING);
                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
            }
        } else if (sc.state == SCE_PS_BASE85STRING) {
            if (sc.Match('~', '>')) {
                sc.Forward();
                sc.ForwardSetState(SCE_PS_DEFAULT);
            } else if (!IsABase85Char(sc.ch) && !IsAWhitespaceChar(sc.ch)) {
                sc.SetState(SCE_PS_BASE85STRING);
                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
            }
        }

        // Determine if a new state should be entered.
        if (sc.state == SCE_C_DEFAULT) {
            unsigned int tokenpos = sc.currentPos;

            if (sc.ch == '[' || sc.ch == ']') {
                sc.SetState(SCE_PS_PAREN_ARRAY);
            } else if (sc.ch == '{' || sc.ch == '}') {
                sc.SetState(SCE_PS_PAREN_PROC);
            } else if (sc.ch == '/') {
                if (sc.chNext == '/') {
                    sc.SetState(SCE_PS_IMMEVAL);
                    sc.Forward();
                } else {
                    sc.SetState(SCE_PS_LITERAL);
                }
            } else if (sc.ch == '<') {
                if (sc.chNext == '<') {
                    sc.SetState(SCE_PS_PAREN_DICT);
                    sc.Forward();
                } else if (sc.chNext == '~') {
                    sc.SetState(SCE_PS_BASE85STRING);
                    sc.Forward();
                } else {
                    sc.SetState(SCE_PS_HEXSTRING);
                }
            } else if (sc.ch == '>' && sc.chNext == '>') {
                    sc.SetState(SCE_PS_PAREN_DICT);
                    sc.Forward();
            } else if (sc.ch == '>' || sc.ch == ')') {
                sc.SetState(SCE_C_DEFAULT);
                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
            } else if (sc.ch == '(') {
                sc.SetState(SCE_PS_TEXT);
                nestTextCurrent = 1;
            } else if (sc.ch == '%') {
                if (sc.chNext == '%' && sc.atLineStart) {
                    sc.SetState(SCE_PS_DSC_COMMENT);
                    sc.Forward();
                    if (sc.chNext == '+') {
                        sc.Forward();
                        sc.ForwardSetState(SCE_PS_DSC_VALUE);
                    }
                } else {
                    sc.SetState(SCE_PS_COMMENT);
                }
            } else if ((sc.ch == '+' || sc.ch == '-' || sc.ch == '.') &&
                       IsABaseNDigit(sc.chNext, 10)) {
                sc.SetState(SCE_PS_NUMBER);
                numRadix = 0;
                numHasPoint = (sc.ch == '.');
                numHasExponent = false;
                numHasSign = (sc.ch == '+' || sc.ch == '-');
            } else if ((sc.ch == '+' || sc.ch == '-') && sc.chNext == '.' &&
                       IsABaseNDigit(sc.GetRelative(2), 10)) {
                sc.SetState(SCE_PS_NUMBER);
                numRadix = 0;
                numHasPoint = false;
                numHasExponent = false;
                numHasSign = true;
            } else if (IsABaseNDigit(sc.ch, 10)) {
                sc.SetState(SCE_PS_NUMBER);
                numRadix = 0;
                numHasPoint = false;
                numHasExponent = false;
                numHasSign = false;
            } else if (!IsAWhitespaceChar(sc.ch)) {
                sc.SetState(SCE_PS_NAME);
            }

            // Mark the start of tokens
            if (tokenizing && sc.state != SCE_C_DEFAULT && sc.state != SCE_PS_COMMENT &&
                sc.state != SCE_PS_DSC_COMMENT && sc.state != SCE_PS_DSC_VALUE) {
                styler.Flush();
                styler.StartAt(tokenpos, static_cast<char>(INDIC2_MASK));
                styler.ColourTo(tokenpos, INDIC2_MASK);
                styler.Flush();
                styler.StartAt(tokenpos);
                styler.StartSegment(tokenpos);
            }
        }

        if (sc.atLineEnd)
            styler.SetLineState(lineCurrent, nestTextCurrent);
    }

    sc.Complete();
}

static void FoldPSDoc(unsigned int startPos, int length, int, WordList *[],
                       Accessor &styler) {
    bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
    bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0;
    unsigned int endPos = startPos + length;
    int visibleChars = 0;
    int lineCurrent = styler.GetLine(startPos);
    int levelCurrent = SC_FOLDLEVELBASE;
    if (lineCurrent > 0)
        levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
    int levelMinCurrent = levelCurrent;
    int levelNext = levelCurrent;
    char chNext = styler[startPos];
    int styleNext = styler.StyleAt(startPos);
    int style;
    for (unsigned int i = startPos; i < endPos; i++) {
        char ch = chNext;
        chNext = styler.SafeGetCharAt(i + 1);
        style = styleNext;
        styleNext = styler.StyleAt(i + 1);
        bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');  //mac??
        if ((style & 31) == SCE_PS_PAREN_PROC) {
            if (ch == '{') {
                // Measure the minimum before a '{' to allow
                // folding on "} {"
                if (levelMinCurrent > levelNext) {
                    levelMinCurrent = levelNext;
                }
                levelNext++;
            } else if (ch == '}') {
                levelNext--;
            }
        }
        if (atEOL) {
            int levelUse = levelCurrent;
            if (foldAtElse) {
                levelUse = levelMinCurrent;
            }
            int lev = levelUse | levelNext << 16;
            if (visibleChars == 0 && foldCompact)
                lev |= SC_FOLDLEVELWHITEFLAG;
            if (levelUse < levelNext)
                lev |= SC_FOLDLEVELHEADERFLAG;
            if (lev != styler.LevelAt(lineCurrent)) {
                styler.SetLevel(lineCurrent, lev);
            }
            lineCurrent++;
            levelCurrent = levelNext;
            levelMinCurrent = levelCurrent;
            visibleChars = 0;
        }
        if (!isspacechar(ch))
            visibleChars++;
    }
}

static const char * const psWordListDesc[] = {
    "PS Level 1 operators",
    "PS Level 2 operators",
    "PS Level 3 operators",
    "RIP-specific operators",
    "User-defined operators",
    0
};

LexerModule lmPS(SCLEX_PS, ColourisePSDoc, "ps", FoldPSDoc, psWordListDesc);
<commit_msg>Patch from Kein-Hong Man fixes a CRLF glitch in LexPS.<commit_after>// Scintilla source code edit control
/** @file LexPS.cxx
 ** Lexer for PostScript
 **
 ** Written by Nigel Hathaway <nigel@bprj.co.uk>.
 ** The License.txt file describes the conditions under which this software may be distributed.
 **/

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

static inline bool IsASelfDelimitingChar(const int ch) {
    return (ch == '[' || ch == ']' || ch == '{' || ch == '}' ||
            ch == '/' || ch == '<' || ch == '>' ||
            ch == '(' || ch == ')' || ch == '%');
}

static inline bool IsAWhitespaceChar(const int ch) {
    return (ch == ' '  || ch == '\t' || ch == '\r' ||
            ch == '\n' || ch == '\f' || ch == '\0');
}

static bool IsABaseNDigit(const int ch, const int base) {
    int maxdig = '9';
    int letterext = -1;

    if (base <= 10)
        maxdig = '0' + base - 1;
    else
        letterext = base - 11;

    return ((ch >= '0' && ch <= maxdig) ||
            (ch >= 'A' && ch <= ('A' + letterext)) ||
            (ch >= 'a' && ch <= ('a' + letterext)));
}

static inline bool IsABase85Char(const int ch) {
    return ((ch >= '!' && ch <= 'u') || ch == 'z');
}

static void ColourisePSDoc(
    unsigned int startPos,
    int length,
    int initStyle,
    WordList *keywordlists[],
    Accessor &styler) {

    WordList &keywords1 = *keywordlists[0];
    WordList &keywords2 = *keywordlists[1];
    WordList &keywords3 = *keywordlists[2];
    WordList &keywords4 = *keywordlists[3];
    WordList &keywords5 = *keywordlists[4];

    StyleContext sc(startPos, length, initStyle, styler);

    bool tokenizing = styler.GetPropertyInt("ps.tokenize") != 0;
    int pslevel = styler.GetPropertyInt("ps.level", 3);
    int lineCurrent = styler.GetLine(startPos);
    int nestTextCurrent = 0;
    if (lineCurrent > 0 && initStyle == SCE_PS_TEXT)
        nestTextCurrent = styler.GetLineState(lineCurrent - 1);
    int numRadix = 0;
    bool numHasPoint = false;
    bool numHasExponent = false;
    bool numHasSign = false;

    // Clear out existing tokenization
    if (tokenizing && length > 0) {
        styler.StartAt(startPos, static_cast<char>(INDIC2_MASK));
        styler.ColourTo(startPos + length-1, 0);
        styler.Flush();
        styler.StartAt(startPos);
        styler.StartSegment(startPos);
    }

    for (; sc.More(); sc.Forward()) {
        if (sc.atLineStart)
            lineCurrent = styler.GetLine(sc.currentPos);

        // Determine if the current state should terminate.
        if (sc.state == SCE_PS_COMMENT || sc.state == SCE_PS_DSC_VALUE) {
            if (sc.atLineEnd) {
                sc.SetState(SCE_C_DEFAULT);
            }
        } else if (sc.state == SCE_PS_DSC_COMMENT) {
            if (sc.ch == ':') {
                sc.Forward();
                if (!sc.atLineEnd)
                    sc.SetState(SCE_PS_DSC_VALUE);
                else
                    sc.SetState(SCE_C_DEFAULT);
            } else if (sc.atLineEnd) {
                sc.SetState(SCE_C_DEFAULT);
            } else if (IsAWhitespaceChar(sc.ch) && sc.ch != '\r') {
                sc.ChangeState(SCE_PS_COMMENT);
            }
        } else if (sc.state == SCE_PS_NUMBER) {
            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) {
                if ((sc.chPrev == '+' || sc.chPrev == '-' ||
                     sc.chPrev == 'E' || sc.chPrev == 'e') && numRadix == 0)
                    sc.ChangeState(SCE_PS_NAME);
                sc.SetState(SCE_C_DEFAULT);
            } else if (sc.ch == '#') {
                if (numHasPoint || numHasExponent || numHasSign || numRadix != 0) {
                    sc.ChangeState(SCE_PS_NAME);
                } else {
                    char szradix[5];
                    sc.GetCurrent(szradix, 4);
                    numRadix = atoi(szradix);
                    if (numRadix < 2 || numRadix > 36)
                        sc.ChangeState(SCE_PS_NAME);
                }
            } else if ((sc.ch == 'E' || sc.ch == 'e') && numRadix == 0) {
                if (numHasExponent) {
                    sc.ChangeState(SCE_PS_NAME);
                } else {
                    numHasExponent = true;
                    if (sc.chNext == '+' || sc.chNext == '-')
                        sc.Forward();
                }
            } else if (sc.ch == '.') {
                if (numHasPoint || numHasExponent || numRadix != 0) {
                    sc.ChangeState(SCE_PS_NAME);
                } else {
                    numHasPoint = true;
                }
            } else if (numRadix == 0) {
                if (!IsABaseNDigit(sc.ch, 10))
                    sc.ChangeState(SCE_PS_NAME);
            } else {
                if (!IsABaseNDigit(sc.ch, numRadix))
                    sc.ChangeState(SCE_PS_NAME);
            }
        } else if (sc.state == SCE_PS_NAME || sc.state == SCE_PS_KEYWORD) {
            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) {
                char s[100];
                sc.GetCurrent(s, sizeof(s));
                if ((pslevel >= 1 && keywords1.InList(s)) ||
                    (pslevel >= 2 && keywords2.InList(s)) ||
                    (pslevel >= 3 && keywords3.InList(s)) ||
                    keywords4.InList(s) || keywords5.InList(s)) {
                    sc.ChangeState(SCE_PS_KEYWORD);
                }
                sc.SetState(SCE_C_DEFAULT);
            }
        } else if (sc.state == SCE_PS_LITERAL || sc.state == SCE_PS_IMMEVAL) {
            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch))
                sc.SetState(SCE_C_DEFAULT);
        } else if (sc.state == SCE_PS_PAREN_ARRAY || sc.state == SCE_PS_PAREN_DICT ||
                   sc.state == SCE_PS_PAREN_PROC) {
            sc.SetState(SCE_C_DEFAULT);
        } else if (sc.state == SCE_PS_TEXT) {
            if (sc.ch == '(') {
                nestTextCurrent++;
            } else if (sc.ch == ')') {
                if (--nestTextCurrent == 0)
                   sc.ForwardSetState(SCE_PS_DEFAULT);
            } else if (sc.ch == '\\') {
                sc.Forward();
            }
        } else if (sc.state == SCE_PS_HEXSTRING) {
            if (sc.ch == '>') {
                sc.ForwardSetState(SCE_PS_DEFAULT);
            } else if (!IsABaseNDigit(sc.ch, 16) && !IsAWhitespaceChar(sc.ch)) {
                sc.SetState(SCE_PS_HEXSTRING);
                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
            }
        } else if (sc.state == SCE_PS_BASE85STRING) {
            if (sc.Match('~', '>')) {
                sc.Forward();
                sc.ForwardSetState(SCE_PS_DEFAULT);
            } else if (!IsABase85Char(sc.ch) && !IsAWhitespaceChar(sc.ch)) {
                sc.SetState(SCE_PS_BASE85STRING);
                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
            }
        }

        // Determine if a new state should be entered.
        if (sc.state == SCE_C_DEFAULT) {
            unsigned int tokenpos = sc.currentPos;

            if (sc.ch == '[' || sc.ch == ']') {
                sc.SetState(SCE_PS_PAREN_ARRAY);
            } else if (sc.ch == '{' || sc.ch == '}') {
                sc.SetState(SCE_PS_PAREN_PROC);
            } else if (sc.ch == '/') {
                if (sc.chNext == '/') {
                    sc.SetState(SCE_PS_IMMEVAL);
                    sc.Forward();
                } else {
                    sc.SetState(SCE_PS_LITERAL);
                }
            } else if (sc.ch == '<') {
                if (sc.chNext == '<') {
                    sc.SetState(SCE_PS_PAREN_DICT);
                    sc.Forward();
                } else if (sc.chNext == '~') {
                    sc.SetState(SCE_PS_BASE85STRING);
                    sc.Forward();
                } else {
                    sc.SetState(SCE_PS_HEXSTRING);
                }
            } else if (sc.ch == '>' && sc.chNext == '>') {
                    sc.SetState(SCE_PS_PAREN_DICT);
                    sc.Forward();
            } else if (sc.ch == '>' || sc.ch == ')') {
                sc.SetState(SCE_C_DEFAULT);
                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
            } else if (sc.ch == '(') {
                sc.SetState(SCE_PS_TEXT);
                nestTextCurrent = 1;
            } else if (sc.ch == '%') {
                if (sc.chNext == '%' && sc.atLineStart) {
                    sc.SetState(SCE_PS_DSC_COMMENT);
                    sc.Forward();
                    if (sc.chNext == '+') {
                        sc.Forward();
                        sc.ForwardSetState(SCE_PS_DSC_VALUE);
                    }
                } else {
                    sc.SetState(SCE_PS_COMMENT);
                }
            } else if ((sc.ch == '+' || sc.ch == '-' || sc.ch == '.') &&
                       IsABaseNDigit(sc.chNext, 10)) {
                sc.SetState(SCE_PS_NUMBER);
                numRadix = 0;
                numHasPoint = (sc.ch == '.');
                numHasExponent = false;
                numHasSign = (sc.ch == '+' || sc.ch == '-');
            } else if ((sc.ch == '+' || sc.ch == '-') && sc.chNext == '.' &&
                       IsABaseNDigit(sc.GetRelative(2), 10)) {
                sc.SetState(SCE_PS_NUMBER);
                numRadix = 0;
                numHasPoint = false;
                numHasExponent = false;
                numHasSign = true;
            } else if (IsABaseNDigit(sc.ch, 10)) {
                sc.SetState(SCE_PS_NUMBER);
                numRadix = 0;
                numHasPoint = false;
                numHasExponent = false;
                numHasSign = false;
            } else if (!IsAWhitespaceChar(sc.ch)) {
                sc.SetState(SCE_PS_NAME);
            }

            // Mark the start of tokens
            if (tokenizing && sc.state != SCE_C_DEFAULT && sc.state != SCE_PS_COMMENT &&
                sc.state != SCE_PS_DSC_COMMENT && sc.state != SCE_PS_DSC_VALUE) {
                styler.Flush();
                styler.StartAt(tokenpos, static_cast<char>(INDIC2_MASK));
                styler.ColourTo(tokenpos, INDIC2_MASK);
                styler.Flush();
                styler.StartAt(tokenpos);
                styler.StartSegment(tokenpos);
            }
        }

        if (sc.atLineEnd)
            styler.SetLineState(lineCurrent, nestTextCurrent);
    }

    sc.Complete();
}

static void FoldPSDoc(unsigned int startPos, int length, int, WordList *[],
                       Accessor &styler) {
    bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
    bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0;
    unsigned int endPos = startPos + length;
    int visibleChars = 0;
    int lineCurrent = styler.GetLine(startPos);
    int levelCurrent = SC_FOLDLEVELBASE;
    if (lineCurrent > 0)
        levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
    int levelMinCurrent = levelCurrent;
    int levelNext = levelCurrent;
    char chNext = styler[startPos];
    int styleNext = styler.StyleAt(startPos);
    int style;
    for (unsigned int i = startPos; i < endPos; i++) {
        char ch = chNext;
        chNext = styler.SafeGetCharAt(i + 1);
        style = styleNext;
        styleNext = styler.StyleAt(i + 1);
        bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');  //mac??
        if ((style & 31) == SCE_PS_PAREN_PROC) {
            if (ch == '{') {
                // Measure the minimum before a '{' to allow
                // folding on "} {"
                if (levelMinCurrent > levelNext) {
                    levelMinCurrent = levelNext;
                }
                levelNext++;
            } else if (ch == '}') {
                levelNext--;
            }
        }
        if (atEOL) {
            int levelUse = levelCurrent;
            if (foldAtElse) {
                levelUse = levelMinCurrent;
            }
            int lev = levelUse | levelNext << 16;
            if (visibleChars == 0 && foldCompact)
                lev |= SC_FOLDLEVELWHITEFLAG;
            if (levelUse < levelNext)
                lev |= SC_FOLDLEVELHEADERFLAG;
            if (lev != styler.LevelAt(lineCurrent)) {
                styler.SetLevel(lineCurrent, lev);
            }
            lineCurrent++;
            levelCurrent = levelNext;
            levelMinCurrent = levelCurrent;
            visibleChars = 0;
        }
        if (!isspacechar(ch))
            visibleChars++;
    }
}

static const char * const psWordListDesc[] = {
    "PS Level 1 operators",
    "PS Level 2 operators",
    "PS Level 3 operators",
    "RIP-specific operators",
    "User-defined operators",
    0
};

LexerModule lmPS(SCLEX_PS, ColourisePSDoc, "ps", FoldPSDoc, psWordListDesc);
<|endoftext|>


<commit_before>#include "Macro.h"
#include "BlackCrow.h"
#include "Planned.h"
#include "Worker.h"
#include <numeric>

namespace BlackCrow {

	using namespace BWAPI;
	using namespace Filter;

	Macro::Macro(BlackCrow &parent) : bc(parent) {}

	void Macro::onStart() {
		initBases();
		startPosition = getStartingHatchery()->getPosition();
	}

	void Macro::onFrame() {
		for (auto it = plannedStuff.begin(); it != plannedStuff.end();) {
			std::shared_ptr<Planned> planned = *it;
			planned->onFrame();
			if (planned->getStatus() == Planned::Status::FAILED || planned->getStatus() == Planned::Status::COMPLETED) {
				it = plannedStuff.erase(it);
			} else {
				it++;
			}
		}
	}

	void Macro::onUnitCompleted(BWAPI::Unit unit) {
		if (unit->getType() == UnitTypes::Zerg_Hatchery)
			hatcheries.push_back(unit);
	}

	void Macro::onUnitDestroyed(BWAPI::Unit unit) {
		if (unit->getType() == UnitTypes::Zerg_Hatchery || unit->getType() == UnitTypes::Zerg_Lair || unit->getType() == UnitTypes::Zerg_Hive)
			hatcheries.erase(std::remove(hatcheries.begin(), hatcheries.end(), unit), hatcheries.end());

		for (Base& base : bases) {
			if (base.onUnitDestroyed(unit))
				break;
		}
	}

	// Planned
	std::shared_ptr<PlannedUnit> Macro::planUnit(BWAPI::UnitType type, BWAPI::Position nearTo) {
		auto unit = std::make_shared<PlannedUnit>(bc, type, nearTo);
		plannedStuff.push_back(unit);
		return unit;
	}

	std::shared_ptr<PlannedBuilding> Macro::planBuilding(BWAPI::UnitType type, BWAPI::TilePosition buildPosition) {
		auto building = std::make_shared<PlannedBuilding>(bc, type, buildPosition);
		plannedStuff.push_back(building);
		return building;
	}

	std::shared_ptr<PlannedExtractor> Macro::planExtractor(Geyser& geyser) {
		auto extractor = std::make_shared<PlannedExtractor>(bc, geyser);
		plannedStuff.push_back(extractor);
		return extractor;
	}

	int Macro::getTypeCurrentlyPlanned(BWAPI::UnitType type) {
		return std::accumulate(plannedStuff.begin(), plannedStuff.end(), 0, [&](int sum, std::shared_ptr<Planned> planned) {

			if (type == UnitTypes::Zerg_Extractor) {
				// TODO typeof comparison here?
				std::shared_ptr<PlannedExtractor> plannedExtractor = std::dynamic_pointer_cast<PlannedExtractor>(planned);
				if (plannedExtractor)
					return ++sum;
			}

			std::shared_ptr<PlannedUnit> plannedUnit = std::dynamic_pointer_cast<PlannedUnit>(planned);
			if (plannedUnit && plannedUnit->type == type)
				return ++sum;

			std::shared_ptr<PlannedBuilding> plannedBuilding = std::dynamic_pointer_cast<PlannedBuilding>(planned);
			if (plannedBuilding && plannedBuilding->type == type)
				return ++sum;

			std::shared_ptr<PlannedUpgrade> plannedUpgrade = std::dynamic_pointer_cast<PlannedUpgrade>(planned);
			if (plannedUpgrade && plannedUpgrade->type == type)
				return ++sum;

			std::shared_ptr<PlannedTech> plannedTech = std::dynamic_pointer_cast<PlannedTech>(planned);
			if (plannedTech && plannedTech->type == type)
				return ++sum;

			return sum;
		});
	}

	// Expansions and Bases // TODO Need enemy information to do this
	Base& Macro::getSafestToExpand() {
		return bases.front();
	}

	void Macro::expand() {

	}

	int Macro::getNumberOfCurrentlyExpandingBases() {
		return 0;
	}

	int Macro::getNumberOfEstablishedBases() {
		return 0;
	}

	Base& Macro::getSafestEstablishedBase() {
		for (Base& base : bases) {
			if (base.isEstablished())
				return base;
		}
		return bases.front();
	}
	// TODO end

	Base& Macro::getNearestBase(BWAPI::Position position) { // Is there a better, or templatey/lambda way?
		Base* closestBase = nullptr;
		double closestDistance = std::numeric_limits<double>::max();
		for(Base& base : bases) {
			if (base.isEstablished()) {
				double distance = Util::distance(base.bwemBase.Center(), position);
				if (distance < closestDistance) {
					closestDistance = distance;
					closestBase = &base;
				}
			}
		}
		return *closestBase;
	}

	// Worker
	int Macro::getTotalWorkers() {
		return std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getTotalWorkers(); });
	}

	int Macro::getMineralWorkers() {
		return std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getTotalMineralWorkers(); });
	}

	int Macro::getGasWorkers() {
		return std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getTotalGasWorkers(); });
	}

	bool Macro::isWorkerNeededForSaturation() {
		return std::any_of(bases.begin(), bases.end(), [](Base& base) { return base.isWorkerNeeded(); });
	}

	int Macro::getWorkersNeededForSaturation() {
		return std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getWorkersNeeded(); });
	}

	void Macro::buildWorkerDrone() {
		auto base = std::find_if(bases.begin(), bases.end(), [](Base& base) { return base.isWorkerNeeded(); });
		planUnit(UnitTypes::Zerg_Drone, base->bwemBase.Center());
	}

	void Macro::addDrone(BWAPI::Unit drone) {
		Base* closestEstablished = nullptr;
		double closestEstablishedDistance = std::numeric_limits<double>::max();

		Base* closestEstablishedWorkerNeeded = nullptr;
		double closestEstablishedWorkerNeededDistance = std::numeric_limits<double>::max();

		for (Base& base : bases) {
			if (base.isEstablished()) {

				// Get any base where we can put a worker if we have no base that needs a worker
				if (!closestEstablished) {
					closestEstablished = &base;
					closestEstablishedDistance = Util::distance(closestEstablished->bwemBase.Center(), drone->getPosition());
				}

				// If the base needs worker and is closer, use it
				if (base.isWorkerNeeded()) {
					double distance = Util::distance(base.bwemBase.Center(), drone->getPosition());
					if (distance < closestEstablishedWorkerNeededDistance) {
						closestEstablishedWorkerNeeded = &base;
						closestEstablishedWorkerNeededDistance = distance;
					}
				}

				// If we have no closest base that needs worker, check if the current established base is closest and if yes, use it
				if (!closestEstablishedWorkerNeeded) {
					double distance = Util::distance(base.bwemBase.Center(), drone->getPosition());
					if (distance < closestEstablishedDistance) {
						closestEstablishedDistance = distance;
						closestEstablished = &base;
					}
				}
			}
		}

		if (closestEstablishedWorkerNeeded)
			closestEstablishedWorkerNeeded->addWorker(drone);
		else if(closestEstablished)
			closestEstablished->addWorker(drone);
			// If not, I guess we are dead
	}

	BWAPI::Unit Macro::getDroneForBuilding(BWAPI::Position position) {
		// Predicates for getNearestBase, we want to have workers here
		return getNearestBase(position).removeWorker(position);
	}

	// Gas
	int Macro::getGasWorkerSlotsAvailable() {
		return std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getGasWorkerSlotsAvailable(); });
	}

	int Macro::getExtractorsAbleToBuild() {
		return std::accumulate(bases.begin(), bases.end(), 0, [&](int sum, Base& base) { return sum + base.getExtractorsAbleToBuild(); });
	}

	void Macro::buildExtractor() { // TODO build extractor at safeset base
		for (Base& base : bases) {
			if (base.isEstablished()) {
				for (Geyser& geyser : base.geysers) {
					if (geyser.isBuildable()) {
						planExtractor(geyser);
							return;
					}
				}
			}
		}
	}

	void Macro::addGasWorker() {

	}

	void Macro::removeGasWorker() {

	}

	// Larva
	int Macro::getTotalLarvaeAmount() {
		return 0;
	}

	BWAPI::Unit Macro::getUnreservedLarva(Position nearTo) {
		std::vector<BWAPI::Unit> url = getUnreservedLarvae();
		if (url.size() > 0)
			return Util::findClosestUnit(url, nearTo);
		else
		return nullptr;
	}

	int Macro::getUnreservedLarvaeAmount() {
		return getUnreservedLarvae().size();
	}

	// Estimates
	Resources Macro::getUnreservedResources() {
		Resources resources = { Broodwar->self()->minerals(), Broodwar->self()->gas() };

		for (std::shared_ptr<Planned> planned : plannedStuff) {
			resources.minerals -= planned->getMineralPrice();
			resources.gas -= planned->getGasPrice();
		}

		return resources;
	}

	double Macro::getAverageMineralsPerFrame() {
		return 0;
	}

	double Macro::getAverageGasPerFrame() {
		return 0;
	}

	// Private
	void Macro::initBases() {
		for (const BWEM::Area& bwemArea : bc.bwem.Areas()) {

			Area& area = bc.map.getArea(bwemArea);
			for (const BWEM::Base& bwemBase : bwemArea.Bases()) {
				bases.emplace_back(bc, bwemBase, area);
				Base& base = bases.back();

				// Starting Base
				if (bwemBase.Starting()) {
					BWAPI::Unit startingHatchery = getStartingHatchery();
					if (bwemBase.Location() == startingHatchery->getTilePosition()) {

						base.hatchery = startingHatchery;
						Unitset drones = Broodwar->getUnitsInRadius(startingHatchery->getPosition(), 350, BWAPI::Filter::IsWorker);

						for (Unit drone : drones) {
							base.addWorker(drone);
						}
					}
				}
			}
		}

		for (Base& base : bases)
			if (base.hatchery)
				for (Worker& worker : base.workers)
					if (worker.mineral && worker.mineral->id <= 0) {
						// TODO BIG BIG ERROR
						//assert(!"Wrong mineral ids!");
						Broodwar->sendText("!!!!! Error! Wrong Mineral IDs! !!!!!");
					}
	}

	BWAPI::Unit Macro::getStartingHatchery() {
		for (auto &unit : Broodwar->self()->getUnits()) {
			if (unit->getType().isResourceDepot()) {
				return unit;
			}
		}
		return nullptr;
	}

	std::vector<BWAPI::Unit> Macro::getAllLarvae() {
		std::vector<BWAPI::Unit> allLarvae;

		for (Unit hatchery : hatcheries) {
			Unitset hatchLarvae = hatchery->getLarva();
			std::copy(hatchLarvae.begin(), hatchLarvae.end(), std::back_inserter(allLarvae));
		}
		return allLarvae;
	}

	std::vector<BWAPI::Unit> Macro::getReservedLarvae() {
		std::vector<BWAPI::Unit> reservedLarvae;

		// TODO this doesn't look good
		for (std::shared_ptr<Planned> planned : plannedStuff) {
			std::shared_ptr<PlannedUnit> pu = std::dynamic_pointer_cast<PlannedUnit>(planned); // TODO Dynamic Cast is bad?
			if (pu) {
				Unit larva = pu->reservedLarva();
				if (larva)
					reservedLarvae.push_back(larva); // Can you push a nullptr?
			}
		}

		return reservedLarvae;
	}

	std::vector<BWAPI::Unit> Macro::getUnreservedLarvae() {
		std::vector<BWAPI::Unit> allLarvae = getAllLarvae();
		std::vector<BWAPI::Unit> reservedLarvae = getReservedLarvae();
		std::vector<BWAPI::Unit> unreservedLarvae;

		std::sort(allLarvae.begin(), allLarvae.end());
		std::sort(reservedLarvae.begin(), reservedLarvae.end());
		std::set_difference(allLarvae.begin(), allLarvae.end(), reservedLarvae.begin(), reservedLarvae.end(), std::inserter(unreservedLarvae, unreservedLarvae.begin()));

		return unreservedLarvae;
	}
}<commit_msg>Implemented getTotalLarvaeAmount()<commit_after>#include "Macro.h"
#include "BlackCrow.h"
#include "Planned.h"
#include "Worker.h"
#include <numeric>

namespace BlackCrow {

	using namespace BWAPI;
	using namespace Filter;

	Macro::Macro(BlackCrow &parent) : bc(parent) {}

	void Macro::onStart() {
		initBases();
		startPosition = getStartingHatchery()->getPosition();
	}

	void Macro::onFrame() {
		for (auto it = plannedStuff.begin(); it != plannedStuff.end();) {
			std::shared_ptr<Planned> planned = *it;
			planned->onFrame();
			if (planned->getStatus() == Planned::Status::FAILED || planned->getStatus() == Planned::Status::COMPLETED) {
				it = plannedStuff.erase(it);
			} else {
				it++;
			}
		}
	}

	void Macro::onUnitCompleted(BWAPI::Unit unit) {
		if (unit->getType() == UnitTypes::Zerg_Hatchery)
			hatcheries.push_back(unit);
	}

	void Macro::onUnitDestroyed(BWAPI::Unit unit) {
		if (unit->getType() == UnitTypes::Zerg_Hatchery || unit->getType() == UnitTypes::Zerg_Lair || unit->getType() == UnitTypes::Zerg_Hive)
			hatcheries.erase(std::remove(hatcheries.begin(), hatcheries.end(), unit), hatcheries.end());

		for (Base& base : bases) {
			if (base.onUnitDestroyed(unit))
				break;
		}
	}

	// Planned
	std::shared_ptr<PlannedUnit> Macro::planUnit(BWAPI::UnitType type, BWAPI::Position nearTo) {
		auto unit = std::make_shared<PlannedUnit>(bc, type, nearTo);
		plannedStuff.push_back(unit);
		return unit;
	}

	std::shared_ptr<PlannedBuilding> Macro::planBuilding(BWAPI::UnitType type, BWAPI::TilePosition buildPosition) {
		auto building = std::make_shared<PlannedBuilding>(bc, type, buildPosition);
		plannedStuff.push_back(building);
		return building;
	}

	std::shared_ptr<PlannedExtractor> Macro::planExtractor(Geyser& geyser) {
		auto extractor = std::make_shared<PlannedExtractor>(bc, geyser);
		plannedStuff.push_back(extractor);
		return extractor;
	}

	int Macro::getTypeCurrentlyPlanned(BWAPI::UnitType type) {
		return std::accumulate(plannedStuff.begin(), plannedStuff.end(), 0, [&](int sum, std::shared_ptr<Planned> planned) {

			if (type == UnitTypes::Zerg_Extractor) {
				// TODO typeof comparison here?
				std::shared_ptr<PlannedExtractor> plannedExtractor = std::dynamic_pointer_cast<PlannedExtractor>(planned);
				if (plannedExtractor)
					return ++sum;
			}

			std::shared_ptr<PlannedUnit> plannedUnit = std::dynamic_pointer_cast<PlannedUnit>(planned);
			if (plannedUnit && plannedUnit->type == type)
				return ++sum;

			std::shared_ptr<PlannedBuilding> plannedBuilding = std::dynamic_pointer_cast<PlannedBuilding>(planned);
			if (plannedBuilding && plannedBuilding->type == type)
				return ++sum;

			std::shared_ptr<PlannedUpgrade> plannedUpgrade = std::dynamic_pointer_cast<PlannedUpgrade>(planned);
			if (plannedUpgrade && plannedUpgrade->type == type)
				return ++sum;

			std::shared_ptr<PlannedTech> plannedTech = std::dynamic_pointer_cast<PlannedTech>(planned);
			if (plannedTech && plannedTech->type == type)
				return ++sum;

			return sum;
		});
	}

	// Expansions and Bases // TODO Need enemy information to do this
	Base& Macro::getSafestToExpand() {
		return bases.front();
	}

	void Macro::expand() {

	}

	int Macro::getNumberOfCurrentlyExpandingBases() {
		return 0;
	}

	int Macro::getNumberOfEstablishedBases() {
		return 0;
	}

	Base& Macro::getSafestEstablishedBase() {
		for (Base& base : bases) {
			if (base.isEstablished())
				return base;
		}
		return bases.front();
	}
	// TODO end

	Base& Macro::getNearestBase(BWAPI::Position position) { // Is there a better, or templatey/lambda way?
		Base* closestBase = nullptr;
		double closestDistance = std::numeric_limits<double>::max();
		for(Base& base : bases) {
			if (base.isEstablished()) {
				double distance = Util::distance(base.bwemBase.Center(), position);
				if (distance < closestDistance) {
					closestDistance = distance;
					closestBase = &base;
				}
			}
		}
		return *closestBase;
	}

	// Worker
	int Macro::getTotalWorkers() {
		return std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getTotalWorkers(); });
	}

	int Macro::getMineralWorkers() {
		return std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getTotalMineralWorkers(); });
	}

	int Macro::getGasWorkers() {
		return std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getTotalGasWorkers(); });
	}

	bool Macro::isWorkerNeededForSaturation() {
		return std::any_of(bases.begin(), bases.end(), [](Base& base) { return base.isWorkerNeeded(); });
	}

	int Macro::getWorkersNeededForSaturation() {
		return std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getWorkersNeeded(); });
	}

	void Macro::buildWorkerDrone() {
		auto base = std::find_if(bases.begin(), bases.end(), [](Base& base) { return base.isWorkerNeeded(); });
		planUnit(UnitTypes::Zerg_Drone, base->bwemBase.Center());
	}

	void Macro::addDrone(BWAPI::Unit drone) {
		Base* closestEstablished = nullptr;
		double closestEstablishedDistance = std::numeric_limits<double>::max();

		Base* closestEstablishedWorkerNeeded = nullptr;
		double closestEstablishedWorkerNeededDistance = std::numeric_limits<double>::max();

		for (Base& base : bases) {
			if (base.isEstablished()) {

				// Get any base where we can put a worker if we have no base that needs a worker
				if (!closestEstablished) {
					closestEstablished = &base;
					closestEstablishedDistance = Util::distance(closestEstablished->bwemBase.Center(), drone->getPosition());
				}

				// If the base needs worker and is closer, use it
				if (base.isWorkerNeeded()) {
					double distance = Util::distance(base.bwemBase.Center(), drone->getPosition());
					if (distance < closestEstablishedWorkerNeededDistance) {
						closestEstablishedWorkerNeeded = &base;
						closestEstablishedWorkerNeededDistance = distance;
					}
				}

				// If we have no closest base that needs worker, check if the current established base is closest and if yes, use it
				if (!closestEstablishedWorkerNeeded) {
					double distance = Util::distance(base.bwemBase.Center(), drone->getPosition());
					if (distance < closestEstablishedDistance) {
						closestEstablishedDistance = distance;
						closestEstablished = &base;
					}
				}
			}
		}

		if (closestEstablishedWorkerNeeded)
			closestEstablishedWorkerNeeded->addWorker(drone);
		else if(closestEstablished)
			closestEstablished->addWorker(drone);
			// If not, I guess we are dead
	}

	BWAPI::Unit Macro::getDroneForBuilding(BWAPI::Position position) {
		// Predicates for getNearestBase, we want to have workers here
		return getNearestBase(position).removeWorker(position);
	}

	// Gas
	int Macro::getGasWorkerSlotsAvailable() {
		return std::accumulate(bases.begin(), bases.end(), 0, [](int sum, Base& base) { return sum + base.getGasWorkerSlotsAvailable(); });
	}

	int Macro::getExtractorsAbleToBuild() {
		return std::accumulate(bases.begin(), bases.end(), 0, [&](int sum, Base& base) { return sum + base.getExtractorsAbleToBuild(); });
	}

	void Macro::buildExtractor() { // TODO build extractor at safeset base
		for (Base& base : bases) {
			if (base.isEstablished()) {
				for (Geyser& geyser : base.geysers) {
					if (geyser.isBuildable()) {
						planExtractor(geyser);
							return;
					}
				}
			}
		}
	}

	void Macro::addGasWorker() {

	}

	void Macro::removeGasWorker() {

	}

	// Larva
	int Macro::getTotalLarvaeAmount() {
		return getAllLarvae().size();
	}

	// Can return nullptr
	BWAPI::Unit Macro::getUnreservedLarva(Position nearTo) {
		std::vector<BWAPI::Unit> url = getUnreservedLarvae();
		if (url.size() > 0)
			return Util::findClosestUnit(url, nearTo);
		else
		return nullptr;
	}

	int Macro::getUnreservedLarvaeAmount() {
		return getUnreservedLarvae().size();
	}

	// Estimates
	Resources Macro::getUnreservedResources() {
		Resources resources = { Broodwar->self()->minerals(), Broodwar->self()->gas() };

		for (std::shared_ptr<Planned> planned : plannedStuff) {
			resources.minerals -= planned->getMineralPrice();
			resources.gas -= planned->getGasPrice();
		}

		return resources;
	}

	double Macro::getAverageMineralsPerFrame() {
		return 0;
	}

	double Macro::getAverageGasPerFrame() {
		return 0;
	}

	// Private
	void Macro::initBases() {
		for (const BWEM::Area& bwemArea : bc.bwem.Areas()) {

			Area& area = bc.map.getArea(bwemArea);
			for (const BWEM::Base& bwemBase : bwemArea.Bases()) {
				bases.emplace_back(bc, bwemBase, area);
				Base& base = bases.back();

				// Starting Base
				if (bwemBase.Starting()) {
					BWAPI::Unit startingHatchery = getStartingHatchery();
					if (bwemBase.Location() == startingHatchery->getTilePosition()) {

						base.hatchery = startingHatchery;
						Unitset drones = Broodwar->getUnitsInRadius(startingHatchery->getPosition(), 350, BWAPI::Filter::IsWorker);

						for (Unit drone : drones) {
							base.addWorker(drone);
						}
					}
				}
			}
		}

		for (Base& base : bases)
			if (base.hatchery)
				for (Worker& worker : base.workers)
					if (worker.mineral && worker.mineral->id <= 0) {
						// TODO BIG BIG ERROR
						//assert(!"Wrong mineral ids!");
						Broodwar->sendText("!!!!! Error! Wrong Mineral IDs! !!!!!");
					}
	}

	BWAPI::Unit Macro::getStartingHatchery() {
		for (auto &unit : Broodwar->self()->getUnits()) {
			if (unit->getType().isResourceDepot()) {
				return unit;
			}
		}
		return nullptr;
	}

	std::vector<BWAPI::Unit> Macro::getAllLarvae() {
		std::vector<BWAPI::Unit> allLarvae;

		for (Unit hatchery : hatcheries) {
			Unitset hatchLarvae = hatchery->getLarva();
			std::copy(hatchLarvae.begin(), hatchLarvae.end(), std::back_inserter(allLarvae));
		}
		return allLarvae;
	}

	std::vector<BWAPI::Unit> Macro::getReservedLarvae() {
		std::vector<BWAPI::Unit> reservedLarvae;

		// TODO this doesn't look good
		for (std::shared_ptr<Planned> planned : plannedStuff) {
			std::shared_ptr<PlannedUnit> pu = std::dynamic_pointer_cast<PlannedUnit>(planned); // TODO Dynamic Cast is bad?
			if (pu) {
				Unit larva = pu->reservedLarva();
				if (larva)
					reservedLarvae.push_back(larva); // Can you push a nullptr?
			}
		}

		return reservedLarvae;
	}

	std::vector<BWAPI::Unit> Macro::getUnreservedLarvae() {
		std::vector<BWAPI::Unit> allLarvae = getAllLarvae();
		std::vector<BWAPI::Unit> reservedLarvae = getReservedLarvae();
		std::vector<BWAPI::Unit> unreservedLarvae;

		std::sort(allLarvae.begin(), allLarvae.end());
		std::sort(reservedLarvae.begin(), reservedLarvae.end());
		std::set_difference(allLarvae.begin(), allLarvae.end(), reservedLarvae.begin(), reservedLarvae.end(), std::inserter(unreservedLarvae, unreservedLarvae.begin()));

		return unreservedLarvae;
	}
}<|endoftext|>


<commit_before><commit_msg>prepare: remove also calls to __VERIFIER_assert in RemoveErrorCalls pass<commit_after><|endoftext|>


<commit_before>#include "stdafx.h"
#include "model.h"

Model::Model(DeviceResources* resources)
{
	m_pDeviceResources = shared_ptr<DeviceResources>(resources);
}

Model::~Model()
{

}

HRESULT Model::Initialize()
{
	auto result = LoadModelFromFBXFile("../Models/teapot.fbx");
	if (FAILED(result))
	{
		return result;
	}

	//auto result = InitializeVertexBuffer();
	//if (FAILED(result))
	//{
	//	return result;
	//}

	//result = InitializeIndexBuffer(NULL);
	//if (FAILED(result))
	//{
	//	return result;
	//}

	return InitializeConstantBuffer();
}

HRESULT Model::LoadModelFromFBXFile(char* fileName)
{
	Debug::WriteCurrentDir();
	auto sdkManager = FbxManager::Create();

	auto fbxIOsettings = FbxIOSettings::Create(sdkManager, IOSROOT);
	sdkManager->SetIOSettings(fbxIOsettings);
	fbxIOsettings->SetBoolProp(IMP_FBX_MATERIAL, false);
	fbxIOsettings->SetBoolProp(IMP_FBX_TEXTURE, false);
	fbxIOsettings->SetBoolProp(IMP_FBX_ANIMATION, false);
	fbxIOsettings->SetBoolProp(IMP_FBX_TEXTURE, false);

	auto fbxImporter = FbxImporter::Create(sdkManager, "");
	auto fbxScene = FbxScene::Create(sdkManager, "");

	auto success = fbxImporter->Initialize(fileName, -1, sdkManager->GetIOSettings());
	if (!success)
	{
		return success;
	}

	success = fbxImporter->Import(fbxScene);
	fbxImporter->Destroy();

	if (!success)
	{
		return success;
	}

	auto axisSystem = fbxScene->GetGlobalSettings().GetAxisSystem();

	auto fbxRootNode = fbxScene->GetRootNode();
	auto count = fbxRootNode->GetChildCount();

	auto modelVertices = new vector<Vertex>();
	auto modelIndexes = new vector<unsigned int>();

	// The scene maybe
	for (auto s = 0; s < count; s++)
	{
		auto child = fbxRootNode->GetChild(s);
		auto childName = child->GetName();
		auto childCount = child->GetChildCount();

		// For each model in the scene
		for (auto m = 0; m < childCount; m++)
		{
			child = child->GetChild(m);

			if (child->GetNodeAttribute() == NULL)
				continue;

			auto attributeType = child->GetNodeAttribute()->GetAttributeType();

			if (attributeType != FbxNodeAttribute::eMesh)
				continue;

			Debug::WriteLine("FBX : Loading child", childName);

			auto childMesh = child->GetMesh();
			auto vertexCount = childMesh->GetPolygonVertexCount();
			auto vertexIndexes = childMesh->GetPolygonVertices();
			auto controlPoints = childMesh->GetControlPoints();
			auto controlPointsCount = childMesh->GetControlPointsCount();

			for (auto cp = 0; cp < controlPointsCount; cp++)
			{
				auto point = controlPoints[cp];
				auto newVertex = new Vertex();

				newVertex->Position = ConvertFbxVector4ToXMFLOAT4(&point, &axisSystem, 1.0);
				newVertex->Color	= XMFLOAT3{ 0.9f, 0.7f, 1.0f };
				newVertex->UV		= XMFLOAT2{ 0.0f, 0.0f };
				newVertex->Normal	= XMFLOAT2{ 0.0f, 0.0f };

				modelVertices->push_back(*newVertex);
			}

			for (auto v = 0; v < vertexCount; v++)
			{
				modelIndexes->push_back(vertexIndexes[v]);
			}
		}
	}

	if (modelVertices->size() <= 0)
	{
		return 0;
	}

	DeviceResource()->IndexCount = modelIndexes->size();
	DeviceResource()->VertexCount = modelVertices->size();

	D3D11_BUFFER_DESC vertexBufferDesc = { 0 };
	vertexBufferDesc.ByteWidth = sizeof(Vertex) * modelVertices->size();
	vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	vertexBufferDesc.CPUAccessFlags = 0;
	vertexBufferDesc.MiscFlags = 0;
	vertexBufferDesc.StructureByteStride = 0;

	D3D11_SUBRESOURCE_DATA vertexBufferData = { 0 };
	vertexBufferData.pSysMem = &modelVertices[0];
	vertexBufferData.SysMemPitch = 0;
	vertexBufferData.SysMemSlicePitch = 0;

	auto result = DeviceResource()->Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &DeviceResource()->VertexBuffer);
	if (FAILED(result))
	{
		return result;
	}

	D3D11_BUFFER_DESC indexBufferDesc = { 0 };
	indexBufferDesc.ByteWidth = sizeof(unsigned int) * DeviceResource()->IndexCount;
	indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
	indexBufferDesc.CPUAccessFlags = 0;
	indexBufferDesc.MiscFlags = 0;
	indexBufferDesc.StructureByteStride = 0;

	D3D11_SUBRESOURCE_DATA indexBufferData = { 0 };
	indexBufferData.pSysMem = &modelIndexes[0];
	indexBufferData.SysMemPitch = 0;
	indexBufferData.SysMemSlicePitch = 0;

	// fbxScene->Destroy();
	// fbxRootNode->Destroy();

	return DeviceResource()->Device->CreateBuffer(&indexBufferDesc, &indexBufferData, &DeviceResource()->IndexBuffer);
}

HRESULT Model::LoadModelFromOBJFile(char* fileName)
{
	// TODO : Get the vertices from the file

	Vertex* vertices[] = { 0 };

	m_initData.pSysMem = vertices;
	m_initData.SysMemPitch = 0;
	m_initData.SysMemSlicePitch = 0;

	m_bufferDesc.Usage = D3D11_USAGE_DEFAULT;
	m_bufferDesc.ByteWidth = sizeof(Vertex) * ARRAYSIZE(vertices);
	m_bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	m_bufferDesc.CPUAccessFlags = 0;
	m_bufferDesc.MiscFlags = 0;

	return 0;
}

XMFLOAT4 Model::ConvertFbxVector4ToXMFLOAT4(FbxVector4* coordinate, FbxAxisSystem* axisSystem, float scale)
{
	bool rightHanded = true;
	auto coordSystem = axisSystem->GetCoorSystem();
	if (coordSystem != FbxAxisSystem::ECoordSystem::eRightHanded)
	{
		rightHanded = false;
	}

	bool yUp = true;
	bool xFront = false;

	int upInverter = 1;
	int upVectorSign;
	auto upVector = axisSystem->GetUpVector(upVectorSign);
	if (upVectorSign != -1)
	{
		upInverter = -1;
	}
	if (upVector != FbxAxisSystem::eYAxis)
	{
		yUp = false;
	}

	int frontInverter = 1;
	int frontVectorSign;
	auto frontVector = axisSystem->GetFrontVector(frontVectorSign);
	if (frontVectorSign != -1)
	{
		frontInverter = -1;
	}

	auto l = 0.0f;
	auto x = 0.0f;
	auto y = 0.0f;
	auto z = 0.0f;

	XMFLOAT4 dxVector;

	if (xFront)
	{
		l = coordinate->mData[3];
		x = coordinate->mData[2] * scale;
		y = coordinate->mData[1] * upInverter * scale;
		z = coordinate->mData[0] * frontInverter * scale;
	}
	else
	{
		x = coordinate->mData[0] * scale;
		y = coordinate->mData[1] * upInverter * scale;
		z = coordinate->mData[2] * frontInverter * scale;
		l = coordinate->mData[3];
	}

	dxVector = XMFLOAT4
	{
		static_cast<float>(x),
		static_cast<float>(y),
		static_cast<float>(z),
		static_cast<float>(l)
	};
	return dxVector;
}

HRESULT Model::InitializeConstantBuffer()
{
	// Belongs to renderer class
	D3D11_BUFFER_DESC constantBufferDesc = { 0 };
	constantBufferDesc.ByteWidth = sizeof(ConstantBufferData);
	constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;

	D3D11_SUBRESOURCE_DATA constantBufferData = { 0 };
	constantBufferData.pSysMem = &DeviceResource()->ConstBuffer;
	constantBufferData.SysMemPitch = 0;
	constantBufferData.SysMemSlicePitch = 0;

	return DeviceResource()->Device->CreateBuffer(&constantBufferDesc, &constantBufferData, &DeviceResource()->ConstBuffer);
}

HRESULT Model::InitializeVertexBuffer()
{
	static const Vertex cube[] =
	{
		{ XMFLOAT4(-0.5f, -0.5f, -0.5f, 0.0f), XMFLOAT3(0.0f, 0.0f, 0.0f) },
		{ XMFLOAT4(-0.5f, -0.5f, 0.5f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f) },
		{ XMFLOAT4(-0.5f, 0.5f, -0.5f, 0.0f), XMFLOAT3(0.0f, 1.0f, 0.0f) },
		{ XMFLOAT4(-0.5f, 0.5f, 0.5f, 0.0f), XMFLOAT3(0.0f, 1.0f, 1.0f) },
		{ XMFLOAT4(0.5f, -0.5f, -0.5f, 0.0f), XMFLOAT3(1.0f, 0.0f, 0.0f) },
		{ XMFLOAT4(0.5f, -0.5f, 0.5f, 0.0f), XMFLOAT3(1.0f, 0.0f, 1.0f) },
		{ XMFLOAT4(0.5f, 0.5f, -0.5f, 0.0f), XMFLOAT3(1.0f, 1.0f, 0.0f) },
		{ XMFLOAT4(0.5f, 0.5f, 0.5f, 0.0f), XMFLOAT3(1.0f, 1.0f, 1.0f) },
	};

	D3D11_BUFFER_DESC vertexBufferDesc = { 0 };
	vertexBufferDesc.ByteWidth = sizeof(Vertex) * ARRAYSIZE(cube);
	vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	vertexBufferDesc.CPUAccessFlags = 0;
	vertexBufferDesc.MiscFlags = 0;
	vertexBufferDesc.StructureByteStride = 0;

	D3D11_SUBRESOURCE_DATA vertexBufferData = { 0 };
	vertexBufferData.pSysMem = cube;
	vertexBufferData.SysMemPitch = 0;
	vertexBufferData.SysMemSlicePitch = 0;

	return DeviceResource()->Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &DeviceResource()->VertexBuffer);
}

HRESULT Model::InitializeIndexBuffer(int indeces[])
{
	// 6 faces * 4 vertices = 24 vertices.
	static const unsigned int cubeIndices[] =
	{
		0, 2, 1, 1, 2, 3, 4, 5, 6, 5, 7, 6,
		0, 1, 5, 0, 5, 4, 2, 6, 7, 2, 7, 3,
		0, 4, 6, 0, 6, 2, 1, 3, 7, 1, 7, 5
	};

	DeviceResource()->IndexCount = ARRAYSIZE(cubeIndices);

	D3D11_BUFFER_DESC indexBufferDesc;
	indexBufferDesc.ByteWidth = sizeof(unsigned int) * ARRAYSIZE(cubeIndices);
	indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
	indexBufferDesc.CPUAccessFlags = 0;
	indexBufferDesc.MiscFlags = 0;
	indexBufferDesc.StructureByteStride = 0;

	D3D11_SUBRESOURCE_DATA indexBufferData;
	indexBufferData.pSysMem = cubeIndices;
	indexBufferData.SysMemPitch = 0;
	indexBufferData.SysMemSlicePitch = 0;

	auto result = DeviceResource()->Device->CreateBuffer(&indexBufferDesc, &indexBufferData, &DeviceResource()->IndexBuffer);
	if (FAILED(result))
	{
		return result;
	}
	return result;
}

HRESULT Model::CreateVertexAndIndexBuffer(XMFLOAT3* vertices)
{
	//long size = 0;
	//int* indexBuffer = new int[size];
	//Vertex* vertexBuffer = new Vertex[size];

	//for (long i = 0; i < size; i++)
	//{
	//	vertexBuffer[i].Position = vertices[i];
	//	indexBuffer[i] = i;
	//}
	return 0;
}

// TODO : Add material<commit_msg>still dont know<commit_after>#include "stdafx.h"
#include "model.h"

Model::Model(DeviceResources* resources)
{
	m_pDeviceResources = shared_ptr<DeviceResources>(resources);
}

Model::~Model()
{

}

HRESULT Model::Initialize()
{
	auto result = LoadModelFromFBXFile("../Models/teapot.fbx");
	if (FAILED(result))
	{
		return result;
	}

	//auto result = InitializeVertexBuffer();
	//if (FAILED(result))
	//{
	//	return result;
	//}

	//result = InitializeIndexBuffer(NULL);
	//if (FAILED(result))
	//{
	//	return result;
	//}

	return InitializeConstantBuffer();
}

HRESULT Model::LoadModelFromFBXFile(char* fileName)
{
	Debug::WriteCurrentDir();
	auto sdkManager = FbxManager::Create();

	auto fbxIOsettings = FbxIOSettings::Create(sdkManager, IOSROOT);
	sdkManager->SetIOSettings(fbxIOsettings);
	fbxIOsettings->SetBoolProp(IMP_FBX_MATERIAL, false);
	fbxIOsettings->SetBoolProp(IMP_FBX_TEXTURE, false);
	fbxIOsettings->SetBoolProp(IMP_FBX_ANIMATION, false);
	fbxIOsettings->SetBoolProp(IMP_FBX_TEXTURE, false);

	auto fbxImporter = FbxImporter::Create(sdkManager, "");
	auto fbxScene = FbxScene::Create(sdkManager, "");

	auto success = fbxImporter->Initialize(fileName, -1, sdkManager->GetIOSettings());
	if (!success)
	{
		return success;
	}

	success = fbxImporter->Import(fbxScene);
	fbxImporter->Destroy();

	if (!success)
	{
		return success;
	}

	auto axisSystem = fbxScene->GetGlobalSettings().GetAxisSystem();

	auto fbxRootNode = fbxScene->GetRootNode();
	auto count = fbxRootNode->GetChildCount();

	auto modelVertices = new vector<Vertex>();
	auto modelIndexes = new vector<unsigned int>();

	// The scene maybe
	for (auto s = 0; s < count; s++)
	{
		auto child = fbxRootNode->GetChild(s);
		auto childName = child->GetName();
		auto childCount = child->GetChildCount();

		// For each model in the scene
		for (auto m = 0; m < childCount; m++)
		{
			child = child->GetChild(m);

			if (child->GetNodeAttribute() == NULL)
				continue;

			auto attributeType = child->GetNodeAttribute()->GetAttributeType();

			if (attributeType != FbxNodeAttribute::eMesh)
				continue;

			Debug::WriteLine("FBX : Loading child", childName);

			auto childMesh = child->GetMesh();
			auto vertexCount = childMesh->GetPolygonVertexCount();
			auto vertexIndexes = childMesh->GetPolygonVertices();
			auto controlPoints = childMesh->GetControlPoints();
			auto controlPointsCount = childMesh->GetControlPointsCount();

			for (auto cp = 0; cp < controlPointsCount; cp++)
			{
				auto point = controlPoints[cp];
				auto newVertex = new Vertex();

				newVertex->Position = ConvertFbxVector4ToXMFLOAT4(&point, &axisSystem, 1.0);
				newVertex->Color	= XMFLOAT3{ 0.9f, 0.7f, 1.0f };
				newVertex->UV		= XMFLOAT2{ 0.0f, 0.0f };
				newVertex->Normal	= XMFLOAT2{ 0.0f, 0.0f };

				modelVertices->push_back(*newVertex);
			}

			for (auto v = 0; v < vertexCount; v++)
			{
				modelIndexes->push_back(vertexIndexes[v]);
			}
		}
	}

	if (modelVertices->size() <= 0)
	{
		return 0;
	}

	DeviceResource()->IndexCount = modelIndexes->size();
	DeviceResource()->VertexCount = modelVertices->size();

	D3D11_BUFFER_DESC vertexBufferDesc = { 0 };
	vertexBufferDesc.ByteWidth = sizeof(Vertex) * modelVertices->size();
	vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	vertexBufferDesc.CPUAccessFlags = 0;
	vertexBufferDesc.MiscFlags = 0;
	vertexBufferDesc.StructureByteStride = 0;

	D3D11_SUBRESOURCE_DATA vertexBufferData = { 0 };
	vertexBufferData.pSysMem = &modelVertices[0];
	vertexBufferData.SysMemPitch = 0;
	vertexBufferData.SysMemSlicePitch = 0;

	auto result = DeviceResource()->Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &DeviceResource()->VertexBuffer);
	if (FAILED(result))
	{
		return result;
	}

	D3D11_BUFFER_DESC indexBufferDesc = { 0 };
	indexBufferDesc.ByteWidth = sizeof(unsigned int) * DeviceResource()->IndexCount;
	indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
	indexBufferDesc.CPUAccessFlags = 0;
	indexBufferDesc.MiscFlags = 0;
	indexBufferDesc.StructureByteStride = 0;

	D3D11_SUBRESOURCE_DATA indexBufferData = { 0 };
	indexBufferData.pSysMem = &modelIndexes[0];
	indexBufferData.SysMemPitch = 0;
	indexBufferData.SysMemSlicePitch = 0;

	// fbxScene->Destroy();
	// fbxRootNode->Destroy();

	return DeviceResource()->Device->CreateBuffer(&indexBufferDesc, &indexBufferData, &DeviceResource()->IndexBuffer);
}

HRESULT Model::LoadModelFromOBJFile(char* fileName)
{
	// TODO : Get the vertices from the file

	Vertex* vertices[] = { 0 };

	m_initData.pSysMem = vertices;
	m_initData.SysMemPitch = 0;
	m_initData.SysMemSlicePitch = 0;

	m_bufferDesc.Usage = D3D11_USAGE_DEFAULT;
	m_bufferDesc.ByteWidth = sizeof(Vertex) * ARRAYSIZE(vertices);
	m_bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	m_bufferDesc.CPUAccessFlags = 0;
	m_bufferDesc.MiscFlags = 0;

	return 0;
}

XMFLOAT4 Model::ConvertFbxVector4ToXMFLOAT4(FbxVector4* coordinate, FbxAxisSystem* axisSystem, float scale)
{
	bool rightHanded = true;
	auto coordSystem = axisSystem->GetCoorSystem();
	if (coordSystem != FbxAxisSystem::ECoordSystem::eRightHanded)
	{
		rightHanded = false;
	}

	bool yUp = true;
	bool xFront = false;

	int upInverter = 1;
	int upVectorSign;
	auto upVector = axisSystem->GetUpVector(upVectorSign);
	if (upVectorSign != -1)
	{
		upInverter = -1;
	}
	if (upVector != FbxAxisSystem::eYAxis)
	{
		yUp = false;
	}

	int frontInverter = 1;
	int frontVectorSign;
	auto frontVector = axisSystem->GetFrontVector(frontVectorSign);
	if (frontVectorSign != -1)
	{
		frontInverter = -1;
	}

	auto l = 0.0f;
	auto x = 0.0f;
	auto y = 0.0f;
	auto z = 0.0f;

	XMFLOAT4 dxVector;

	if (xFront)
	{
		x = coordinate->mData[2] * scale;
		y = coordinate->mData[1] * upInverter * scale;
		z = coordinate->mData[0] * frontInverter * scale;
	}
	else
	{
		// Flip y and z to convert from RH to LH
		x = coordinate->mData[0] * scale;
		y = coordinate->mData[2] * scale;
		z = coordinate->mData[1] * scale;
	}

	dxVector = XMFLOAT4
	{
		static_cast<float>(x),
		static_cast<float>(y),
		static_cast<float>(z),
		static_cast<float>(l)
	};
	return dxVector;
}

HRESULT Model::InitializeConstantBuffer()
{
	// Belongs to renderer class
	D3D11_BUFFER_DESC constantBufferDesc = { 0 };
	constantBufferDesc.ByteWidth = sizeof(ConstantBufferData);
	constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;

	D3D11_SUBRESOURCE_DATA constantBufferData = { 0 };
	constantBufferData.pSysMem = &DeviceResource()->ConstBuffer;
	constantBufferData.SysMemPitch = 0;
	constantBufferData.SysMemSlicePitch = 0;

	return DeviceResource()->Device->CreateBuffer(&constantBufferDesc, &constantBufferData, &DeviceResource()->ConstBuffer);
}

HRESULT Model::InitializeVertexBuffer()
{
	static const Vertex cube[] =
	{
		{ XMFLOAT4(-0.5f, -0.5f, -0.5f, 0.0f), XMFLOAT3(0.0f, 0.0f, 0.0f) },
		{ XMFLOAT4(-0.5f, -0.5f, 0.5f, 0.0f), XMFLOAT3(0.0f, 0.0f, 1.0f) },
		{ XMFLOAT4(-0.5f, 0.5f, -0.5f, 0.0f), XMFLOAT3(0.0f, 1.0f, 0.0f) },
		{ XMFLOAT4(-0.5f, 0.5f, 0.5f, 0.0f), XMFLOAT3(0.0f, 1.0f, 1.0f) },
		{ XMFLOAT4(0.5f, -0.5f, -0.5f, 0.0f), XMFLOAT3(1.0f, 0.0f, 0.0f) },
		{ XMFLOAT4(0.5f, -0.5f, 0.5f, 0.0f), XMFLOAT3(1.0f, 0.0f, 1.0f) },
		{ XMFLOAT4(0.5f, 0.5f, -0.5f, 0.0f), XMFLOAT3(1.0f, 1.0f, 0.0f) },
		{ XMFLOAT4(0.5f, 0.5f, 0.5f, 0.0f), XMFLOAT3(1.0f, 1.0f, 1.0f) },
	};

	D3D11_BUFFER_DESC vertexBufferDesc = { 0 };
	vertexBufferDesc.ByteWidth = sizeof(Vertex) * ARRAYSIZE(cube);
	vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	vertexBufferDesc.CPUAccessFlags = 0;
	vertexBufferDesc.MiscFlags = 0;
	vertexBufferDesc.StructureByteStride = 0;

	D3D11_SUBRESOURCE_DATA vertexBufferData = { 0 };
	vertexBufferData.pSysMem = cube;
	vertexBufferData.SysMemPitch = 0;
	vertexBufferData.SysMemSlicePitch = 0;

	return DeviceResource()->Device->CreateBuffer(&vertexBufferDesc, &vertexBufferData, &DeviceResource()->VertexBuffer);
}

HRESULT Model::InitializeIndexBuffer(int indeces[])
{
	// 6 faces * 4 vertices = 24 vertices.
	static const unsigned int cubeIndices[] =
	{
		0, 2, 1, 1, 2, 3, 4, 5, 6, 5, 7, 6,
		0, 1, 5, 0, 5, 4, 2, 6, 7, 2, 7, 3,
		0, 4, 6, 0, 6, 2, 1, 3, 7, 1, 7, 5
	};

	DeviceResource()->IndexCount = ARRAYSIZE(cubeIndices);

	D3D11_BUFFER_DESC indexBufferDesc;
	indexBufferDesc.ByteWidth = sizeof(unsigned int) * ARRAYSIZE(cubeIndices);
	indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
	indexBufferDesc.CPUAccessFlags = 0;
	indexBufferDesc.MiscFlags = 0;
	indexBufferDesc.StructureByteStride = 0;

	D3D11_SUBRESOURCE_DATA indexBufferData;
	indexBufferData.pSysMem = cubeIndices;
	indexBufferData.SysMemPitch = 0;
	indexBufferData.SysMemSlicePitch = 0;

	auto result = DeviceResource()->Device->CreateBuffer(&indexBufferDesc, &indexBufferData, &DeviceResource()->IndexBuffer);
	if (FAILED(result))
	{
		return result;
	}
	return result;
}

HRESULT Model::CreateVertexAndIndexBuffer(XMFLOAT3* vertices)
{
	//long size = 0;
	//int* indexBuffer = new int[size];
	//Vertex* vertexBuffer = new Vertex[size];

	//for (long i = 0; i < size; i++)
	//{
	//	vertexBuffer[i].Position = vertices[i];
	//	indexBuffer[i] = i;
	//}
	return 0;
}

// TODO : Add material<|endoftext|>


<commit_before>/*
Stereo Vision Algorithm Framework, Copyright(c) 2016-2018, Peng Chao
ѡȡROIĵ
*/

#include "CenterPointLayer.h"

namespace svaf{

CenterPointLayer::CenterPointLayer(LayerParameter& layer) : Layer(layer)
{
}

CenterPointLayer::~CenterPointLayer()
{
}

bool CenterPointLayer::Run(vector<Block>& images, vector<Block>& disp, LayerParameter& layer, void* param){
	CHECK_GE(images.size(), 2) << "";
	pWorld = (World*)param;
	int type = 2;
	switch (type){
	case 2:
		ROICenter(images);
		break;
	default:
		break;
	}
	return true;
}

void CenterPointLayer::ROICenter(vector<Block>& images){
	auto roi0 = images[0].roi;
	auto roi1 = images[1].roi;
	images[0].pMatch = &images[1];

	__t.StartWatchTimer();
	images[0].points.clear();
	images[1].points.clear();
	images[0].points.push_back(Point2f(roi0.width / 2.0, roi0.height / 2.0));
	images[1].points.push_back(Point2f(roi1.width / 2.0, roi1.height / 2.0));
	images[0].ptidx.push_back(0);
	__t.ReadWatchTimer(__name + " Time");
	if (__logt){
		(*figures)[__name + "_t"][*id] = (float)__t;
	}

	LOG(INFO) << "ROI Center Has Been Setted.";
	RLOG("ROI CenterHas Been Selected.");
}

}
<commit_msg>add note for CenterPointLayer.cpp<commit_after>/*
Stereo Vision Algorithm Framework, Copyright(c) 2016-2018, Peng Chao
ѡȡROIĵ
*/

#include "CenterPointLayer.h"

namespace svaf{

// 캯
CenterPointLayer::CenterPointLayer(LayerParameter& layer) : Layer(layer)
{
}

//
CenterPointLayer::~CenterPointLayer()
{
}

//
bool CenterPointLayer::Run(vector<Block>& images, vector<Block>& disp, LayerParameter& layer, void* param){
	CHECK_GE(images.size(), 2) << "";
	pWorld = (World*)param;
	int type = 2;
	switch (type){
	case 2:
		ROICenter(images);
		break;
	default:
		break;
	}
	return true;
}

// ROIROIλãά㼯
void CenterPointLayer::ROICenter(vector<Block>& images){
	auto roi0 = images[0].roi;
	auto roi1 = images[1].roi;
	images[0].pMatch = &images[1];

	__t.StartWatchTimer();
	images[0].points.clear();
	images[1].points.clear();
	images[0].points.push_back(Point2f(roi0.width / 2.0, roi0.height / 2.0));
	images[1].points.push_back(Point2f(roi1.width / 2.0, roi1.height / 2.0));
	images[0].ptidx.push_back(0);
	__t.ReadWatchTimer(__name + " Time");
	if (__logt){
		(*figures)[__name + "_t"][*id] = (float)__t;
	}

	LOG(INFO) << "ROI Center Has Been Setted.";
	RLOG("ROI CenterHas Been Selected.");
}

}
<|endoftext|>