C# Artemis Entity System Tutorial


Artemis is a high performance Entity System framework for games, originally written in Java by Arni Arent and Tiago Costa, now ported to C#.
Its goal is to provide a clean API to abstract your game world organization into entities, components and systems.
Artemis has no dependencies (for PC, in Xbox and Windows Phone 7 we have one) and can be used with any game framework or library, 2D or 3D, and even multiplatform, if you use it with Mono/MonoTouch/Mono4Android.

Differences from the original version

We support all the features included in the original Java version, but we’ve also added the following features:

  • Multithreading Support (two ways of doing this)
  • Specialized System templates for your multithreading needs
  • Communication between Systems using a Blackboard approach
  • Bugs fixed, performance improvements
  • Xbox/WP7/Mono(Android/Linux/Mac/iOS) support
  • Events for intercepting adding/removal of entities/components
  • Blackboard for sharing common objects between systems
  • Entity Pool (to make objects reusable, minimize garbage collection activity, improve performance)
  • Small goodies, like feeding the EntityWorld with whole Entities(maybe loading from external resources), enabling/disabling systems and entities, getting Entity tag, API shortcuts(see unit tests for more on this), etc.

Getting Started

  • Entities are only an aggregation of Components, identified by a unique id
  • Components are only data
  • Systems publish/subscribe to Components, creating behavior

There is much more to tell about this paradigm and we already have rich articles which inspired this framework. Some of them:

And many more can be found here.

Your components must inherit from the class Component or ComponentPoolable if you want it to use the Artemis Component Pool. Example:

//Add this Attribute and extend ComponentPoolable if you want your Component to use Artemis Component Pool
[Artemis.Attributes.ArtemisComponentPool(InitialSize=5,Resizes=true, ResizeSize=20, isSupportMultiThread=false)]
class Velocity : ComponentPoolable
{
        private float velocity;
        private float angle;

        public Velocity() { }

        public Velocity(float vector)
        {
            velocity = vector;
        }

        public Velocity(float velocity, float angle)
        {
            this.velocity = velocity;
            this.angle = angle;
        }

        public float Speed {
            get { return velocity;}
            set { velocity = value; }
        }

        public float Angle
        {
            get { return angle; }
            set { angle = value;}
        }

        public void AddAngle(float a)
        {
            angle = (angle + a) % 360;
        }

        public float AngleAsRadians
        {
            get { return (float)Math.PI * angle / 180.0f; }
        }

        //obligatory for poolable Components
        public void Cleanup()
        {
             coords = Vector3.Zero;
        }
}

A sample for entity assembling:

Entity e = world.CreateEntity(); // you can pass an unique ID as first parameter.
e.AddComponent(new Transform(200,400));
e.AddComponentFromPool(new Velocity(2.4f,0.9f)); // use AddComponentFromPool if the Component extend from ComponentPoolable
e.Refresh();// always call Refresh() when adding/removing components!

Your systems should inherit from one of the following templates:

  • EntitySystem – the simplest system template, not tied to components, good for stuff like collision
  • EntityProcessingSystem – a template for processing many entities, tied to components
  • IntervalEntitySystem – a simple system template, not tied to components, process periodically, based on world delta.
  • IntervalEntityProcessingSystem – a template that process entities periodically, based on world delta, tied to components.
  • ParallelEntityProcessingSystem – a template to leverage your multicore CPU for processing many entities, tied to components
  • ProcessingSystem – a template that process whichever logic you desire, without being tied to components
  • QueueProcessingSystem – instead of filter by components, this system process entities that are added to its public queue
  • HybridQueueProcessingSystem – process entities by queue and components
  • QueueProcessingSystemThreadSafe – process entities by a public static thread safe queue
  • FQueueSystemProcessingThreadSafe – process anything (not only entities) added to its public static thread safe queue
  • TagSystem – a simple system template, not tied to components, process a tagged entity
  • IntervalTagSystem – a simple system template, not tied to components, process a tagged entity periodically, based on world delta.
  • DelayedEntitySystem – a simple system template that starts process after a given time, based on world delta.
  • DelayedEntityProcessingSystem – a template that starts processing entities after a given time, based on world delta. Tied to components

And here is a system example, using Velocity and Transform components to create the Movement behavior:

//Add this attribute so the EntityWorld knows the systems it should execute, use the Layer to determine execution order
[Artemis.Attributes.ArtemisEntitySystem(ExecutionType = ExecutionType.UpdateSynchronous, Layer = 1)]
public class MovementSystem : EntityProcessingSystem {

    public MovementSystem() : base(Aspect.All(typeof(Transform), typeof(Velocity))) { }

    public override void Initialize() {}

    public override void Process(Entity e) {
        Velocity velocity = e.getComponent();
        float v = velocity.Speed;

        Transform transform = e.getComponent();

        float r = velocity.AngleAsRadians;

        float xn = transform.X + (TrigLUT.Cos(r) * v * world.Delta);
        float yn = transform.Y + (TrigLUT.Sin(r) * v * world.Delta);

        transform.SetLocation(xn, yn);
    }
}

On your game initialization, create a new EntityWorld and initialize it:

var world = new EntityWorld();
world.InitializeAll(true); // pass true/false to enable/disable DataAttributes on Systems

Update or Draw the World:

world.Update();
world.Draw(); // do this on a different loop, e.g: every 15 ms

And you are good to go. The Entity object has some intuitive methods like Delete(), GetComponent(), RemoveComponent(), which you can see in action on the example game.

Aspects

Aspects are used in the constructor of your entity systems to tell them which components they should be interested. At the moment we have three methods to build Aspects:

  • Aspect.All(params Type[] types) – Most of the time you will use this option, so the system processes entities which have all components of the Aspect.
  • Aspect.One(params Type[] types) – The system will process entities which have at least one of the components of the Aspect.
  • Aspect.Exclude(params Type[] types) – The system will not process entities which have at least one of the components of the Aspect.

You can also compose your Aspect utilizing these methods together, example:

public LogEnemySystem() : base(Aspect.All(typeof(Health)).One(typeof(Koopa),typeof(Goomba),typeof(Magikoopa)).exclude(typeof(Ghost))) {}

Extending Systems

It’s quite simple to extend the EntitySystem with your own logic, an example can be found here, which gives us less setup on systems which only uses Aspect.All(), example:

[Artemis.Attributes.ArtemisEntitySystem(ExecutionType = ExecutionType.UpdateSynchronous, Layer = 1)]
public class MovementSystem : EntityComponentProcessingSystem {
    public override void Process(Entity e,Transform transform, Velocity velocity) {
        float v = velocity.Speed;
        float r = velocity.AngleAsRadians;

        float xn = transform.X + (TrigLUT.Cos(r) * v * world.Delta);
        float yn = transform.Y + (TrigLUT.Sin(r) * v * world.Delta);

        transform.SetLocation(xn, yn);
    }
}

Templates

Create your entity templates to avoid manually creating and configuring entities:

[Artemis.Attributes.ArtemisEntityTemplate("BulletExplosion")]
public EnemyTemplate : Artemis.IEntityTemplate {
	public Entity BuildEntity(Entity e,EntityWorld entityWorld, params object[] args) {
		e.AddComponent(new Transform(200,400));
		e.AddComponent(new Velocity(2.4f,0.9f));
	}
}

Create your entities with the template applied:

var enemy = world.CreateEntityFromTemplate("BulletExplosion",array_of_parameters); // you can also use an alternative signature passing a custom unique id as the first parameter.
enemy.Refresh();

Blackboard

You can easily share common objects between systems using the blackboard, here is a XNA example, on the game initialization:

EntitySystem.BlackBoard.SetEntry("ContentManager", Content);
EntitySystem.BlackBoard.SetEntry("GraphicsDevice", GraphicsDevice);
EntitySystem.BlackBoard.SetEntry("SpriteBatch", spriteBatch);

Then you can retrieve the objects inside systems like this:

this.device = EntitySystem.BlackBoard.GetEntry("GraphicsDevice");
this.spriteBatch = EntitySystem.BlackBoard.GetEntry("SpriteBatch");
this.contentManager = EntitySystem.BlackBoard.GetEntry("ContentManager");

Games created with Artemis C#

Magnetic by Nature – by Tripleslash Studios. They also have a Kickstarter running for the game, support it!

Discussion, issues, suggestions

We have a forum section here.

 Use It !!!

,

  1. #1 by free android english game on 3 de abril de 2014 - 9:25 am

    Asking questions are genuinely nice thing if
    you are not understanding anything entirely, except this paragraph presents
    nice understanding even.

  2. #2 by google authorship program on 24 de agosto de 2014 - 4:41 am

    You actually make it appear really easy along with your presentation however I to find
    this topic to be really something that I think I would never understand.
    It seems too complicated and very broad for me. I am taking a look forward for
    your subsequent publish, I will attempt to get the hold of it!

  3. #3 by ผิวขาว on 22 de setembro de 2014 - 5:12 pm

    Hey There. I discovered your blog the use of msn. That
    is a very well written article. I will be sure to
    bookmark it and come back to read more of your useful information. Thanks for
    the post. I will certainly return.

  4. #4 by flash-jp.com on 12 de outubro de 2014 - 8:09 am

    Pretty! This was an extremely wonderful post.
    Many thanks for providing this info.

  5. #5 by จำหน่าย induction heater on 12 de novembro de 2014 - 5:36 pm

    A wire mesh was set up like a see-through wall, perhaps serving
    as some kind of antennae for pulling energy from the aether.
    Induction heating uses the key of electromagnetic induction that
    is a non contact heating process. However, no one enjoys waiting for hot water and jumping in the shower only to
    find that all the hot water has been used up.

  6. #6 by Lumagenex on 17 de dezembro de 2014 - 3:23 am

    I am really loving the theme/design օf your weblog.

    Do yoս ever run into any internet browser compatibility ƿroblems?
    A handful of my blog audience havе complained aboսt mʏ site
    not operating correctly іn Explorer but loοks great in Chrome.

    Do you have any tips to help fix this issue?

  7. #7 by Abigail Lewis on 18 de dezembro de 2014 - 8:15 pm

    wonderful usage of words in the writing, it actually did help when i was reading

  8. #8 by Mason Ramirez on 4 de janeiro de 2015 - 9:39 pm

    The communications engineering desk reference download post is absolutely the most effective i’ve
    read today.

  9. #9 by ferragamo wallet on 4 de janeiro de 2015 - 9:48 pm

    Zufaellig bin ich auf eure Seite gelandet und muss feststellen, dass mir
    diese vom Design und den Informationen richtig gut gefaellt.

    ferragamo wallet Ferragamo Tie Sale
    ferragamo ties discount Salvatore Ferragamo Reversible Belt
    salvatore ferragamo florence Salvatore Ferragamo Black Handbag
    ferragamo jackets Vintage Ferragamo Handbags
    http://09124.org/index.php?option=com_phocaguestbook&view=phocaguestbook&id=1&Itemid=20

  10. #10 by jogos de lutas on 8 de janeiro de 2015 - 8:02 pm

    It’s a pity you don’t hve a donate button! I’d without
    a doubt donate to this fantastic blog! I suuppose for now i’ll settle for book-marking
    and adding your RSS feed to my Google account. I look forward to
    fresh updates and will share tyis site with my Facebook group.

    Talk soon!

  11. #11 by Audrey Parker on 11 de janeiro de 2015 - 9:29 pm

    One of the better items i have seen this week.

  12. #12 by .VLY5nSuUfn8 on 20 de janeiro de 2015 - 8:54 am

    Corian counter surfaces are usually strikingly pleasing, nevertheless provided that they’re
    clean up in addition to shiny! It’s best to
    clean these together with delicate, healthy cleanup alternatives which means you don’t need
    to bother about detrimental their own floor as well as forgetting element residues.
    Adhere to this particular food a great simple and risk-free handmade corian cleanser.

  13. #13 by Henry Perry on 22 de janeiro de 2015 - 11:23 pm

    I’ve a question about the piece, where am i
    able to e-mail the writer?

  14. #14 by o que E bom pra espinha caseiro on 23 de janeiro de 2015 - 3:46 am

    nosso blog pode ser encontrado aqui (temporariamente:
    a minha filha é estudante página do blog) . o trabalho da acne cuidados da
    pele produtos para ajudar a normalizar a corte para evitar obstruções
    dos poros, matando o Propionibacterium acnes, e diminuir
    a inflamação. Sua pele pode ser o seu melhor trunfo enquanto você investir
    no direito as rotinas e cuidados com a pele produtos para o
    cuidado dos que.

  15. #15 by Matthew Stewart on 24 de janeiro de 2015 - 5:09 pm

    Saved like a favorite, wonderful site!

  16. #16 by Hannah Martinez on 24 de janeiro de 2015 - 10:17 pm

    bookmarked, terrific internet site!

  17. #17 by Natalie Ramirez on 26 de janeiro de 2015 - 1:19 am

    One of the better items i have seen in the week.

  18. #18 by Ethan Cruz on 27 de janeiro de 2015 - 7:09 am

    fantastic usage of words in the piece, it in reality
    did help when i was reading

  19. #19 by Info market Indonesia on 8 de fevereiro de 2015 - 7:20 pm

    This is a good tip particularly to those fresh to the blogosphere.
    Short but very accurate info… Thank you for sharing this one.
    A must read article!

  20. #20 by www.erova.com on 19 de fevereiro de 2015 - 12:01 am

    Thanks for another informative site. Where else could I am getting that kind of info written in such a
    perfect method? I have a project that I’m simply now working on, and I have been at the glance out for
    such info.

  21. #21 by Clyde on 25 de fevereiro de 2015 - 4:38 pm

    I’m excited to discover this site. I wanted to thank you for your time due to
    this fantastic read!! I definitely enjoyed every
    little bit of it aand I have youu book mawrked to
    checkk out new tings in your site.

  22. #22 by firmas de limpeza on 6 de março de 2015 - 12:24 am

    It’s difficult to find knowledgeable people about this
    topic, however, you seem like you know what you’re talking about!
    Thanks

  23. #23 by Modadamulher on 12 de maio de 2015 - 11:04 am

    If a facelift is used too much, it eventually will look sinister face display.
    You are most probably living another person’s life. Beauty salon in Abu Dhabi offer extensive beauty treatments to men and women.

  24. #24 by MixDeVendas on 20 de maio de 2015 - 3:38 am

    Food4Wealth is a new and popular guide that supposed to show
    you the way to grow healthy and organic food in an easy way.
    Laetrile is most abundant in the bitter almond and it’s also in many of the foods we tend not to eat these days like millet, macadamia nuts and buckwheat.
    Whenever metabolism improves then the system will work
    off additional pounds.

  25. #25 by Ashly on 24 de maio de 2015 - 1:00 am

    My brother recommended I would possibly like this website.
    He was once totally right. This submit actually made my day.
    You cann’t consider simply how much time I had spent for this info!
    Thank you!

  26. #26 by induction heater on 1 de junho de 2015 - 6:02 pm

    Timothy Thrapp, who founded and heads WITTS, is shown powering up the
    generator using a standard motor that is plugged into the grid.

    In air conditioners the evaporator is the main functioning parts since it produces
    the desired cooling effect. Staying svelte means an even better power-to-weight ratio which
    adds both acceleration and fuel economy. eval(ez_write_tag([[300,250],’brighthubengineering_com-medrectangle-3′]));
    .

  27. #27 by induction heater คืออะไร on 2 de junho de 2015 - 3:37 pm

    Furnaces with middle frequency are used for small applications.
    The induction heater is often overlooked, but replacing your old one can make a
    big difference in your home. Copper has many applications
    due to its properties of ductility, which permits it
    to be drawn into very fine wires; malleability allowing it be formed into various shapes,
    and conductivity. The metal part that makes its way into the
    magnetic area moves eddy power inside the part.

  28. #28 by content marketing strategy template on 2 de junho de 2015 - 4:26 pm

    On Sunday, June 7, the 69th annual Toony Awards shall be beamed dwell into houses world wide.

  29. #29 by ชุดคลุมท้องราคาถูก on 3 de junho de 2015 - 1:52 am

    If you are having difficulty finding maternity clothes in your own style, you can go a long way through pregnancy
    in regular shirts and leggings. However, you can enhance the
    elegance of your dress by using the right accessories to look more stylish at the party.
    When you try to get her attention all the time she will
    not see you in an attractive light and will probably pity
    you. Cheap maternity clothing is effective and does not swell your budget.

  30. #30 by induction heater คืออะไร on 3 de junho de 2015 - 1:15 pm

    People can experience fast heating, energy savings
    and high production rates benefits. In the past, a lengthy process that involved complex
    calculations, as well as empirical formulas and practical
    experience was required. In October 1971 while performing on a Madison Square
    Garden bill with other acts from the 1950s, he was booed off the stage by an audience who expected oldies.

    We spend almost one third of our life in bed and there is
    no need to have central heating on while you sleep.

  31. #31 by Free List Hack Review on 3 de junho de 2015 - 4:08 pm

    Price and administration accounting are instruments to allow management to take choices onn a day-to-day
    basis.

  32. #32 by vestida de mulher on 4 de junho de 2015 - 3:38 am

    Their wedding dress is one of the most special designer dresses which they will cherish all through their life.
    A sweater can even be added during the colder months.
    What many brides are considering for their wedding is a
    different style dress for each of their bridesmaids.

  33. #33 by แผ่นอะคริลิค ราคาเท่าไหร่ on 5 de junho de 2015 - 10:20 am

    This will likely ensure an outstanding fit and proper sealing around the
    opening, which means you will enjoy the most energy savings possible.
    After painting it with gray dry brush it with white paint but
    this time make sure it’s a very light dry brushing. When you purchase acrylic sheets you can appear for non-glare acrylic sheets
    that have a matte finish with reasonably tiny reduction of sharpness.

    Plastic sheet acrylic is also a beneficial option when you want to
    lower the glare from light.

  34. #34 by แผ่นอะคริลิค ทนความร้อน on 7 de junho de 2015 - 3:28 pm

    Cast – This acrylic type is more expensive but has higher quality.
    The frame provides a sturdy base for your paper mache mask.
    I do hope you have found this little ‘how-to’ guide
    useful. After the drawing is complete, have students use a tooth brush dipped
    in water or spray bottle to get their drawings wet, just until colors begin to run.

  35. #35 by https://twitter.com/N32Zany/status/608049596972081152 on 9 de junho de 2015 - 7:44 pm

    Ray’s large hit is the YouTube sequence Equals Three , which features him providing
    commentary on other viral movies.

  36. #36 by https://twitter.com/N32Zany/status/608051205441523712 on 9 de junho de 2015 - 10:30 pm

    AdSensxe Tip: Google and YouTube are critical about fraudulent
    cpicks (that price theiir advertisers money).

  37. #37 by แผ่นอะคริลิค ราคาถูก on 10 de junho de 2015 - 12:11 am

    Because of the difficulty of fixing heavier scratches, we strongly recommend you don’t scratch it.

    Most tattoo flash art are done in outline or stencil.
    Acrylic products can be used anywhere around the house since they’re very safe.
    Aside from its sheet form, you can also find various
    designs made out of acrylic plastic.

  38. #38 by อินดักชั่น ฮีตเตอร์ on 11 de junho de 2015 - 11:08 am

    Mouse is a computer pointing device which help users to operat on the
    computer desktop. The most common examples are a molded material consisting of iron powders
    in a compacted non-conductive binder, or lamination style concentrators.
    Read more of my Examiner articles about Fiesta here. All
    but the pilot and co-pilot were killed including: Nelson, his fianc.

  39. #39 by Dominic on 16 de junho de 2015 - 11:17 pm

    I’m just tooo lazy to always monitor whether or not campaigns are nonetheless operating and/or
    chase afteer replacements.

  40. #40 by Porter on 17 de junho de 2015 - 10:48 pm

    The Web has bred many unethical practices, like hacking, spamming and phishing.

  41. #41 by แผ่นอะคริลิค ขนาด on 20 de junho de 2015 - 9:16 am

    Cut both the black and gold chenille stems
    in half, save the halves for another project. In this case an extrusion unit is attached to the thermoforming unit and the both processes are done in one step.

    If your project design requires your cover to be cut to a custom size, using plexiglass for solar panels is likely
    to be a far cheaper option. Our notice boards are available in a range
    of styles and sizes, these notice boards can either be a standard size or custom made to fit your display requirements.

  42. #42 by business planning definition on 20 de junho de 2015 - 10:32 am

    Future Projections: Clarify the route wherein possession and administration plan to take the enterprise.

  43. #43 by Crazy 5RR Cash Download on 23 de junho de 2015 - 4:15 am

    It is one of the most popular unbiased small enterprise publications on the internet.

  44. #44 by Wilmer on 26 de junho de 2015 - 6:38 am

    If you write articles permit your affiliates to run these
    of their ezines or publish them on thesir websites with their affiliate URLs in your
    resource box.

  45. #45 by ulthera ยกกระชับหน้า on 7 de agosto de 2015 - 6:30 pm

    The average combined change in arm circumference for the LLLT treatment group was _2.

    If attempted on locations where the sagging is more pronounced,
    you will just be disappointed by the results no matter how many
    sessions you hold. but deep under the skin to the same tissue addressed in surgery.

    If you take pleasure in your botox final results, soon after quite a few months it will be time for a re-up in your therapy.

  46. #46 by ขายน้ำมันมะพร้าวสกัดเย็น on 27 de agosto de 2015 - 2:13 pm

    And it is not bitter at all as some olive oils are. Well, after having them taken cared of, my
    next dental visit six months later and after six months of brushing
    with organic coconut oil. Research says that Hemp Seed oil may be beneficial for hormonal balance, Hemp seed contains GLA thus it makes a suitable choice
    in PMS conditions. When applied topically, organic coconut oil helps with athlete’s foot, canker sores, herpes, genital warts, acne, and sore muscles.

  47. #47 by ขายเซรั่มปลูกคิ้ว real hair รีวิว on 9 de outubro de 2015 - 11:08 pm

    But, it is also true that there are a few prescription eyelash growth products that burn and sting, discolor the iris and blur the vision. Herbal growth enhancer products
    increase the blood flow and enable nutrients to go where they are needed.

    The gland will increase in an endeavor to create more TSH more if
    the body is low thyroid levels. As you see, tan is produced when the
    skin produces enough melanin that gives the skin its rosy or
    brownish color.

  48. #48 by nba 2k16 mt database on 6 de abril de 2016 - 10:59 pm

    Unbelievably individual pleasant website. Tremendous information available on few gos to.|

1 2 3 878
(não será publicado)