module demos.space_invaders;

import app;

import bindbc.sdl;

import bubel.ecs.attributes;
import bubel.ecs.core;
import bubel.ecs.entity;
import bubel.ecs.manager;
import bubel.ecs.std;

import cimgui.cimgui;

import ecs_utils.gfx.texture;
import ecs_utils.math.vector;
import ecs_utils.utils;

import game_core.basic;

//import std.math : PI;


//import std.array : staticArray;

private enum float px = 1.0/512.0;


extern(C):

enum ShootGridDependency = "ShootGridDependency";

/*#######################################################################################################################
------------------------------------------------ Types ------------------------------------------------------------------
#######################################################################################################################*/

struct SpaceInvaders
{
    __gshared const (char)* tips = "Use \"WASD\" keys to move and \"Space\" for shooting.";

    EntityTemplate* enemy_tmpl;
    EntityTemplate* ship_tmpl;
    EntityTemplate* laser_tmpl;
    EntityTemplate*[5] bullet_tmpl;
    Texture texture;

    ShootGrid* shoot_grid;

    bool move_system = true;
    bool draw_system = true;
    
    const vec2 map_size = vec2(400,300);
    const float cell_size = 60;

    EntityID player_ship;

    ~this() @nogc nothrow
    {
        if(shoot_grid)Mallocator.dispose(shoot_grid);
        if(enemy_tmpl)launcher.manager.freeTemplate(enemy_tmpl);
        if(ship_tmpl)launcher.manager.freeTemplate(ship_tmpl);
        if(laser_tmpl)launcher.manager.freeTemplate(laser_tmpl);
        foreach (EntityTemplate* tmpl; bullet_tmpl)
        {
            if(tmpl)launcher.manager.freeTemplate(tmpl);
        }
        texture.destory();
    }
}

struct SceneGrid
{
    struct Element
    {
        EntityID entity;
        int guild;
        vec2 min;
        vec2 max;
    }

    struct Cell
    {
        Element[20] elements;
    }

    void create()
    {
        cells_count.x = cast(int)((space_invaders.map_size.x - 0.01f) / space_invaders.cell_size) + 1;
        cells_count.y = cast(int)((space_invaders.map_size.y - 0.01f) / space_invaders.cell_size) + 1;
        cells = Mallocator.makeArray!Cell(cells_count.x * cells_count.y);
    }

    void destory()
    {
        if(cells)
        {
            Mallocator.dispose(cells);
            cells = null;
        }
    }

    ivec2 cells_count;
    Cell[] cells;
}

enum Direction : byte 
{
    up,
    down,
    left,
    right
}

/*#######################################################################################################################
------------------------------------------------ Components ------------------------------------------------------------------
#######################################################################################################################*/

/*struct CLocation
{
    mixin ECS.Component;

    alias value this;

    vec2 value = vec2(0);
}*/

struct CScale
{
    mixin ECS.Component;

    ///use component as it value
    alias value this;

    vec2 value = vec2(16,16);
}

struct CColliderScale
{
    mixin ECS.Component;

    alias value this;

    vec2 value = vec2(16,16);
}

struct CRotation
{
    mixin ECS.Component;

    ///use component as it value
    alias value this;

    float value = 0;
}

struct CTexture
{
    mixin ECS.Component;

    //Texture tex;
    uint id;
    vec4 coords = vec4(0,0,0,1);
}

struct CVelocity
{
    mixin ECS.Component;

    alias value this;

    vec2 value = vec2(0,0);
}

struct CInput
{
    mixin ECS.Component;
}

struct CEnemy
{
    mixin ECS.Component;    
}

struct CShip
{
    mixin ECS.Component;
}

struct CAutoShoot
{
    mixin ECS.Component;
}

struct CGuild
{
    mixin ECS.Component;

    byte guild;
}

struct CBullet
{
    mixin ECS.Component;

    int damage = 1;
}

struct CWeapon
{
    mixin ECS.Component;

    static struct Level
    {
        float reload_time;
        float dispersion;
        int damage;
    }

    __gshared Level[12] levels = [Level(4000,0),Level(4000,0.1),
    Level(500,0),Level(350,0),Level(250,0.02),Level(175,0.03),Level(110,0.04),
    Level(80,0.05),Level(50,0.08),Level(20,0.1),Level(10,0.12),Level(2,0.14)];

    enum Type : ubyte
    {
        laser,
        enemy_laser,
        blaster,
        canon,
        plasma
    }

    float shoot_time = 0;
    Type type;
    ubyte level = 1;
}

struct CWeaponLocation
{
    mixin ECS.Component;

    vec2 rel_pos = vec2(0,0);
}

struct CShootDirection
{
    mixin ECS.Component;
    
    Direction direction;
}

struct CSideMove
{
    mixin ECS.Component;

    byte group = -1;
}

struct CDepth
{
    mixin ECS.Component;

    alias depth this;

    short depth;
}

struct CShootGrid
{
    mixin ECS.Component;
}

struct CTargetParent
{
    mixin ECS.Component;

    EntityID parent;
    vec2 rel_pos = vec2(0,0);
}


struct CHitPoints
{
    mixin ECS.Component;

    alias value this;

    int value = 3;
}

struct CMaxHitPoints
{
    mixin ECS.Component;

    alias value this;

    int value = 3;
}

struct CHitMark
{
    mixin ECS.Component;

    alias value this;

    ubyte value = 0;
}

struct CUpgrade
{
    mixin ECS.Component;

    alias value this;

    enum Upgrade : ubyte
    {
        hit_points,
        regeneration,
        laser
    }

    Upgrade value;
}

struct CAnimation
{
    mixin ECS.Component;
    
    vec4[] frames;
    float time = 0;
    float speed = 1;
}

struct CAnimationLooped
{
    mixin ECS.Component;
}

struct CDamping
{
    mixin ECS.Component;

    alias value this;

    byte value = 0;
}

struct CParticle
{
    mixin ECS.Component;

    float life = 0;
}

struct CTarget 
{
    mixin ECS.Component;

    EntityID target;
}

struct CTargetPlayerShip
{
    mixin ECS.Component;
}

struct CChildren
{
    mixin ECS.Component;

    EntityID[] childern;
}

struct CBoss
{
    mixin ECS.Component;
}

struct CParts
{
    mixin ECS.Component;

    ubyte count;
}

struct CInit
{
    mixin ECS.Component;

    enum Type
    {
        space_ship,
        tower,
        boss
    }

    Type type;
}

struct CParticleEmitter
{
    mixin ECS.Component;

    vec2 range;
    vec2 time_range;
    ///due to multithreading there should be separate template for every thread.
    ///It can be array of tempaltes or (like in this demo) simply index of template;
    uint tmpl_id;
    //EntityTemplate* tmpl;
}

///Due to perfarmance reason emitter time and attributes are divided into seprate components.
///Beyon that both components are considerd to be used together.
struct CParticleEmitterTime
{
    mixin ECS.Component;

    float time = 0;
}

///You can create separate component for every kind of spawned entities but it's not practial due to archetype fragmentation.
///Second approach can be commented code. It's gives good flexibility inchoosing entity, but it limits to one entity.
///Instead of entity it can be array of templates which is good solution, but if possibilities is known at time of game development it
///can be simply index/enum for type of spawn. Bad thing about this solution is problem witch merging multiple spawning types during
///gameplay, i.e. giving buff which cast firebols upon death.
struct CSpawnUponDeath
{
    mixin ECS.Component;

    enum Type
    {
        flashes_emitter,
    }

    //EntityID parent;
    //EntityTemplate* tmpl;
    Type type;
}

///This component can be replaced by "CSpawnUponDeath" but I want to gives possibility to add this component to every entity
///during gameplay. End application works exacly the same way for every demo so I can't use different way as adding component.
struct CShootWaveUponDeath
{
    mixin ECS.Component;

    CWeapon.Type bullet_type;
}

/*#######################################################################################################################
------------------------------------------------ Events ------------------------------------------------------------------
#######################################################################################################################*/

struct EChangeDirection
{
    mixin ECS.Event;

    this(Direction direction)
    {
        this.direction = direction;
    }

    Direction direction;
}

struct EUpgrade
{
    mixin ECS.Event;
}

struct EDeath
{
    mixin ECS.Event;
}

struct EDamage
{
    mixin ECS.Event;

    this(uint damage)
    {
        this.damage = damage;
    }

    uint damage = 0;
}

struct EBulletHit
{
    mixin ECS.Event;

    this(EntityID id, uint damage)
    {
        this.id = id;
        this.damage = damage;
    }

    EntityID id;
    uint damage;
}

struct EDestroyedChild
{
    mixin ECS.Event;

    this(EntityID id)
    {
        this.id = id;
    }

    EntityID id;
}

/*#######################################################################################################################
------------------------------------------------ Systems ------------------------------------------------------------------
#######################################################################################################################*/

struct ShootGrid
{

    ~this() @nogc nothrow
    {
        if(nodes)Mallocator.dispose(nodes);
        if(masks)Mallocator.dispose(masks);
    }

    struct Node
    {
        alias entity this;

        EntityID entity;
    }

    void create(ivec2 nodes_count, vec2 node_size)
    {
        this.size = nodes_count;
        this.node_size = node_size;
        inv_node_size = vec2(1.0/node_size.x, 1.0/node_size.y);
        nodes = Mallocator.makeArray!Node(nodes_count.x * nodes_count.y);
        masks = Mallocator.makeArray!ubyte(nodes.length);
    }

    void mark(EntityID id, vec2 beg, vec2 end, byte mask)
    {
        ivec2 ibeg = cast(ivec2)(beg * inv_node_size);
        ivec2 iend = cast(ivec2)((end * inv_node_size) + 0.5);
        if(ibeg.x < 0)ibeg.x = 0;
        if(ibeg.y < 0)ibeg.y = 0;
        if(iend.x > size.x)iend.x = size.x;
        if(iend.y > size.y)iend.y = size.y;
        foreach(i; ibeg.y .. iend.y)
        {
            foreach(j; ibeg.x .. iend.x)
            {
                nodes[i * size.x + j] = id;
                masks[i * size.x +j] = mask;
            }
        }
    }

    void clear()
    {
        size_t size = nodes.length * EntityID.sizeof;
        memset(nodes.ptr, 0, size);
        memset(masks.ptr, 0, masks.length);
    }

    bool test(out EntityID id, vec2 beg, vec2 end)
    {
        ivec2 ibeg = cast(ivec2)(beg * inv_node_size);
        ivec2 iend = cast(ivec2)((end * inv_node_size) + 0.5);
        if(ibeg.x < 0)ibeg.x = 0;
        if(ibeg.y < 0)ibeg.y = 0;
        if(iend.x > size.x)iend.x = size.x;
        if(iend.y > size.y)iend.y = size.y;
        foreach(i; ibeg.y .. iend.y)
        {
            foreach(j; ibeg.x .. iend.x)
            {
                if(nodes[i * size.x + j].id != 0)
                {
                    id = nodes[i * size.x + j];
                    return true;
                }
            }
        }
        return false;
    }

    bool test(out EntityID id, vec2 pos, ubyte mask)
    {
        ivec2 ipos = cast(ivec2)(pos * inv_node_size - 0.5);
        if(ipos.x < 0)ipos.x = 0;
        if(ipos.y < 0)ipos.y = 0;
        if(ipos.x >= size.x)ipos.x = size.x - 1;
        if(ipos.y >= size.y)ipos.y = size.y - 1;
        size_t index = ipos.y * size.x + ipos.x;
        if((masks[index] & mask) == 0)return false;
        if(nodes[index].id != 0)
        {
            id = nodes[index];
            return true;
        }
        return false;
    }

    vec2 inv_node_size;
    ivec2 size;
    vec2 node_size;
    Node[] nodes;
    ubyte[] masks;
}

struct ShootGridCleaner
{
    mixin ECS.System!1;

    struct EntitiesData
    {

    }

    void onUpdate(EntitiesData data)
    {
        if(space_invaders.shoot_grid)space_invaders.shoot_grid.clear();
    }
}

struct ShootGridManager
{
    mixin ECS.System!128;

    mixin ECS.WritableDependencies!(ShootGridDependency);

    struct EntitiesData
    {
        uint length;
        //uint thread_id;
        const (Entity)[] entity;
        @readonly CLocation[] locations;
        @readonly CShootGrid[] grid_flag;
        @readonly CGuild[] guild;
        @optional @readonly CScale[] scale;
        @optional @readonly CColliderScale[] collider_scale;
    }

    ShootGrid* grid;

    void onCreate()
    {
        grid = space_invaders.shoot_grid;
    }

    bool onBegin()
    {
        if(!grid)return false;
        //grid.clear();
        return true;
    }

    void onUpdate(EntitiesData data)
    {
        vec2[] scale;
        if(data.collider_scale)scale = cast(vec2[])data.collider_scale;
        else if(data.scale)scale = cast(vec2[])data.scale;
        else return;
        foreach(i; 0..data.length)
        {
            vec2 half_scale = scale[i] * 0.5;
            grid.mark(data.entity[i].id, data.locations[i] - half_scale, data.locations[i] + half_scale, cast(ubyte)(1 << data.guild[i].guild));
        }
    }
}

struct ParentOwnerSystem
{
    mixin ECS.System;

    struct EntitiesData
    {
        CChildren[] children;
    }

    void onRemoveEntity(EntitiesData data)
    {
        //currently EntitiesData always has only one element
        foreach(child; data.children[0].childern)
        {
            launcher.manager.removeEntity(child);
        }
        if(data.children[0].childern.length)Mallocator.dispose(data.children[0].childern);
    }
}

struct ShipWeaponSystem
{
    mixin ECS.System;

    struct EntitiesData
    {
        int length;
        Entity[] entity;
        CInit[] init;
        //CShip[] ship;
        CChildren[] children;
    }

    struct Ship
    {
        EntityTemplate* laser1_tmpl;
        EntityTemplate* laser2_tmpl;
        EntityTemplate* main_weapon_tmpl;

        void add(Entity* entity)
        {
            CChildren* children = entity.getComponent!CChildren;
            if(children is null || children.childern.length != 0)return;
            EntityID[3] weapons;
            laser1_tmpl.getComponent!CTargetParent().parent = entity.id;
            laser2_tmpl.getComponent!CTargetParent().parent = entity.id;
            main_weapon_tmpl.getComponent!CTargetParent().parent = entity.id;
            weapons[0] = launcher.manager.addEntity(laser1_tmpl).id;
            weapons[1] = launcher.manager.addEntity(laser2_tmpl).id;
            weapons[2] = launcher.manager.addEntity(main_weapon_tmpl).id;
            children.childern = Mallocator.makeArray(weapons);
        }

        void create()
        {
            laser1_tmpl = launcher.manager.allocateTemplate([CWeapon.component_id, CLocation.component_id, CShootDirection.component_id, CTargetParent.component_id, CGuild.component_id, CVelocity.component_id].staticArray);
            main_weapon_tmpl = launcher.manager.allocateTemplate([CLocation.component_id, CShootDirection.component_id, CTargetParent.component_id, CGuild.component_id, CVelocity.component_id].staticArray);
            *laser1_tmpl.getComponent!CWeapon = CWeapon(0,CWeapon.Type.laser,3);
            laser1_tmpl.getComponent!CTargetParent().rel_pos = vec2(10,13);
            main_weapon_tmpl.getComponent!CTargetParent().rel_pos = vec2(0,4);
            laser2_tmpl = launcher.manager.allocateTemplate(laser1_tmpl);
            laser2_tmpl.getComponent!CTargetParent().rel_pos = vec2(-10,13);
        }

        ~this()
        {
            launcher.manager.freeTemplate(laser1_tmpl);
            launcher.manager.freeTemplate(laser2_tmpl);
            launcher.manager.freeTemplate(main_weapon_tmpl);
        }
    }

    struct Tower
    {
        EntityTemplate* weapon_tmpl;
        EntityTemplate* top_tmpl;

        void add(Entity* entity)
        {
            CChildren* children = entity.getComponent!CChildren;
            if(children is null || children.childern.length != 0)return;
            CDepth* depth = entity.getComponent!CDepth;
            EntityID[2] weapons;
            weapon_tmpl.getComponent!CTargetParent().parent = entity.id;
            if(depth)weapon_tmpl.getComponent!CDepth().depth = cast(short)(depth.depth - 1);
            else weapon_tmpl.getComponent!CDepth().depth = -1;
            top_tmpl.getComponent!CTargetParent().parent = entity.id;
            if(depth)top_tmpl.getComponent!CDepth().depth = cast(short)(depth.depth - 2);
            else top_tmpl.getComponent!CDepth().depth = -2;

            weapons[0] = launcher.manager.addEntity(weapon_tmpl).id;
            weapons[1] = launcher.manager.addEntity(top_tmpl).id;
            children.childern = Mallocator.makeArray(weapons);
        }

        void create()
        {
            weapon_tmpl = launcher.manager.allocateTemplate(
                [CWeapon.component_id, CLocation.component_id, CShootDirection.component_id,
                CTargetParent.component_id, CGuild.component_id, CVelocity.component_id,
                CAutoShoot.component_id, CTarget.component_id, CTargetPlayerShip.component_id,
                CRotation.component_id, CScale.component_id, CTexture.component_id,
                CDepth.component_id, CWeaponLocation.component_id].staticArray);
            *weapon_tmpl.getComponent!CWeapon = CWeapon(0,CWeapon.Type.laser,3);
            weapon_tmpl.getComponent!CTargetParent().rel_pos = vec2(0,0);
            weapon_tmpl.getComponent!CGuild().guild = 1;
            weapon_tmpl.getComponent!CScale().value = vec2(4,16);
            //weapon_tmpl.getComponent!CWeapon().level = 1;
            *weapon_tmpl.getComponent!CWeapon() = CWeapon(0,CWeapon.Type.canon,1);
            weapon_tmpl.getComponent!CDepth().depth = -1;
            weapon_tmpl.getComponent!CTexture().coords = vec4(136,96,4,16)*px;
            weapon_tmpl.getComponent!CWeaponLocation().rel_pos = vec2(0,12);

            top_tmpl = launcher.manager.allocateTemplate(
                [CLocation.component_id, CTargetParent.component_id, CScale.component_id, 
                CTexture.component_id, CDepth.component_id].staticArray);
            top_tmpl.getComponent!CTargetParent().rel_pos = vec2(0,1);
            top_tmpl.getComponent!CScale().value = vec2(10,11);
            top_tmpl.getComponent!CDepth().depth = -2;
            top_tmpl.getComponent!CTexture().coords = vec4(112,96,10,11)*px;
            
        }

        ~this()
        {
            launcher.manager.freeTemplate(weapon_tmpl);
            launcher.manager.freeTemplate(top_tmpl);
        }
    }

    struct Boss
    {
        EntityTemplate* tower1_tmpl;
        EntityTemplate* tower2_tmpl;
        EntityTemplate* tower3_tmpl;
        EntityTemplate* tower4_tmpl;

        void add(Entity* entity)
        {
            CChildren* children = entity.getComponent!CChildren;
            if(children is null || children.childern.length != 0)return;
            CParts* parts = entity.getComponent!CParts;
            if(parts)parts.count = 4;
            EntityID[4] towers;
            tower1_tmpl.getComponent!CTargetParent().parent = entity.id;
            tower2_tmpl.getComponent!CTargetParent().parent = entity.id;
            tower3_tmpl.getComponent!CTargetParent().parent = entity.id;
            tower4_tmpl.getComponent!CTargetParent().parent = entity.id;
            towers[0] = launcher.manager.addEntity(tower1_tmpl).id;
            towers[1] = launcher.manager.addEntity(tower2_tmpl).id;
            towers[2] = launcher.manager.addEntity(tower3_tmpl).id;
            towers[3] = launcher.manager.addEntity(tower4_tmpl).id;
            children.childern = Mallocator.makeArray(towers);
        }

        void create()
        {
            tower1_tmpl = launcher.manager.allocateTemplate(
                [CHitMark.component_id, CHitPoints.component_id, CLocation.component_id, 
                CTexture.component_id, CScale.component_id, CEnemy.component_id, 
                CShootGrid.component_id, CGuild.component_id, CInit.component_id,
                CChildren.component_id, CDepth.component_id, CTargetParent.component_id,
                CSpawnUponDeath.component_id, CShootWaveUponDeath.component_id].staticArray
            );

            CTexture* tex_comp = tower1_tmpl.getComponent!CTexture;
            //tex_comp.tex = space_invaders.texture;//ship_tex;
            tex_comp.coords = vec4(96*px,96*px,16*px,16*px);
            CLocation* loc_comp = tower1_tmpl.getComponent!CLocation;
            loc_comp.value = vec2(64,space_invaders.map_size.y - 16);
            tower1_tmpl.getComponent!CGuild().guild = 1;
            tower1_tmpl.getComponent!CInit().type = CInit.Type.tower;  
            tower1_tmpl.getComponent!CHitPoints().value = 10;
            tower1_tmpl.getComponent!CDepth().depth = -2;
            tower1_tmpl.getComponent!CShootWaveUponDeath().bullet_type = CWeapon.Type.canon;
            tower1_tmpl.getComponent!CTargetParent().rel_pos = vec2(-33,2);

            tower2_tmpl = launcher.manager.allocateTemplate(tower1_tmpl);
            tower2_tmpl.getComponent!CTargetParent().rel_pos = vec2(33,2);

            tower3_tmpl = launcher.manager.allocateTemplate(tower1_tmpl);
            tower3_tmpl.getComponent!CDepth().depth = 0;
            tower3_tmpl.getComponent!CTargetParent().rel_pos = vec2(-40,-15);

            tower4_tmpl = launcher.manager.allocateTemplate(tower1_tmpl);
            tower4_tmpl.getComponent!CDepth().depth = 0;
            tower4_tmpl.getComponent!CTargetParent().rel_pos = vec2(40,-15);
        }

        ~this()
        {
            launcher.manager.freeTemplate(tower1_tmpl);
            launcher.manager.freeTemplate(tower2_tmpl);
            launcher.manager.freeTemplate(tower3_tmpl);
            launcher.manager.freeTemplate(tower4_tmpl);
        }
    }

    Ship ship;
    Tower tower;
    Boss boss;

    void onCreate()
    {
        ship.create();
        tower.create();
        boss.create();
        /*ship.laser1_tmpl = launcher.manager.allocateTemplate([CWeapon.component_id, CLocation.component_id, CShootDirection.component_id, CTargetParent.component_id, CGuild.component_id, CVelocity.component_id].staticArray);
        ship.main_weapon_tmpl = launcher.manager.allocateTemplate([CLocation.component_id, CShootDirection.component_id, CTargetParent.component_id, CGuild.component_id, CVelocity.component_id].staticArray);
        *ship.laser1_tmpl.getComponent!CWeapon = CWeapon(3,0.0);
        ship.laser1_tmpl.getComponent!CTargetParent().rel_pos = vec2(10,13);
        ship.main_weapon_tmpl.getComponent!CTargetParent().rel_pos = vec2(0,4);
        ship.laser2_tmpl = launcher.manager.allocateTemplate(ship.laser1_tmpl);
        ship.laser2_tmpl.getComponent!CTargetParent().rel_pos = vec2(-10,13);*/
    }

    void onDestroy()
    {
        /*launcher.manager.freeTemplate(laser1_tmpl);
        launcher.manager.freeTemplate(laser2_tmpl);
        launcher.manager.freeTemplate(main_weapon_tmpl);*/
    }

    void onAddEntity(EntitiesData data)
    {
        foreach(i; 0..data.length)
        {
            final switch(data.init[i].type)
            {
                case CInit.Type.space_ship:ship.add(&data.entity[i]);break;
                case CInit.Type.tower:tower.add(&data.entity[i]);break;
                case CInit.Type.boss:boss.add(&data.entity[i]);break;
            }
        }
    }
}

struct MoveToParentTargetSystem
{
    mixin ECS.System!32;

    struct EntitiesData
    {
        int length;
        CLocation[] location;
        @optional CVelocity[] velocity;
        @readonly CTargetParent[] target;
    }

    void onUpdate(EntitiesData data)
    {
        if(data.velocity)
        {
            foreach(i;0..data.length)
            {
                Entity* target = launcher.manager.getEntity(data.target[i].parent);
                if(target)
                {
                    CLocation* target_loc = target.getComponent!CLocation;
                    if(target_loc != null)
                    {
                        data.location[i] = *target_loc + data.target[i].rel_pos;
                    }
                    CVelocity* target_vel = target.getComponent!CVelocity;
                    if(target_vel != null)
                    {
                        data.velocity[i] = *target_vel;
                    }
                }
            }
        }
        else
        foreach(i;0..data.length)
        {
            Entity* target = launcher.manager.getEntity(data.target[i].parent);
            if(target)
            {
                CLocation* target_loc = target.getComponent!CLocation;
                if(target_loc != null)
                {
                    data.location[i] = *target_loc + data.target[i].rel_pos;
                }
            }
        }
    }
}

struct DrawSystem
{
    mixin ECS.System!32;

    struct EntitiesData
    {
        uint length;
        //uint thread_id;
        uint job_id;
        @readonly CTexture[] textures;
        @readonly CLocation[] locations;
        @readonly CScale[] scale;
        @readonly @optional CRotation[] rotation;
        @readonly @optional CDepth[] depth;
        @readonly @optional CHitMark[] hit_mark;
    }

    void onUpdate(EntitiesData data)
    {
        if(!data.depth)
        {
            if(data.hit_mark)
            {
                foreach(i; 0..data.length)
                {
                    uint color = 0x80808080 + 0x01010101 * data.hit_mark[i];
                    short depth = cast(short)(data.locations[i].y);
                    launcher.renderer.draw(space_invaders.texture, data.locations[i].value, data.scale[i], data.textures[i].coords, depth, color, 0, 0, 0, data.job_id);
                }
            }
            else if(data.rotation)
            {
                foreach(i; 0..data.length)
                {
                    short depth = cast(short)(data.locations[i].y);
                    launcher.renderer.draw(space_invaders.texture, data.locations[i].value, data.scale[i], data.textures[i].coords, depth, 0x80808080, data.rotation[i], 0, 0, data.job_id);
                }
            }
            else
            {
                foreach(i; 0..data.length)
                {
                    short depth = cast(short)(data.locations[i].y);
                    launcher.renderer.draw(space_invaders.texture, data.locations[i].value, data.scale[i], data.textures[i].coords, depth, 0x80808080, 0, 0, 0, data.job_id);
                }
            }
        }
        else
        {
            if(data.hit_mark)
            {
                if(data.rotation)
                {
                    foreach(i; 0..data.length)
                    {
                        uint color = 0x80808080 + 0x01010101 * data.hit_mark[i];
                        short depth = cast(short)(data.depth[i] * 8 + data.locations[i].y);
                        launcher.renderer.draw(space_invaders.texture, data.locations[i].value, data.scale[i], data.textures[i].coords, depth, color, data.rotation[i], 0, 0, data.job_id);
                    }
                }
                else
                {
                    foreach(i; 0..data.length)
                    {
                        uint color = 0x80808080 + 0x01010101 * data.hit_mark[i];
                        short depth = cast(short)(data.depth[i] * 8 + data.locations[i].y);
                        launcher.renderer.draw(space_invaders.texture, data.locations[i].value, data.scale[i], data.textures[i].coords, depth, color, 0, 0, 0, data.job_id);
                    }
                }
            }
            else if(data.rotation)
            {
                foreach(i; 0..data.length)
                {
                    short depth = cast(short)(data.depth[i] * 8 + data.locations[i].y);
                    launcher.renderer.draw(space_invaders.texture, data.locations[i].value, data.scale[i], data.textures[i].coords, depth, 0x80808080, data.rotation[i], 0, 0, data.job_id);
                }
            }
            else
            {
                foreach(i; 0..data.length)
                {
                    short depth = cast(short)(data.depth[i] * 8 + data.locations[i].y);
                    launcher.renderer.draw(space_invaders.texture, data.locations[i].value, data.scale[i], data.textures[i].coords, depth, 0x80808080, 0, 0, 0, data.job_id);
                }
            }
        }
        //if(data.thread_id == 0)launcher.renderer.pushData();
    }
}

struct CollisionSystem
{
    mixin ECS.System;

    struct EntitiesData
    {

    }

    void onUpdate(EntitiesData data)
    {

    }
}

struct ShootingSystem
{
    mixin ECS.System!32;

    bool shoot = false;

    __gshared vec4[] fire_frames = [vec4(96,64,8,16)*px,vec4(104,64,8,16)*px,vec4(112,64,8,16)*px,vec4(120,64,8,16)*px,vec4(128,64,8,16)*px,
    vec4(136,64,8,16)*px,vec4(144,64,8,16)*px,vec4(152,64,8,16)*px,vec4(160,64,8,16)*px];

    // __gshared vec4[] fire_frames = [vec4(0,160,8,16)*px,vec4(16,160,16,16)*px,vec4(32,160,16,16)*px,vec4(48,160,16,16)*px,vec4(64,160,16,16)*px,
    // vec4(80,160,16,16)*px,vec4(96,160,16,16)*px,vec4(112,160,16,16)*px];

    struct EntitiesData
    {
        ///variable named "length" contain entites count
        uint length;
        CWeapon[] laser;
        @readonly CLocation[] location;
        @readonly CGuild[] guild;

        @optional @readonly CShootDirection[] shoot_direction;
        @optional @readonly CWeaponLocation[] weapon_location;
        @optional @readonly CAutoShoot[] auto_shoot;
        @optional @readonly CVelocity[] velocity;
        @optional @readonly CRotation[] rotation;
    }

    //EntityTemplate* laser_tmpl;
    EntityTemplate* fire_tmpl;

    //EntityTemplate*[5] bullet_tmpl;
    
    ///Called inside "registerSystem" function
    void onCreate()
    {
        /*bullet_tmpl[0] = launcher.manager.allocateTemplate(
            [CLocation.component_id, CTexture.component_id, CVelocity.component_id, 
            CScale.component_id, CBullet.component_id, CGuild.component_id].staticArray
            );
        bullet_tmpl[0].getComponent!CTexture().coords = vec4(0,24,2,8)*px;
        bullet_tmpl[0].getComponent!CScale().value = vec2(2,8);

        bullet_tmpl[1] = launcher.manager.allocateTemplate(bullet_tmpl[0]);
        bullet_tmpl[2] = launcher.manager.allocateTemplate(bullet_tmpl[0]);
        bullet_tmpl[2].getComponent!CTexture().coords = vec4(64,32,8,16)*px;
        bullet_tmpl[2].getComponent!CScale().value = vec2(8,16);
        bullet_tmpl[3] = launcher.manager.allocateTemplate(bullet_tmpl[0]);
        bullet_tmpl[3].getComponent!CTexture().coords = vec4(56,32,2,2)*px;
        bullet_tmpl[3].getComponent!CScale().value = vec2(2,2);
        // bullet_tmpl[3].getComponent!CTexture().coords = vec4(48,32,8,8)*px;
        // bullet_tmpl[3].getComponent!CScale().value = vec2(8,8);
        bullet_tmpl[4] = launcher.manager.allocateTemplate(bullet_tmpl[0]);*/


        fire_tmpl = launcher.manager.allocateTemplate(
            [CLocation.component_id, CTexture.component_id, CScale.component_id, 
            CAnimation.component_id, CParticle.component_id, CRotation.component_id, 
            CVelocity.component_id, CDamping.component_id].staticArray
            );

        fire_tmpl.getComponent!CTexture().coords = vec4(96,64,8,16)*px;
        fire_tmpl.getComponent!CScale().value = vec2(8,16);
        fire_tmpl.getComponent!(CParticle).life = 300;
        *fire_tmpl.getComponent!(CAnimation) = CAnimation(fire_frames, 0, 3);
    }

    void onDestroy()
    {
        //launcher.manager.freeTemplate(laser_tmpl);
        /*foreach (EntityTemplate* tmpl; bullet_tmpl)
        {
            launcher.manager.freeTemplate(tmpl);
        }*/
        launcher.manager.freeTemplate(fire_tmpl);
    }

    bool onBegin()
    {
        /*laser_location = space_invaders.laser_tmpl.getComponent!CLocation;
        laser_velocity = space_invaders.laser_tmpl.getComponent!CVelocity;
        laser_guild = space_invaders.laser_tmpl.getComponent!CGuild;*/
        if(launcher.getKeyState(SDL_SCANCODE_SPACE))
        {
            shoot = true;
        }
        else shoot = false;
        return true;
    }

    void onUpdate(EntitiesData data)
    {
        //conditional branch for whole entities block
        if(shoot || data.auto_shoot)
        {
            foreach(i;0..data.length)
            {
                CWeapon* laser = &data.laser[i];
                laser.shoot_time += launcher.delta_time;
                while(laser.shoot_time > CWeapon.levels[laser.level - 1].reload_time)
                {
                    CVelocity laser_velocity;
                    CGuild laser_guild;
                    CLocation laser_location;
                    CVelocity fire_velocity;
                    CLocation fire_location;
                    CRotation fire_rotation;

                    laser.shoot_time -= CWeapon.levels[laser.level - 1].reload_time;
                    laser_location.value = data.location[i];

                    laser_velocity.value = vec2((randomf()*2-1) * CWeapon.levels[laser.level - 1].dispersion,1);//data.shoot_direction[i].direction == Direction.up ? 1.0 : -1.0);
                    if(data.shoot_direction && data.shoot_direction[i].direction == Direction.down)laser_velocity.y = -1;

                    laser_guild.guild = data.guild[i].guild;

                    if(laser.level < 3)laser_velocity.value = laser_velocity.value * 0.4f; 
                    
                    if(data.velocity)
                    {
                        fire_velocity.value = data.velocity[i];
                        //laser_velocity.value += data.velocity[i] * 0.5;
                    }
                    else fire_velocity.value = vec2(0,0);

                    fire_location.value = data.location[i];
                    if(data.shoot_direction && data.shoot_direction[i].direction == Direction.down)
                    {
                        fire_rotation.value = PI;
                        //fire_location.value.y -= 16;
                    }
                    else 
                    {
                        fire_rotation.value = 0;
                        //fire_location.value.y += 24;
                    }

                    if(data.rotation)
                    {
                        float sinn = sinf(data.rotation[i]);
                        float coss = cosf(data.rotation[i]);
                        float x = laser_velocity.y*sinn + laser_velocity.x*coss;
                        float y = laser_velocity.y*coss + laser_velocity.x*sinn;
                        laser_velocity.value = vec2(x,y);
                        fire_rotation.value = data.rotation[i];
                        if(data.weapon_location)
                        {
                            vec2 rel_pos = vec2(data.weapon_location[i].rel_pos.y*sinn+data.weapon_location[i].rel_pos.x*coss, data.weapon_location[i].rel_pos.y*coss+data.weapon_location[i].rel_pos.x*sinn);
                            laser_location.value += rel_pos;
                            fire_location.value += rel_pos;
                        }
                    }
                    else if(data.weapon_location)
                    {
                        laser_location.value += data.weapon_location[i].rel_pos;
                        fire_location.value += data.weapon_location[i].rel_pos;
                    }

                    launcher.manager.addEntity(space_invaders.bullet_tmpl[data.laser[i].type],[laser_velocity.ref_, laser_guild.ref_, laser_location.ref_].staticArray);
                    launcher.manager.addEntity(fire_tmpl,[fire_location.ref_, fire_rotation.ref_, fire_velocity.ref_].staticArray);
                }
            }
        }
        else
        {
            foreach(i;0..data.length)
            {
                CWeapon* laser = &data.laser[i];
                laser.shoot_time += launcher.delta_time;
                if(laser.shoot_time > CWeapon.levels[laser.level - 1].reload_time)laser.shoot_time = CWeapon.levels[laser.level - 1].reload_time;
            }
        }
        
    }
}

struct DampingSystem
{
    mixin ECS.System!32;

    struct EntitiesData
    {
        uint length;
        const (Entity)[] entity;
        @readonly CDamping[] damping;
        CVelocity[] velocity;
    }

    float[10] damp = 0;

    bool onBegin()
    {
        foreach(i;0..10)
        {
            damp[i] = powf((0.98 - cast(float)i * 0.02),launcher.delta_time*0.1);
        }

        return true;
    }

    void onUpdate(EntitiesData data)
    {
        foreach(i; 0..data.length)
        {
            data.velocity[i] = data.velocity[i] * damp[data.damping[i]];
        }
    }
}

struct BulletsCollisionSystem
{
    mixin ECS.System!32;

    mixin ECS.ReadOnlyDependencies!(ShootGridDependency);

    struct EntitiesData
    {
        ///variable named "length" contain entites count
        uint length;
        const (Entity)[] entity;
        @readonly CLocation[] location;
        @readonly CBullet[] laser;
        @readonly CGuild[] guild;
    }

    void onUpdate(EntitiesData data)
    {
        EntityID id;
        foreach(i; 0..data.length)
        {
            if(space_invaders.shoot_grid.test(id, data.location[i], cast(ubyte)(~(1 << data.guild[i].guild))))
            {
                launcher.manager.sendEvent(id, EBulletHit(data.entity[i].id,1));
                //launcher.manager.removeEntity(data.entity[i].id);
            }
        }
    }
}

struct ParticleEmittingSystem
{
    mixin ECS.System!32;

    struct EntitiesData
    {
        uint length;
        //uint thread_id;
        CParticleEmitterTime[] emit_time;
        @readonly CLocation[] location;
        @readonly CParticleEmitter[] emitter;

        @optional @readonly CVelocity[] velocity;
        @optional @readonly CDepth[] depth;
    }
    
    __gshared vec4[] flashes = [vec4(224,0,16,16)*px,vec4(240,0,16,16)*px,vec4(256,0,16,16)*px,vec4(272,0,16,16)*px,vec4(288,0,16,16)*px,
    vec4(304,0,16,16)*px,vec4(320,0,16,16)*px];

    EntityTemplate*[1] templates;

    void onCreate()
    {
        templates[0] = launcher.manager.allocateTemplate(
            [CLocation.component_id, CTexture.component_id, CScale.component_id, 
            CAnimation.component_id, CParticle.component_id, CRotation.component_id, 
            CVelocity.component_id, CDamping.component_id, CDepth.component_id].staticArray);
        *templates[0].getComponent!CAnimation() = CAnimation(flashes,0,2);
        *templates[0].getComponent!CParticle() = CParticle(350);
        //*templates[0].getComponent!CDepth() = CDepth(-3);
    }

    void onDestroy()
    {
        foreach(tmpl; templates)
        {
            launcher.manager.freeTemplate(tmpl);
        }
    }

    void onUpdate(EntitiesData data)
    {
        foreach(i;0..data.length)
        {
            data.emit_time[i].time -= launcher.delta_time;
            while(data.emit_time[i].time < 0)
            {
                CVelocity velocity;
                CDepth depth;

                CParticleEmitter* emitter = &data.emitter[i];
                data.emit_time[i].time += emitter.time_range.x + randomf() * emitter.time_range.y;

                if(data.velocity)
                {
                    velocity.value = data.velocity[i];
                }

                if(data.depth)
                {
                    depth.depth = data.depth[i];
                }

                launcher.manager.addEntity(templates[0],[data.location[i].ref_,velocity.ref_,depth.ref_].staticArray);
            }
        }
    }
}

struct UpgradeCollisionSystem
{
    mixin ECS.System!32;

    mixin ECS.ReadOnlyDependencies!(ShootGridDependency);

    struct EntitiesData
    {
        ///variable named "length" contain entites count
        uint length;
        const (Entity)[] entity;
        @readonly CLocation[] location;
        @readonly CUpgrade[] upgrade;
    }

    void onUpdate(EntitiesData data)
    {
        EntityID id;
        foreach(i; 0..data.length)
        {
            if(space_invaders.shoot_grid.test(id, data.location[i], cast(ubyte)(0xFF)))
            {
                Entity* entity = launcher.manager.getEntity(id);
                if(entity && entity.hasComponent(CShip.component_id))
                {
                    launcher.manager.sendEvent(id, EUpgrade());
                    launcher.manager.removeEntity(data.entity[i].id);
                }
            }
        }
    }
}

struct UpgradeSystem
{
    mixin ECS.System;

    struct EntitiesData
    {
        const (Entity)[] entity;
        //@readonly CShip[] ship;
    }

    void handleEvent(Entity* entity, EUpgrade event)
    {
        CWeapon* laser = entity.getComponent!CWeapon;
        if(laser)
        {
            if(laser.level < CWeapon.levels.length)laser.level++;
        }
        CShip* ship = entity.getComponent!CShip;
        if(ship)
        {
            CChildren* children = entity.getComponent!CChildren;
            if(children)
            {
                foreach(child;children.childern)
                {
                    launcher.manager.sendEvent(child,EUpgrade());
                }
            }
        }
    }
}

struct ChangeDirectionSystem
{
    mixin ECS.System!32;

    Direction[8] groups_directions;
    bool has_changes;

    struct EntitiesData
    {
        uint length;
        const (Entity)[] entities;
        const (CLocation)[] locations;
        CVelocity[] velocity;

        const(CSideMove)[] side_move;
        @optional const(CScale)[] scale;
    }

    void onCreate()
    {
        foreach(ref direction; groups_directions)
        {
            direction = cast(Direction)-1;
        }
    }

    void onEnd()
    {
        if(has_changes)
        {
            foreach(ref direction; groups_directions)
            {
                direction = cast(Direction)-1;
            }
        }
        has_changes = false;
        foreach(ref direction; groups_directions)
        {
            if(direction != cast(Direction)-1)
            {
                has_changes = true;
            }
        }
    }

    void onUpdate(EntitiesData data)
    {
        //if(!data.side_move)return;
        if(has_changes)
        foreach(i;0..data.length)
        {
            byte group = data.side_move[i].group;
            if(group == -1)
            {
                if(data.locations[i].x < 0)
                {
                    if(data.velocity[i].x < 0)data.velocity[i].x = -data.velocity[i].x;
                }
                else if(data.locations[i].x > space_invaders.map_size.x)
                {
                    if(data.velocity[i].x > 0)data.velocity[i].x = -data.velocity[i].x;
                }
            }
            else
            {
                Direction direction = groups_directions[group];
                if(direction != cast(Direction)-1)
                {
                    CVelocity* velocity = &data.velocity[i];
                    final switch(direction)
                    {
                        case Direction.up:
                            if(velocity.value.y > 0)velocity.value.y = -velocity.value.y;
                            break;
                        case Direction.down:
                            if(velocity.value.y < 0)velocity.value.y = -velocity.value.y;
                            break;
                        case Direction.left:
                            if(velocity.value.x > 0)velocity.value.x = -velocity.value.x;
                            break;
                        case Direction.right:
                            if(velocity.value.x < 0)velocity.value.x = -velocity.value.x;
                            break;
                    }
                }
            }
        }
        else if(data.scale)
        {
            foreach(i;0..data.length)
            {
                if(data.locations[i].x - data.scale[i].x * 0.5 < 0)
                {
                    if(data.side_move[i].group == -1)
                    {
                        if(data.velocity[i].x < 0)data.velocity[i].x = -data.velocity[i].x;
                    }
                    else
                    {
                        groups_directions[data.side_move[i].group] = Direction.right;
                    }
                }
                else if(data.locations[i].x + data.scale[i].x * 0.5 > space_invaders.map_size.x)
                {
                    if(data.side_move[i].group == -1)
                    {
                        if(data.velocity[i].x > 0)data.velocity[i].x = -data.velocity[i].x;
                    }
                    else
                    {
                        groups_directions[data.side_move[i].group] = Direction.left;
                    }
                }
            }
        }
        else
        {
            foreach(i;0..data.length)
            {
                if(data.locations[i].x < 0)
                {
                    if(data.side_move[i].group == -1)
                    {
                        if(data.velocity[i].x < 0)data.velocity[i].x = -data.velocity[i].x;
                    }
                    else
                    {
                        groups_directions[data.side_move[i].group] = Direction.right;
                    }
                }
                else if(data.locations[i].x > space_invaders.map_size.x)
                {
                    if(data.side_move[i].group == -1)
                    {
                        if(data.velocity[i].x > 0)data.velocity[i].x = -data.velocity[i].x;
                    }
                    else
                    {
                        groups_directions[data.side_move[i].group] = Direction.left;
                    }
                }
            }
        }
    }
}

struct HitMarkingSystem
{
    mixin ECS.System!16;

    struct EntitiesData
    {
        uint length;
        CHitMark[] mark;
    }

    void onUpdate(EntitiesData data)
    {
        foreach(i;0..data.length)
        {
            //if(data.mark[i] < 10)data.mark[i] = 0;
            //else data.mark[i] -= 1;
            data.mark[i] = cast(ubyte)(data.mark[i] * 0.9);
        }
    }
}

struct HitPointsSystem
{
    mixin ECS.System;

    __gshared vec4[] upgrade_laser_frames = [vec4(96,80,16,16)*px,vec4(112,80,16,16)*px,vec4(128,80,16,16)*px,vec4(144,80,16,16)*px,vec4(128,80,16,16)*px,vec4(112,80,16,16)*px];
    __gshared vec4[] explosion_laser_frames = [vec4(80,128,16,16)*px,vec4(96,128,16,16)*px,vec4(112,128,16,16)*px,vec4(128,128,16,16)*px,vec4(144,128,16,16)*px,vec4(160,128,16,16)*px,vec4(176,128,16,16)*px,vec4(192,128,16,16)*px,vec4(208,128,16,16)*px];

    EntityTemplate* upgrade_tmpl;
    EntityTemplate* explosion_tmpl;

    struct EntitiesData
    {
        CHitPoints[] hp;
    }

    void onCreate()
    {
        upgrade_tmpl = launcher.manager.allocateTemplate(
            [CVelocity.component_id, CLocation.component_id, CTexture.component_id, 
            CScale.component_id, CUpgrade.component_id, CAnimation.component_id, 
            CAnimationLooped.component_id].staticArray);
        //tex_comp.tex = space_invaders.texture;//ship_tex;
        upgrade_tmpl.getComponent!CTexture().coords = vec4(0*px,32*px,16*px,16*px);
        *upgrade_tmpl.getComponent!CAnimation = CAnimation(upgrade_laser_frames, 0, 1);
        upgrade_tmpl.getComponent!CVelocity().value = vec2(0,-0.1);

        explosion_tmpl = launcher.manager.allocateTemplate(
            [CDepth.component_id, CParticle.component_id, CLocation.component_id, 
            CTexture.component_id, CScale.component_id, CAnimation.component_id].staticArray);
        //explosion_tmpl.getComponent!(CTexture).tex = space_invaders.texture;
        *explosion_tmpl.getComponent!CAnimation = CAnimation(explosion_laser_frames, 0, 1.333);
        explosion_tmpl.getComponent!(CParticle).life = 600;
        *explosion_tmpl.getComponent!CDepth = -1;
    }

    void onDestroy()
    {
        launcher.manager.freeTemplate(upgrade_tmpl);
        launcher.manager.freeTemplate(explosion_tmpl);
    }

    /*void handleEvent(Entity* entity, EDamage event)
    {
        CHitPoints* hp = entity.getComponent!CHitPoints;
        if(*hp <= 0)return;
        *hp -= event.damage;
        if(*hp <= 0)
        {
            launcher.manager.sendEvent(entity.id, EDeath());
            //launcher.manager.removeEntity(entity.id);
        }
        CHitMark* hit_mark = entity.getComponent!CHitMark;
        if(hit_mark)hit_mark.value = 127;
    }*/
    
    void handleEvent(Entity* entity, EBulletHit event)
    {
        CHitPoints* hp = entity.getComponent!CHitPoints;
        if(*hp <= 0)return;
        launcher.manager.removeEntity(event.id);
        *hp -= event.damage;
        if(*hp <= 0)
        {
            launcher.manager.sendEvent(entity.id, EDeath());
            //launcher.manager.removeEntity(entity.id);
        }
        CHitMark* hit_mark = entity.getComponent!CHitMark;
        if(hit_mark)hit_mark.value = 127;
    }

    void handleEvent(Entity* entity, EDeath event)
    {
        CEnemy* enemy = entity.getComponent!CEnemy;
        if(enemy)
        {
            CLocation* location = entity.getComponent!CLocation;
            if(location)
            {
                if(randomRange(0, 1000) < 5)
                {
                    launcher.manager.addEntity(upgrade_tmpl,[location.ref_].staticArray);
                }
                launcher.manager.addEntity(explosion_tmpl,[location.ref_].staticArray);
            }
        }
        launcher.manager.removeEntity(entity.id);
    }
}

struct ChildDestroySystem
{
    mixin ECS.System;

    struct EntitiesData
    {
        CTargetParent[] parent;
    }

    void handleEvent(Entity* entity, EDeath event)
    {
        CTargetParent* parent = entity.getComponent!CTargetParent;
        if(parent)
        {
            launcher.manager.sendEvent(parent.parent, EDestroyedChild(entity.id));
        }
    }
}

struct ShootWaveSystem
{
    mixin ECS.System;

    struct EntitiesData
    {
        CLocation[] location;
        CShootWaveUponDeath[] shoot_wave;
    }

    vec2[] dirs;

    void onCreate()
    {
        enum count = 24;
        dirs = Mallocator.makeArray!vec2(count);
        float step = 2 * PI / cast(float)count;
        foreach(i;0..count)
        {
            float angle = step * i;
            dirs[i] = vec2(sinf(angle),cosf(angle)) * 0.2;
        }
    }

    void onDestroy()
    {
        Mallocator.dispose(dirs);
    }

    void handleEvent(Entity* entity, EDeath event)
    {

        CShootWaveUponDeath* wave = entity.getComponent!CShootWaveUponDeath;
        CLocation* location = entity.getComponent!CLocation;
        CGuild* guild = entity.getComponent!CGuild;

        //ShootingSystem.bullet_tmpl
        EntityTemplate* tmpl = space_invaders.bullet_tmpl[wave.bullet_type];
        foreach(dir;dirs)
        {
            if(guild)launcher.manager.addEntity(tmpl,[location.ref_,guild.ref_,CVelocity(dir).ref_].staticArray);
            else launcher.manager.addEntity(tmpl,[location.ref_,CVelocity(dir).ref_].staticArray);
        }
        //launcher.manager.addEntity(tmpl);//,[location.ref_].staticArray);

        //launcher.manager.addEntity(space_invaders.bullet_tmpl[0]);
    }
}

struct PartsDestroySystem
{
    mixin ECS.System;

    struct EntitiesData
    {
        CInit[] init;
        CChildren[] children;
        CParts[] parts;
    }

    EntityTemplate* flashes_emitter;

    void onCreate()
    {
        flashes_emitter = launcher.manager.allocateTemplate(
            [
                CVelocity.component_id, CLocation.component_id, CParticleEmitter.component_id,
                CParticleEmitterTime.component_id, CTargetParent.component_id, CDepth.component_id
            ].staticArray);
        *flashes_emitter.getComponent!CParticleEmitter() = CParticleEmitter(vec2(0,0), vec2(800,1600), 0);
    }

    void onDestroy()
    {
        launcher.manager.freeTemplate(flashes_emitter);
    }

    void handleEvent(Entity* entity, EDestroyedChild event)
    {
        CParts* parts = entity.getComponent!CParts;
        parts.count--;

        CInit* init = entity.getComponent!CInit;
        if(init.type == CInit.Type.boss)
        {
            CChildren* children = entity.getComponent!CChildren;
            foreach(ref EntityID child; children.childern)
            {
                if(child == event.id)
                {
                    Entity* child_entity = launcher.manager.getEntity(child);
                    if(child_entity)
                    {
                        CLocation location;
                        CTargetParent* target_parent = child_entity.getComponent!CTargetParent;
                        CDepth* target_depth = child_entity.getComponent!CDepth;
                        CLocation* target_location = child_entity.getComponent!CLocation;
                        //CVelocity* velocity = child_entity.getComponent!CTargetParent;

                        if(target_location)location = *target_location;

                        *flashes_emitter.getComponent!CTargetParent() = *target_parent;
                        if(target_depth)child = launcher.manager.addEntity(flashes_emitter, [target_depth.ref_, location.ref_].staticArray).id;
                        else child = launcher.manager.addEntity(flashes_emitter, [location.ref_].staticArray).id;
                    }
                    break;
                }
            }
        }

        if(parts.count == 0)
        {
            if(init.type == CInit.Type.boss)
            {
                launcher.manager.addComponents(entity.id, CHitPoints(100), CShootGrid());
            }
        }
    }
}

struct ClampPositionSystem
{
    mixin ECS.System!32;
    mixin ECS.ExcludedComponents!(CSideMove);

    struct EntitiesData
    {
        uint length;
        const (Entity)[] entities;
        //components are treated as required by default
        CLocation[] locations;

        @optional @readonly CColliderScale[] collider_scale;
        @optional @readonly CScale[] scale;
        @optional const (CBullet)[] laser;
        @optional const (CUpgrade)[] upgrade;
        //@optional CVelocity[] velocity;
        //@optional const (CSideMove)[] side_move;
    }

    //ChangeDirectionSystem change_direction_system; 

    void onUpdate(EntitiesData data)
    {
        if(data.laser || data.upgrade)
        {
            foreach(i;0..data.length)
            {
                if(data.locations[i].x < 0 || data.locations[i].x > space_invaders.map_size.x || 
                   data.locations[i].y < 0 || data.locations[i].y > space_invaders.map_size.y)launcher.manager.removeEntity(data.entities[i].id);
            }
        }
        /*else if(data.side_move)
        {
            foreach(i;0..data.length)
            {
                if(data.locations[i].x < 0)
                {
                    //data.locations[i].x = 0;
                    //launcher.manager.sendEvent(data.entities[i].id,EChangeDirection(Direction.right));
                    if(data.side_move[i].group == -1)
                    {
                        if(data.velocity[i].x < 0)data.velocity[i].x = -data.velocity[i].x;
                    }
                    else
                    {
                        change_direction_system.groups_directions[data.side_move[i].group] = Direction.left;
                    }
                }
                else if(data.locations[i].x > space_invaders.map_size.x)
                {
                    //data.locations[i].x = space_invaders.map_size.x;
                    //launcher.manager.sendEvent(data.entities[i].id,EChangeDirection(Direction.left));
                    if(data.side_move[i].group == -1)
                    {
                        if(data.velocity[i].x > 0)data.velocity[i].x = -data.velocity[i].x;
                    }
                    else
                    {
                        change_direction_system.groups_directions[data.side_move[i].group] = Direction.right;
                    }
                }
                if(data.locations[i].y < 0) data.locations[i].y = 0;
                else if(data.locations[i].y > space_invaders.map_size.y)data.locations[i].y = space_invaders.map_size.y;
            }
        }*/
        else if(data.collider_scale)
        {
            foreach(i;0..data.length)
            {
                vec2 hscale = data.collider_scale[i] * 0.5;
                if(data.locations[i].x - hscale.x < 0)data.locations[i].x = hscale.x;
                else if(data.locations[i].x + hscale.x > space_invaders.map_size.x)data.locations[i].x = space_invaders.map_size.x - hscale.x;
                if(data.locations[i].y - hscale.y < 0)data.locations[i].y = hscale.y;
                else if(data.locations[i].y + hscale.y > space_invaders.map_size.y)data.locations[i].y = space_invaders.map_size.y - hscale.y;
            }
        }
        else if(data.scale)
        {
            foreach(i;0..data.length)
            {
                vec2 hscale = data.scale[i] * 0.5;
                if(data.locations[i].x - hscale.x < 0)data.locations[i].x = hscale.x;
                else if(data.locations[i].x + hscale.x > space_invaders.map_size.x)data.locations[i].x = space_invaders.map_size.x - hscale.x;
                if(data.locations[i].y - hscale.y < 0)data.locations[i].y = hscale.y;
                else if(data.locations[i].y + hscale.y > space_invaders.map_size.y)data.locations[i].y = space_invaders.map_size.y - hscale.y;
            }
        }
        else
        {
            foreach(i;0..data.length)
            {
                if(data.locations[i].x < 0)data.locations[i].x = 0;
                else if(data.locations[i].x > space_invaders.map_size.x)data.locations[i].x = space_invaders.map_size.x;
                if(data.locations[i].y < 0)data.locations[i].y = 0;
                else if(data.locations[i].y > space_invaders.map_size.y)data.locations[i].y = space_invaders.map_size.y;
            }
        }
    }
}

struct MovementSystem
{
    mixin ECS.System!32;

    struct EntitiesData
    {
        uint length;
        //read only components can be marked with @readonly attribute or with const expression instead 
        const (CVelocity)[] velocity;
        //components are treated as required by default
        CLocation[] locations;
        //@optional const (CBullet)[] laser;
        const (Entity)[] entities;

        //@optional CSideMove[] side_move;
    }

    void onUpdate(EntitiesData data)
    {
        foreach(i;0..data.length)
        {
            data.locations[i].x += data.velocity[i].x * launcher.delta_time * 0.5;
            data.locations[i].y += data.velocity[i].y * launcher.delta_time * 0.5;
        }
    }
}

struct AnimationSystem
{
    mixin ECS.System!32;

    struct EntitiesData
    {
        uint length;
        CAnimation[] animation;
        CTexture[] texture;
        @optional @readonly CAnimationLooped[] looped;
    }

    void onUpdate(EntitiesData data)
    {
        float dt = launcher.delta_time * 0.01;
        if(data.looped)
        {
            foreach(i;0..data.length)
            {
                data.animation[i].time += dt * data.animation[i].speed;
                while(cast(uint)data.animation[i].time >= data.animation[i].frames.length)data.animation[i].time -= cast(float)data.animation[i].frames.length;
                if(cast(uint)(data.animation[i].time) >= data.animation[i].frames.length)assert(0);
                uint index = cast(uint)(data.animation[i].time);
                if(index < data.animation[i].frames.length)data.texture[i].coords = data.animation[i].frames[index];
            }
        }
        else 
        {
            foreach(i;0..data.length)
            {
                data.animation[i].time += dt * data.animation[i].speed;
                if(cast(uint)data.animation[i].time >= data.animation[i].frames.length)data.animation[i].time = data.animation[i].frames.length - 0.9;
                uint index = cast(uint)(data.animation[i].time);
                if(index < data.animation[i].frames.length)data.texture[i].coords = data.animation[i].frames[index];
            }
        }

    }
}

struct ParticleSystem
{
    mixin ECS.System!32;

    struct EntitiesData
    {
        uint length;
        @readonly Entity[] entitiy;
        CParticle[] particle;
    }

    void onUpdate(EntitiesData data)
    {
        foreach(i;0..data.length)
        {
            data.particle[i].life -= launcher.delta_time;
            if(data.particle[i].life < 0)launcher.manager.removeEntity(data.entitiy[i].id);
        }
    }
}

struct RotateToTargetSystem
{
    mixin ECS.System!32;

    struct EntitiesData
    {
        int length;
        @readonly CTarget[] target;
        @readonly CLocation[] location;
        CRotation[] rotation;
    }

    void onUpdate(EntitiesData data)
    {
        foreach(i;0..data.length)
        {
            Entity* target = launcher.manager.getEntity(data.target[i].target);
            if(target)
            {
                CLocation* target_loc = target.getComponent!CLocation;
                if(target_loc)
                {
                    vec2 rel_pos = target_loc.value - data.location[i];
                    float length = sqrtf(rel_pos.x*rel_pos.x + rel_pos.y*rel_pos.y);
                    if(rel_pos.x > 0)data.rotation[i] = acosf(rel_pos.y/length);
                    else data.rotation[i] = 2 * PI - acosf(rel_pos.y/length);

                }
            }
            //CLocation* target_loc = 
            //vec2 rel_pos = d
            //data.rotation = 0;
        }
    }
}

struct ShipTargetSystem
{
    mixin ECS.System!32;

    struct EntitiesData
    {
        int length;
        @readonly CTargetPlayerShip[] target_player;
        CTarget[] target;
    }

    EntityID player_ship;

    void iterateShips(CShipIterator.EntitiesData data)
    {
        player_ship = data.entity[0].id;
    }

    void onAddEntity(EntitiesData data)
    {
        foreach(i;0..data.length)
        {
            data.target[i].target = player_ship;
        }
    }

    bool onBegin()
    {
        Entity* ship = launcher.manager.getEntity(player_ship);
        if(ship is null)
        {
            launcher.manager.callEntitiesFunction!CShipIterator(&iterateShips);
            ship = launcher.manager.getEntity(player_ship);
            if(ship is null)return false;
            return true;
        }
        return false;
    }

    void onUpdate(EntitiesData data)
    {
        foreach(i;0..data.length)
        {
            data.target[i].target = player_ship;
        }
    }
}

struct CShipIterator
{
    mixin ECS.System!1;

    struct EntitiesData
    {
        @readonly Entity[] entity;
        @readonly CShip[] ship;
    }

    bool onBegin()
    {
        return false;
    }

    void onUpdate(EntitiesData data)
    {
        
    }
}

/*struct SpawnUponDeathSystem
{
    mixin ECS.System;

    struct EntitiesData
    {
        @readonly CSpawnUponDeath[] spawn;
        @optional CTargetParent[] parent;
    }

    EntityTemplate* flashes_emitter;

    void onCreate()
    {
        flashes_emitter = launcher.manager.allocateTemplate(
            [
                CVelocity.component_id, CLocation.component_id, CParticleEmitter.component_id,
                CParticleEmitterTime.component_id, CTargetParent.component_id
            ].staticArray);
        *flashes_emitter.getComponent!CParticleEmitter() = CParticleEmitter(vec2(0,0), vec2(400,400), 0);
    }

    void onDestroy()
    {
        launcher.manager.freeTemplate(flashes_emitter);
    }

    void onRemoveEntity(EntitiesData data)
    {
        //CSpawnUponDeath[] spawn = 
        switch(data.spawn[0].type)
        {
            case CSpawnUponDeath.Type.flashes_emitter:
                if(data.parent)
                {
                    /*Entity* parent_entity = launcher.manager.getEntity(data.parent[0].parent);
                    CChildren* children = entity.getComponent!CChildren;
                    foreach(ref EntityID child; children.childern)
                    {
                        if(child == event.id)
                        {
                            Entity* child_entity = launcher.manager.getEntity(child);
                            if(child_entity)
                            {
                                *flashes_emitter.getComponent!CTargetParent = data.parent[0];
                                launcher.manager.addEntity(flashes_emitter);
                                //child = launcher.manager.addEntity(flashes_emitter);
                            }
                            break;
                        }
                    }
                }
                break;
            default:break;
        }
    }

    //void handleEvent(Entity* entity, )
}//*/

/**
*System is responsible for movement of objects with CInput component.
*In this example every entity has same speed when using movement system.
*/
struct InputMovementSystem
{
    mixin ECS.System!32;

    vec2 move_vector;

    struct EntitiesData
    {
        uint length;
        //read only components can be marked with @readonly attribute or with const expression instead 
        const (CInput)[] input;
        //components are treated as required by default
        //CLocation[] locations;
        CVelocity[] velocity;
        CTexture[] textures;
    }

    /**
    *onBegin gives opportunity to check keys once and call update on entities only when
    *one key is pressed.
    */
    bool onBegin()
    {
        move_vector = vec2(0,0);
        if(launcher.getKeyState(SDL_SCANCODE_W))
        {
            move_vector += vec2(0,1);
        }
        else if(launcher.getKeyState(SDL_SCANCODE_S))
        {
            move_vector += vec2(0,-1);
        } 
        if(launcher.getKeyState(SDL_SCANCODE_A))
        {
            move_vector += vec2(-1,0);
        }
        else if(launcher.getKeyState(SDL_SCANCODE_D))
        {   
            move_vector += vec2(1,0);
        }

        if(move_vector.x != 0 ||move_vector.y != 0)
        {
            move_vector = move_vector / sqrtf(move_vector.x * move_vector.x + move_vector.y * move_vector.y);
            return true;
        }
        //don't call system update because no key pressed 
        return false;
    }

    /**
    *Update is called multiple times in one "manager.update()" call.
    *Number of "onUpdate" calls is count of buffers which must be updated during pass.
    *When multithreading is used, number of "onUpdate" calls can be greater due to fact that
    *JobSystem can split buffers for better data packing.
    */
    void onUpdate(EntitiesData data)
    {
        /*if(move_vector.x == 0)
        {
            foreach(i; 0..data.length)
            {
                data.textures[i].coords = vec4(0*px,80*px,48*px,32*px);
            }
            //return;
        }*/
        //move every entity using movement vector
        //if(move_vector.x != 0 || move_vector.y != 0)
        foreach(i; 0..data.length)
        {
            data.velocity[i] += move_vector * launcher.delta_time * 0.005;
            if(data.velocity[i].x > 0.5)data.velocity[i].x = 0.5;
            else if(data.velocity[i].x < -0.5)data.velocity[i].x = -0.5;
            if(data.velocity[i].y > 0.5)data.velocity[i].y = 0.5;
            else if(data.velocity[i].y < -0.5)data.velocity[i].y = -0.5;
            //data.locations[i].x += move_vector.x * launcher.delta_time * 0.25;
            //data.locations[i].y += move_vector.y * launcher.delta_time * 0.25;
            //if(move_vector.x > 0)data.textures[i].coords = vec4(48*px,80*px,48*px,32*px);
            //else data.textures[i].coords = vec4(0*px,80*px,48*px,32*px);
        }
        /*else 
        foreach(i; 0..data.length)
        {
            data.velocity[i] = vec2(0,0);
        }*/
    }
}

/*#######################################################################################################################
------------------------------------------------ Functions ------------------------------------------------------------------
#######################################################################################################################*/

__gshared SpaceInvaders* space_invaders;

void spaceInvadersStart()
{
    space_invaders = Mallocator.make!SpaceInvaders;

    space_invaders.texture.create();
    space_invaders.texture.load("assets/textures/atlas.png");

    space_invaders.shoot_grid = Mallocator.make!ShootGrid;
    space_invaders.shoot_grid.create(ivec2(80,60), vec2(5,5));

    launcher.manager.beginRegister();

    launcher.manager.registerDependency(ShootGridDependency);

    launcher.manager.registerComponent!CLocation;
    launcher.manager.registerComponent!CTexture;
    launcher.manager.registerComponent!CInput;
    launcher.manager.registerComponent!CShip;
    launcher.manager.registerComponent!CEnemy;
    launcher.manager.registerComponent!CScale;
    launcher.manager.registerComponent!CShootDirection;
    launcher.manager.registerComponent!CAutoShoot;
    launcher.manager.registerComponent!CWeapon;
    launcher.manager.registerComponent!CVelocity;
    launcher.manager.registerComponent!CBullet;
    launcher.manager.registerComponent!CSideMove;
    launcher.manager.registerComponent!CDepth;
    launcher.manager.registerComponent!CShootGrid;
    launcher.manager.registerComponent!CGuild;
    launcher.manager.registerComponent!CHitPoints;
    launcher.manager.registerComponent!CHitMark;
    launcher.manager.registerComponent!CUpgrade;
    launcher.manager.registerComponent!CParticle;
    launcher.manager.registerComponent!CMaxHitPoints;
    launcher.manager.registerComponent!CAnimation;
    launcher.manager.registerComponent!CRotation;
    launcher.manager.registerComponent!CAnimationLooped;
    launcher.manager.registerComponent!CDamping;
    launcher.manager.registerComponent!CTargetParent;
    launcher.manager.registerComponent!CTarget;
    launcher.manager.registerComponent!CTargetPlayerShip;
    launcher.manager.registerComponent!CChildren;
    launcher.manager.registerComponent!CWeaponLocation;
    launcher.manager.registerComponent!CInit;
    launcher.manager.registerComponent!CBoss;
    launcher.manager.registerComponent!CParts;
    launcher.manager.registerComponent!CColliderScale;
    launcher.manager.registerComponent!CParticleEmitter;
    launcher.manager.registerComponent!CParticleEmitterTime;
    launcher.manager.registerComponent!CSpawnUponDeath;
    launcher.manager.registerComponent!CShootWaveUponDeath;

    launcher.manager.registerEvent!EChangeDirection;
    launcher.manager.registerEvent!EDamage;
    launcher.manager.registerEvent!EUpgrade;
    launcher.manager.registerEvent!EDeath;
    launcher.manager.registerEvent!EDestroyedChild;
    launcher.manager.registerEvent!EBulletHit;

    //launcher.manager.registerSystem!MoveSystem(0);
    launcher.manager.registerSystem!DrawSystem(100);
    launcher.manager.registerSystem!InputMovementSystem(-100);
    launcher.manager.registerSystem!MovementSystem(-99);
    launcher.manager.registerSystem!ClampPositionSystem(-90);
    launcher.manager.registerSystem!ShootingSystem(0);
    launcher.manager.registerSystem!ChangeDirectionSystem(0);
    launcher.manager.registerSystem!BulletsCollisionSystem(-70);
    launcher.manager.registerSystem!ShootGridManager(-80);
    launcher.manager.registerSystem!ShootGridCleaner(-101);
    launcher.manager.registerSystem!HitPointsSystem(0);
    launcher.manager.registerSystem!HitMarkingSystem(-100);
    launcher.manager.registerSystem!UpgradeCollisionSystem(-70);
    launcher.manager.registerSystem!UpgradeSystem(-100);
    launcher.manager.registerSystem!ParticleSystem(-100);
    launcher.manager.registerSystem!AnimationSystem(-100);
    launcher.manager.registerSystem!DampingSystem(-101);
    launcher.manager.registerSystem!MoveToParentTargetSystem(-98);
    launcher.manager.registerSystem!ParentOwnerSystem(-101);
    launcher.manager.registerSystem!ShipWeaponSystem(-100);
    launcher.manager.registerSystem!ParticleEmittingSystem(-95);
    launcher.manager.registerSystem!RotateToTargetSystem(-100);
    launcher.manager.registerSystem!ShipTargetSystem(-110);
    launcher.manager.registerSystem!CShipIterator(-100);
    launcher.manager.registerSystem!PartsDestroySystem(-80);
    launcher.manager.registerSystem!ChildDestroySystem(-110);
    launcher.manager.registerSystem!ShootWaveSystem(-100);
    //launcher.manager.registerSystem!SpawnUponDeathSystem(-110);
    
    launcher.manager.endRegister();

    launcher.gui_manager.addComponent(CInput(),"Input");
    launcher.gui_manager.addComponent(CShip(),"Ship");
    launcher.gui_manager.addComponent(CEnemy(),"Enemy");
    launcher.gui_manager.addComponent(CAutoShoot(),"Auto Shoot");
    launcher.gui_manager.addComponent(CWeapon(0, CWeapon.Type.laser),"Weapon (laser)");
    launcher.gui_manager.addComponent(CVelocity(vec2(0,0)),"Velocity (0,0)");
    launcher.gui_manager.addComponent(CBullet(),"Bullet (dmg1)");
    launcher.gui_manager.addComponent(CSideMove(),"Side Move");
    launcher.gui_manager.addComponent(CSideMove(0),"Side Move (g1)");
    launcher.gui_manager.addComponent(CSideMove(1),"Side Move (g2)");
    launcher.gui_manager.addComponent(CShootGrid(),"Shoot Grid");
    launcher.gui_manager.addComponent(CGuild(),"Guild (Player)");
    launcher.gui_manager.addComponent(CGuild(1),"Guild (Enemy)");
    launcher.gui_manager.addComponent(CHitPoints(10),"Hit Points (10)");
    launcher.gui_manager.addComponent(CHitMark(),"Hit Mark");
    launcher.gui_manager.addComponent(CUpgrade(CUpgrade.Upgrade.laser),"Upgrade (laser)");
    launcher.gui_manager.addComponent(CParticle(1000),"Particle (1s)");
    //launcher.gui_manager.addComponent(CMaxHitPoints(),"Max Hit Points");
    launcher.gui_manager.addComponent(CDamping(0),"Damping (0)");
    launcher.gui_manager.addComponent(CDamping(4),"Damping (4)");
    launcher.gui_manager.addComponent(CDamping(8),"Damping (8)");
    launcher.gui_manager.addComponent(CTargetParent(),"Target Parent");
    launcher.gui_manager.addComponent(CTargetPlayerShip(),"Target Player Ship");
    launcher.gui_manager.addComponent(CTarget(),"Target");
    launcher.gui_manager.addComponent(CChildren(),"Children");
    launcher.gui_manager.addComponent(CWeaponLocation(vec2(0,16)),"Weapon Location (0,16)");
    launcher.gui_manager.addComponent(CInit(CInit.Type.space_ship),"Init (Ship)");
    launcher.gui_manager.addComponent(CInit(CInit.Type.boss),"Init (Boss)");
    launcher.gui_manager.addComponent(CInit(CInit.Type.tower),"Init (Tower)");
    launcher.gui_manager.addComponent(CBoss(),"Boss");
    launcher.gui_manager.addComponent(CColliderScale(),"Collider Scale");
    launcher.gui_manager.addComponent(CParticleEmitter(),"Particle Emitter");
    launcher.gui_manager.addComponent(CParticleEmitterTime(),"Particle Emitter Time");
    //launcher.gui_manager.addComponent(CSpawnUponDeath(),"Spawn Upon Death");
    launcher.gui_manager.addComponent(CShootWaveUponDeath(CWeapon.Type.canon),"Wave Upon Death");

    launcher.gui_manager.addSystem(DrawSystem.system_id,"Draw System");
    launcher.gui_manager.addSystem(InputMovementSystem.system_id,"Input Movement");
    launcher.gui_manager.addSystem(ShootingSystem.system_id,"Shooting System");
    launcher.gui_manager.addSystem(MovementSystem.system_id,"Movement System");
    launcher.gui_manager.addSystem(ClampPositionSystem.system_id,"Clamp Position System");
    launcher.gui_manager.addSystem(ChangeDirectionSystem.system_id,"Change Direction System");
    launcher.gui_manager.addSystem(BulletsCollisionSystem.system_id,"Bullets Collision System");
    launcher.gui_manager.addSystem(ShootGridManager.system_id,"Shoot Grid Manager");
    launcher.gui_manager.addSystem(ShootGridCleaner.system_id,"Shoot Grid Cleaner");
    launcher.gui_manager.addSystem(HitPointsSystem.system_id,"Hit Points System");
    launcher.gui_manager.addSystem(HitMarkingSystem.system_id,"Hit Marking System");
    launcher.gui_manager.addSystem(UpgradeCollisionSystem.system_id,"Upgrade Collision System");
    launcher.gui_manager.addSystem(UpgradeSystem.system_id,"Upgrade System");
    launcher.gui_manager.addSystem(ParticleSystem.system_id,"Particle System");
    launcher.gui_manager.addSystem(AnimationSystem.system_id,"Animation System");
    launcher.gui_manager.addSystem(DampingSystem.system_id,"Damping System");
    launcher.gui_manager.addSystem(MoveToParentTargetSystem.system_id,"Move To Target System");
    launcher.gui_manager.addSystem(ParentOwnerSystem.system_id,"Parent Owner System");
    launcher.gui_manager.addSystem(ShipWeaponSystem.system_id,"Ship Weapon System");
    launcher.gui_manager.addSystem(ParticleEmittingSystem.system_id,"Particle Emitting System");
    launcher.gui_manager.addSystem(RotateToTargetSystem.system_id,"Rotate To Target System");
    launcher.gui_manager.addSystem(ShipTargetSystem.system_id,"Ship Target System");
    launcher.gui_manager.addSystem(PartsDestroySystem.system_id,"Parts Destroy System");
    launcher.gui_manager.addSystem(ChildDestroySystem.system_id,"Child Destroy System");
    launcher.gui_manager.addSystem(ShootWaveSystem.system_id,"Shoot Wave System");
    //launcher.gui_manager.addSystem(SpawnUponDeathSystem.system_id,"Child Destroy System");

    //launcher.manager.getSystem(CleanSystem.system_id).disable();
    {
        space_invaders.ship_tmpl = launcher.manager.allocateTemplate(
                [CVelocity.component_id, CHitMark.component_id, CHitPoints.component_id, 
                CLocation.component_id, CTexture.component_id, CInput.component_id, 
                CShip.component_id, CScale.component_id, CColliderScale.component_id,
                CShootDirection.component_id, CShootGrid.component_id, CGuild.component_id,
                CDamping.component_id, CChildren.component_id, CInit.component_id].staticArray
                );
        space_invaders.ship_tmpl.getComponent!CTexture().coords = vec4(0,80,48,32)*px;
        space_invaders.ship_tmpl.getComponent!CScale().value = vec2(48,32);
        space_invaders.ship_tmpl.getComponent!CHitPoints().value = 1000;
        space_invaders.ship_tmpl.getComponent!CDamping().value = 7;
        space_invaders.ship_tmpl.getComponent!CInit().type = CInit.Type.space_ship;
        space_invaders.ship_tmpl.getComponent!CColliderScale().value = vec2(26,24);

        launcher.manager.addEntity(space_invaders.ship_tmpl,[CLocation(vec2(64,64)).ref_].staticArray);
    }

    {
        ushort[6] components = [CLocation.component_id, CTexture.component_id, CVelocity.component_id, CScale.component_id, CBullet.component_id, CGuild.component_id];
        space_invaders.laser_tmpl = launcher.manager.allocateTemplate(components);

        space_invaders.laser_tmpl.getComponent!CTexture().coords = vec4(0,24,2,8)*px;
        space_invaders.laser_tmpl.getComponent!CScale().value = vec2(2,8);
        space_invaders.laser_tmpl.getComponent!CVelocity().value = vec2(0,1);
    }

    EntityTemplate* enemy_tmpl;
    EntityTemplate* grouped_tmpl;
    EntityTemplate* tower_tmpl;
    EntityTemplate* boss_tmpl;
    //EntityTemplate* tower_weapon_tmpl;
    EntityID enemy_id;
    EntityID grouped_id;

    {
        boss_tmpl = launcher.manager.allocateTemplate(
            [CHitMark.component_id, CParts.component_id, CLocation.component_id, 
            CTexture.component_id, CScale.component_id, CEnemy.component_id, 
            CBoss.component_id, CGuild.component_id, CInit.component_id,
            CChildren.component_id, CSideMove.component_id, CVelocity.component_id,
            CDepth.component_id].staticArray
        );

        //CTexture* tex_comp = boss_tmpl.getComponent!CTexture;
        //tex_comp.tex = space_invaders.texture;//ship_tex;
        //tex_comp.coords = vec4(128*px,0*px,96*px,48*px);
        //CLocation* loc_comp = boss_tmpl.getComponent!CLocation;
        //loc_comp.value = vec2(64,space_invaders.map_size.y - 16);
        boss_tmpl.getComponent!CTexture().coords =  vec4(128,0,96,48)*px;
        boss_tmpl.getComponent!CGuild().guild = 1;
        boss_tmpl.getComponent!CInit().type = CInit.Type.boss;  
        boss_tmpl.getComponent!CScale().value = vec2(96,48);  
        boss_tmpl.getComponent!CDepth().depth = -1;
        boss_tmpl.getComponent!CParts().count = 4;
        boss_tmpl.getComponent!CVelocity().value =  vec2(0.05,0);
    }

    {
        tower_tmpl = launcher.manager.allocateTemplate(
            [CHitMark.component_id, CHitPoints.component_id, CLocation.component_id, 
            CTexture.component_id, CScale.component_id, CEnemy.component_id, 
            CShootGrid.component_id, CGuild.component_id, CInit.component_id,
            CChildren.component_id].staticArray
        );

        tower_tmpl.getComponent!CTexture().coords = vec4(96,96,16,16)*px;
        tower_tmpl.getComponent!CGuild().guild = 1;
        tower_tmpl.getComponent!CInit().type = CInit.Type.tower;  
        tower_tmpl.getComponent!CHitPoints().value = 10;
    }

    {
        space_invaders.enemy_tmpl = launcher.manager.allocateTemplate(
            [CWeaponLocation.component_id, CHitMark.component_id, CHitPoints.component_id, 
            CVelocity.component_id, CAutoShoot.component_id, CLocation.component_id, 
            CTexture.component_id, CScale.component_id, CWeapon.component_id, 
            CEnemy.component_id, CShootDirection.component_id, CShootGrid.component_id, 
            CGuild.component_id].staticArray
        );

        space_invaders.enemy_tmpl.getComponent!CTexture().coords = vec4(32,32,16,16)*px;
        space_invaders.enemy_tmpl.getComponent!CShootDirection().direction = Direction.down;
        space_invaders.enemy_tmpl.getComponent!CVelocity().value = vec2(0.1,0);
        space_invaders.enemy_tmpl.getComponent!CGuild().guild = 1;
        space_invaders.enemy_tmpl.getComponent!CWeaponLocation().rel_pos = vec2(0,-15);
        
        Entity* current_entity;

        current_entity = launcher.manager.addEntity(space_invaders.enemy_tmpl,[CLocation(vec2(32,space_invaders.map_size.y - 16)).ref_].staticArray);
        launcher.manager.addComponents(current_entity.id,CSideMove(0));
        
        //loc_comp.value = vec2(128,space_invaders.map_size.y - 16);
        current_entity = launcher.manager.addEntity(space_invaders.enemy_tmpl,[CLocation(vec2(128,space_invaders.map_size.y - 16)).ref_].staticArray);
        launcher.manager.addComponents(current_entity.id,CSideMove(-1));

        enemy_id = current_entity.id;
        //enemy_tmpl = launcher.manager.allocateTemplate(current_entity.id);
        
        //loc_comp.value = vec2(256,space_invaders.map_size.y - 16);
        launcher.manager.addEntity(space_invaders.enemy_tmpl,[CLocation(vec2(256,space_invaders.map_size.y - 16)).ref_].staticArray);

        //loc_comp.value = vec2(0,space_invaders.map_size.y - 16);
        current_entity = launcher.manager.addEntity(space_invaders.enemy_tmpl,[CLocation(vec2(0,space_invaders.map_size.y - 16)).ref_].staticArray);
        launcher.manager.addComponents(current_entity.id,CSideMove(0));

        grouped_id = current_entity.id;
        //grouped_tmpl = launcher.manager.allocateTemplate(current_entity.id);
    }
    
    EntityTemplate* upgrade_tmpl;

    {
        upgrade_tmpl = launcher.manager.allocateTemplate([CVelocity.component_id, CLocation.component_id, CTexture.component_id, CScale.component_id, CUpgrade.component_id, CAnimationLooped.component_id, CAnimation.component_id].staticArray);
        upgrade_tmpl.getComponent!CTexture().coords = vec4(0,32,16,16)*px;
        upgrade_tmpl.getComponent!CVelocity().value = vec2(0,-0.1);
        *upgrade_tmpl.getComponent!CAnimation = CAnimation(HitPointsSystem.upgrade_laser_frames, 0, 0.75);
    }

    launcher.manager.commit();

    enemy_tmpl = launcher.manager.allocateTemplate(enemy_id);
    grouped_tmpl = launcher.manager.allocateTemplate(grouped_id);

    space_invaders.bullet_tmpl[0] = launcher.manager.allocateTemplate(
        [CLocation.component_id, CTexture.component_id, CVelocity.component_id, 
        CScale.component_id, CBullet.component_id, CGuild.component_id].staticArray
        );
    space_invaders.bullet_tmpl[0].getComponent!CTexture().coords = vec4(0,24,2,8)*px;
    space_invaders.bullet_tmpl[0].getComponent!CScale().value = vec2(2,8);

    space_invaders.bullet_tmpl[1] = launcher.manager.allocateTemplate(space_invaders.bullet_tmpl[0]);
    space_invaders.bullet_tmpl[2] = launcher.manager.allocateTemplate(space_invaders.bullet_tmpl[0]);
    space_invaders.bullet_tmpl[2].getComponent!CTexture().coords = vec4(64,32,8,16)*px;
    space_invaders.bullet_tmpl[2].getComponent!CScale().value = vec2(8,16);
    space_invaders.bullet_tmpl[3] = launcher.manager.allocateTemplate(space_invaders.bullet_tmpl[0]);
    space_invaders.bullet_tmpl[3].getComponent!CTexture().coords = vec4(56,32,2,2)*px;
    space_invaders.bullet_tmpl[3].getComponent!CScale().value = vec2(2,2);
    // bullet_tmpl[3].getComponent!CTexture().coords = vec4(48,32,8,8)*px;
    // bullet_tmpl[3].getComponent!CScale().value = vec2(8,8);
    space_invaders.bullet_tmpl[4] = launcher.manager.allocateTemplate(space_invaders.bullet_tmpl[0]);

    launcher.gui_manager.addTemplate(enemy_tmpl,"Enemy");
    launcher.gui_manager.addTemplate(grouped_tmpl,"Grouped enemy");
    launcher.gui_manager.addTemplate(launcher.manager.allocateTemplate(space_invaders.ship_tmpl),"Ship");
    launcher.gui_manager.addTemplate(launcher.manager.allocateTemplate(space_invaders.laser_tmpl),"Laser");
    launcher.gui_manager.addTemplate(upgrade_tmpl,"Upgrade");
    launcher.gui_manager.addTemplate(tower_tmpl,"Tower");
    launcher.gui_manager.addTemplate(boss_tmpl,"Boss");
    launcher.gui_manager.addTemplate(launcher.manager.allocateTemplate(space_invaders.bullet_tmpl[3]),"Cannon bullet");
    //launcher.gui_manager.addTemplate(launcher.manager.allocateTemplate(space_invaders.bullet_tmpl[4]),"Laser");
    //launcher.gui_manager.addTemplate(launcher.manager.allocateTemplate(space_invaders.bullet_tmpl[5]),"Laser");
}

void spaceInvadersEnd()
{
    /*launcher.manager.getSystem(DrawSystem.system_id).disable();
    launcher.manager.getSystem(InputMovementSystem.system_id).disable();
    launcher.manager.getSystem(ShootingSystem.system_id).disable();
    launcher.manager.getSystem(MovementSystem.system_id).disable();
    launcher.manager.getSystem(ClampPositionSystem.system_id).disable();
    launcher.manager.getSystem(ShootGridCleaner.system_id).disable();*/

    //launcher.manager.freeTemplate(space_invaders.enemy_tmpl);
    Mallocator.dispose(space_invaders);
    space_invaders = null;
}

void spaceInvadersEvent(SDL_Event* event)
{

}

bool spaceInvadersLoop()
{
    launcher.render_position = (vec2(launcher.window_size.x,launcher.window_size.y)*launcher.scalling - vec2(400,300)) * 0.5;

    /*if(launcher.show_demo_wnd)
    {
        igSetNextWindowPos(ImVec2(800 - 260, 30), ImGuiCond_Once, ImVec2(0,0));
        igSetNextWindowSize(ImVec2(250, 0), ImGuiCond_Once);
        if(igBegin("Simple",&launcher.show_demo_wnd,0))
        {
            if(igCheckbox("Move system",&simple.move_system))
            {
                if(simple.move_system)launcher.manager.getSystem(MoveSystem.system_id).enable();
                else launcher.manager.getSystem(MoveSystem.system_id).disable();
            }
            if(igCheckbox("Draw system",&simple.draw_system))
            {
                if(simple.draw_system)launcher.manager.getSystem(DrawSystem.system_id).enable();
                else launcher.manager.getSystem(DrawSystem.system_id).disable();
            }
            igPushButtonRepeat(true);
            igColumns(3,null,0);
            if(igButton("Spawn",ImVec2(-1,0)))
            {
                spawnEntity();
            }
            igNextColumn();
            if(igButton("+10",ImVec2(-1,0)))
            {
                foreach(i;0..10)spawnEntity();
            }
            igNextColumn();
            if(igButton("+100",ImVec2(-1,0)))
            {
                foreach(i;0..100)spawnEntity();
            }
            igPopButtonRepeat();
            igColumns(1,null,0);
            if(igButton("Clear",ImVec2(-1,0)))
            {
                launcher.manager.getSystem(CleanSystem.system_id).enable();
                launcher.manager.begin();
                launcher.manager.update();
                launcher.manager.end();
                launcher.manager.getSystem(CleanSystem.system_id).disable();
            }
        }
        igEnd();
    }*/

    /*if(launcher.show_tips)
    {
        igSetNextWindowPos(ImVec2(800 - 550, 80), ImGuiCond_Once, ImVec2(0,0));
        igSetNextWindowSize(ImVec2(300, 0), ImGuiCond_Once);
        if(igBegin("Tips",&launcher.show_tips,ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings))
        {
            igTextWrapped("Use \"space\" to spwan entities.\n\nSystems can be enabled/disabled from \"Simple\" window.");
        }
        igEnd();
    }*/

    launcher.manager.begin();
    if(launcher.multithreading)
    {
        launcher.job_updater.begin();
        launcher.manager.updateMT();
        launcher.job_updater.call();
    }
    else
    {
        launcher.manager.update();
    }
    launcher.manager.end();

    /*foreach(i;0..1000)//13000)
    {
        launcher.renderer.draw(simple.texture,vec2(i%100*32,i/100*32),vec2(32,32),vec4(0,0,1,1),0.0);
    }*/

    return true;
}