NPC update or thread

@harton said:
Ok, thank you all for the info. I have to read the pdf and study more about entity systems, including the link from "t-machine".

Empire Phoenix, are you saying that when I was creating the executor I should do?
[java]ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);[/java]
I think don't undestand.

Reading about appstates I've seen that the BulletAppState class starts its own executor...
Line 70:
[java]private boolean startPhysicsOnExecutor() {
if (executor != null) {
executor.shutdown();
}
executor = new ScheduledThreadPoolExecutor(1);
[/java]
Is it a good practice? Starts an executor for every custom state class you have?


It depends, for AI threadpoool I would just make sure that it cannot block the render thread. (eg 4 path searches on a quadcore would reduce framerate since no core remains free)

And it is that I want to avoid XD



I’m having really troubles to understand how to encode an Entity System and I’m not sure if it is the best way. I’m trying to use the jME model with AppStates and Controls but I don’t have idea how it works. I’ve reading the documentation again and again, the java examples attached and the infernal RTS example and now I don’t know who am I.



I’m going to try to explain. I think states is a way to encode different phases of an application, menu, game, etc. Different update method to each phase against “if else” and similar workaround. I think is very useful but when I have to transfer this solution to a npc I only can think in AI states similar to the examples of the document linked by @EmpirePhoenix.



Example:

  • idle state
  • warning state (the npc is alerted by a sound or something)
  • alert state (the npc is seeing the player and is searching the best approach)
  • etc

    Practically all the states require at some point call the pathfinding method. Maybe I should include a pathfinding transitory state and pass the results. I’m very noob now but I think the best approach is the traditional with OOP.



    PD: My english sucks. I don’t mind rewrite something if this is not understood.

Write a generic pathfinding class that all it does is know how to pathfind.



Potentially write a pathfinding interface and then you could have a few different implementations for different NPCs (for example some might use full A*, others might just head blindly in the right direction).



Pathfinding is a separate problem. AI decides when to pathfind and where to…they don’t care how that is implemented.

Just random hints…



AppStates are used to “extend” the application without actually subclassing it. It’s composition instead of inheritance… and then the nice thing is that they can also be swapped in and out. So you can use it for application “modes” or you can use it for global functionality. Mythruna has about a dozen or more app states with 4 or 5 always active.



Controls are used to “extend” a Spatial without actually subclassing Spatial. They can be used to add functionality to a spatial and like states they can be swapped in and out at runtime… so similarly they can be used to change the “mode” of a spatial.



Many entity system examples spend a lot of time codifying the “system” part. But this is unnecessary. An entity system basically consists of entity IDs, components, and a way of getting entities that have certain components. Any code that uses the entities+components is a “system”. In JME, systems are implemented as app states or controls as needed. Every update pass, they grab some entities and do some stuff.



“Entity systems” is a hard topic to understand and dangerous when poorly understood. That is its one major down side.

1 Like

@pspeed:

I also thought that I not very clear about Entity System.



Also I really dont know how to escape from the idea of Entity System is a bad no, not really good design pattern.



As in the T-Machine post, he did metion the good of Entity System is to devide thing into smaller things to some how have a “Manager” to roll several “type of things” at once time. Yes



In theory, it a really good example of “not classify at all” but tell me in the end what is “type of things”

is it == class???



Now, not talking about how good my life can be with an Entity System, I just put here few things should be pretty damn hard to do with an Entity System in my hand:


Every in-game item has multiple facets, or aspects, that explain what it is and how it interacts with the world. A bicycle, for instance, is:

Made of metal
Can be used by a human
A means of transportation
Something that can be bought and sold
A popular birthday present
Man-made
At this point, please note: OOP does not have this concept of multiple aspects; it hard-codes all the aspects into one glob, and declares that the set of behaviours and values of data to be the single-aspected Class of an Object.



1) How can I find a criteria to divide things into Component.
As in OOP, classify is divide but as T-Machine said, it also link things together, and mixed logic, which acording to the article has a lot of bad effects for a MMORPG game and a real-time game.
But tell me is it always ovibous to divide things? No link at all, really..........
I think he just put "batch processing" in a high priority place, and said it 's the only algorithm for all real time game! Which I can not agree.

2) Components are just data but if your "real" data (models, asset, texture, ...) is bad orginized , and various type, and you have to work to transform "real" data to Components then Entity System is bad!!

3) Let think about how managers in an Entity system doing work in piece of information that a component give them.Because component don't think, they are data. So we must have manager to deal with them.

Eg: manager for Renderable. But there are
- textured model, which link to texture.
- and not textured model, not link to texture
- Also, there is Skybox, which in other bucket... so on

The component has to be separated, because they should know nothing about the other.
Then the manager have to separated too. So we have a lot of managers.
Let think about of a social with many cops, and cops have to know everythings about the people by "how familiar they look and behave".
It's bad because the system has to make all the work be cause it's citizen don't know anything.
Yes, in OOP, Object not really just a paper to display information, but its self a independent things to solve its own problem. So a piece of data and a piece of logic, then other solve the link and the interactive between thems.
=====================================================================================
"Some-how" same thing which "so-call" evolution of J2EE (Spring?), in which a service know everything and handle a lot of "easy to read and plain data" bean.

Now, I think a lot of web developers sometime want their bean to some how know each other behavior, not to route all the information and processing to service and let it take care. Why? Because web != large scale , it can be really small too, involve a lot of technique just for 2 reasons:
absolute 100% decoupling and just have to learn to config your data ( another 100% hard work)
In the end it's not that fasinated idea. Decoupling in 85% may work better and a lot easier to understand and to maintain. but 85% is still in OOP.

@harton : As read throgh the post I think you just start with JME and want to know a good pattern to implement a RPG game. Now I not 100% I can offer you one but I'm working on a framework for JME game (based on the work of other contributors and MonkeyZone) for easy extend to several of game genre (including RPG) .
You can check it here : http://hub.jmonkeyengine.org/groups/free-announcements/forum/topic/rpg-game-making-tutorials-series-by-atomix/

As in the Atom framework, there are several kind of State and they are in different level so dont be coffusion one with the other:
Please remember that the most important idea to divide and application into state is to some-how split it into phrase by the different of action, behavior in that phrase. So the State has to be pretty contrast with another!

An AppState (which is official JME AppState class) combine some actions in Application phrases (Start,Loading,Menu,End) to one unit. So without any knowledge of how the game should be (RPG or FPS ...), an Appliaction should pretty sure have those States.
An GameState (only in Atom) combine Game actions into state, it depend a lot in what gameplay, which game genre of the game. Say : Fighting_GameState, InDialogue_GameState. And it control every action which happen in that state:
Exploring: pathFinding, enemyApproach,
Fighting : there are explosion, particle
InDialogure: cinematic, character facial, ...
In Atom framework, NPC and character has state two if we using FSM (Finite state machine) to simulate character AI. Other technique can be use are Scripting in Groovy and DecisionTree. So for a specific game character, there are some common State and some special States:
RunState, animation="Run", speed ="10"
WalkState, animation="Walk",speed ="5"
IdleState, animation="Idle",speed="0"
DieState, animation="Die",speed="0" -> FSM finished.

As you can see we divide the logic into several level and then in one level, several separated block to easy to write, read and maintain. One more thing is : State is the behavior of the object, an object need to receive a Trigger or an Event from the System to notify in to change or to "think" from step to step.

So let make it short, devide you State in to level, and also make an EventSystem.

@harton :

Forgot to mention that in Atom, there is a EntitySystem too which I using Spartan framework but It’s not 100% complete arcording to the specification in T-Machine blog. But it using Apache Cayene to stir up some Relation Mapping into a JME3 game and maybe it fun to watch.



Now I’m trying to make a whole thing work by cleaning and writing comments, so I’m not put in in SVN yet, the current SVN, it the old code, work but no Atom separated yet! It take time but if you want an ready to run example, I can upload it to mediafire or somewhere else.

Or in short, its all about what you need, and how you feel comfortable with it.

(Also you will probably refactor almoste 100% of your code comletly as the project grows)

We will probably at some point introduce a base entity system in jme including documentation and examples but only when we know how we will create and apply it properly :slight_smile: The core devs are pretty much on one page about entity systems themselves. Each of us had to digest the idea as well first and had to implement his own system to try around with, when I first introduced it to @pspeed he was slightly dismissive first (maybe also because I wasn’t explaining it right because I was new to it as well) but he also very quickly started to adapt it in mythruna when it “clicked”.



I think the key in understanding it is that the entity system itself is basically nothing but a data storage and messaging system. Use it everywhere where you normally would…

…store general data and states of something

…get data from one part of the code to another

…use flags

…use callbacks

…do checks on states

…create connections between things

…decouple threaded access on things

1 Like

Thank all for your help.



I’ve found an example very clean with AppStates and Controls. It’s easier than I was thinking. I just finish to write a tower defense game in LUA and this code is very similar that I have. I think that I can now try to implements a litle game with npc AI with this system. I’m not trying to make an RPG, too hard for me now. When I have done a scratch version I will post it for your opinions and corrections/optimizations.



I still have to learn a lot…

I still have to learn a lot…



That will never end, you are basically just going down the rabbit hole further and further.

1 Like
@atomix said:
@pspeed:
I also thought that I not very clear about Entity System.


I really wanted to do a detailed point by point response to this but: a) this thread isn't really the place, b) I technically don't have the time, and c) there seems to be no common ground as your perceptions are pretty far skewed so far. The hardest thing is to completely forget OOP for a minute when thinking about an entity system. So I will attempt to skew back the other direction a little... maybe there is then common ground for some future post in its own thread or something.

OOP has a lot of problems with classification. Does a WoodenDoor extend Door or does it extend WoodBlock or does it extend Openable? and so on. In an EntitySystem, a door would have components based on the systems. There is no real object classification as the components are entirely determined by what the system needs.

Some system that wants to open/close doors could just care about entities with a Position component and an OpenOrClosed component.

A fire spreading system might care about entities with a Position component and a Material(Wood) component.

A rendering system only cares about a Position component and some ModelId or ModelType component.

A map rendering system only cares about Position and Label... and so on.

The systems lead the way on what components you will need. The only time any concept of entity "class" every comes into it is during creation. And even the components that an entity starts with can be defined in the entity system to be 100% data driven.

Your bicycle example is the perfect example of the dangers of OOP because you are already thinking about the bicycle more than how you are using it... and you are already tightly coupling all of those properties and actions together. For example "popular birthday present" and "man made" might be interesting qualities of a real bicycle but they are meaningless to the application if no code ever needs them. "Made of metal" and "rideable" are concepts that are too important on their own to be locked up inside just a bicycle. It's extremely likely that there will be other metal objects and other rideable objects... and they may have nothing to do with a bicycle.

and if we modified the bicycle example to instead use an Entity System... we have none of these issues. Plus, we automatically get use of a "magnetic" or "electricity" system if it exists and with just the change of a Material component we can have wooden bicycle that automatically gets burned like any other wooden object.

The single hardest part about entity systems is dropping everything you've learned about OOP and starting over. OOP still has its place in the application but the entity system isn't that place.
1 Like

Many of tht could be done with a strict oop system as well. Just with tons of interfaces. Like interface burnable, interface useable, interface vehicle. Thw logic itself is mostly in manager classes, and he interfaces only offer data to use, like interface vehicle offers me how many seats and where are they positioned relative to the entity. ect.

@pspeed:

I agree that if the interest in Entity System topic rising, it should have its own topic. And I may start one after I back to read more clearly about it. Thank you for giving valuable information!

@EmpirePhoenix said:
Many of tht could be done with a strict oop system as well. Just with tons of interfaces. Like interface burnable, interface useable, interface vehicle. Thw logic itself is mostly in manager classes, and he interfaces only offer data to use, like interface vehicle offers me how many seats and where are they positioned relative to the entity. ect.


Sure, but then every new concept you add and you have to touch every class that needs that concept... even though it's only really the manager class doing the work. There are ways to get some of the composition benefits using OOP but it becomes painful and unwieldy after too many things are added. JME's control model is pretty nice until you find yourself adding 15 random controls to something.

The off shoot of the flexibility of an ES is that it can be entirely data driven. This is nice for networked games where you can decide the orc chieftains need some special ability and so just add a component somewhere. In classic OOP, something like this has to be specifically supported where it's pretty much free in an ES.

I like an ES because it lets me code up things rapidly. Bootstrap the ES and I can add systems and components at will, deleting old stuff when it becomes obsolete, adding new stuff as I think of it. The untouched systems just keep humming along and all of my data is still 100% compatible with additions because no existing class data really changed.

I’ve started the code for the npc with AppStates and Controls. I think that it is the best way now.

I’m using Otto example model and I’m looking the TestWalkingChar example to help me. In this example all is controlled on Main class and I want split it. I’ve created a AIControl class for pathfinding and behaviour, and I’m confused, thinking the best way to face this…


  • I want a NPC with CharacterControl for the movement, etc, I think is very useful.
  • I want NPC animations
  • I want NPC AI with my control class



    I have three posible solutions:


  1. The AIControl class implements AnimControl and I use this AI class to control the movement (CharacterControl) and animations (AnimControl)
  2. My AIControl class derives from CharacterControl and implements AnimControl.
  3. Create an AIAppState for manage all this, this AppState runs at the same time that “MainAppState” and an UI AppState.



    I’m feeling all this solutions are crap but I’m very noob right now.



    I’m thinking that the best place to pathfinding code will be a static class. What do you think about that?



    PD: Can I use the java way to make threads with jME3?

You can use java threads…however you need to be careful when those threads and the rendering thread interact…make sure you always enqueue results back onto the rendering thread before applying changes.

I’ve been reading some post and I noticed that you are saying about issues between render thread and “custom” threads but now I’m not have idea about you are talking . Maybe I’ve not seached very well but where can I read something about it? I don’t understand very well the multithread document. If you don’t create any aditional thread how many threads starts jME3? I’ve seen that bulletAppState starts one.

If you are using bullet that starts a thread. Other than that everything happens in the render thread JME only has that one thread.



If you create your own threads that is fine but you cannot change the scene graph except from inside the render thread. So from your custom thread you do app.enqueue() and make the change from the enqueued callable which gets called on the render thread.



Please make sure you read this and understand it:

https://wiki.jmonkeyengine.org/legacy/doku.php/jme3:advanced:multithreading



If you don’t understand any terms then look them up etc but you really need to understand multi threading in general and this in particular before you proceed.

1 Like

Ah! Ok, ok. I know what you are saying. I mustn’t “make cubes” or init new spatials, set textures etc on the new thread without syncronize the results with the main process. Am I right?



I have no idea how I would need init new spatials in other thread, it seems for advanced user. I’m only want this thread for pathfinding and other posible operations.



That is the document I’ve read again and again but I am having problems to place this code in the correct place.



I understand uses of the future object and the utility of include on update loop. My doubt is here:

[java]Vector3f location = application.enqueue(new Callable<Vector3f>() {

public Vector3f call() throws Exception {

//we clone the location so we can use the variable safely on our thread

return mySpatial.getLocalTranslation().clone();

}

}).get();[/java]

I think is necesary clone the object to no interact with the render thread, I understand that Vector3f location contains now a local version of mySpatial.getLocalTranslation() and I have to do the same with every information that comes to render thread, example:

[java]

Vector3f location = application.enqueue(new Callable<Vector3f>() {

public Vector3f call() throws Exception {

//we clone the location so we can use the variable safely on our thread

return mySpatial.getLocalTranslation().clone();

}

}).get();



Quaternion rotation = application.enqueue(new Callable<Quaternion >() {

public Quaternion call() throws Exception {

return mySpatial.getLocalRotation().clone();

}

}).get();

[/java]



Or…



[java]

Spatial spt = application.enqueue(new Callable<Spatial>() {

public Spatial call() throws Exception {

return mySpatial.clone();

}

}).get();



Vector3f location = spt.getLocalTranslation();

Quaternion rotation = spt.getLocalRotation();

[/java]



Am I writting nonsense?

Yeah the first mostly make sense, ( I would use a Data Transfer Object(google) tho, where I would put all needed information into, so I dont neeed to use multiple Callables.

(Also in the opposite direction for setters you need to do something similar.)



To the object creation, only modification of the scene graph are not allowed, you can problemlesse create a hughe node Structures load textures on that in a side thread, you just have to enqueue the attach to the live Scene.

1 Like