Scripting Bridge: Combining SBElementArrays - objective-c

According to Apple's documentation on Scripting Bridge performance, we should strive to use batch operations on SBElementArrays, since Apple event calls are expensive.
... whenever possible you should always use one of the “batch
operation” array methods instead of enumerating the array. These
methods avoid the inefficiency of enumeration because they send a
single Apple event rather than one Apple event per item in the array.
I'm using Scripting Bridge with the System Events application, and I'm able to get menu items from the menus successfully. It's much faster than the NSAppleScript method I was using previously.
What I'd like to do is combine together several SBElementArrays, each of which is holding menu items from different menus. The plan is to then run the batch operation once instead of doing it for each menu individually.
It seems to me like this shouldn't be that complicated, though obviously my knowledge in this area is limited at best. Unfortunately I'm running into serious errors.
First Attempt
If I attempt to create an empty SBElementArray element and then loop through the menu items adding each set of menuitems, like so:
SBElementArray* menuItemCombinedArray = [[SBElementArray alloc] init];
for (SystemEventsMenuBarItem* menu in menuBar.menus) {
menuItemCombinedArray = [[menuItemCombinedArray arrayByAddingObjectsFromArray:menu.menuItems] mutableCopy];
}
NSArray* menuItemNameArray = [menuItemCombinedArray arrayByApplyingSelector:#selector(name)];
I get an error saying that [SBElementArray init] should never be used, which is a bit odd since SBElementArray is a subclass of NSMutableArray.
Second Attempt
Next I tried a hackier way, where I created the SBElementArray separately for the first menu, then looped through the remaining menus and added those SBObjects one at a time, like so:
SBElementArray* menus = menuBar.menus;
SystemEventsMenuBar* firstMenu = menus.firstObject;
SBElementArray* menuItemCombinedArray = firstMenu.menuItems;
[menus removeObjectAtIndex:0];
for (SystemEventsMenuBarItem* menu in menus) {
SBElementArray* tempMenuItemsArray = menu.menuItems;
for (int i = 0; i < tempMenuItemsArray.count; i++) {
[menuItemCombinedArray addObject:[tempMenuItemsArray objectAtIndex:i]];
}
}
NSArray* menuItemNameArray = [menuItemCombinedArray arrayByApplyingSelector:#selector(name)];
But now I get a different error: [SBElementArray addObject:]: can't add an object that already exists.'
Summary
From what I've read searching around, it sounds like Scripting Bridge in general, and SBElementArray specifically, are kind of wonky. But Scripting Bridge has been much faster for me than NSAppleScript, much closer to what I'm aiming for. I think if I could get this optimization working I'd be in great shape.
Thanks in advance for any help!

SBElementArray is not an Array - it's a lot of smoke-n-mirrors BS disguising the otherwise simple fact that Apple event IPC is not OOP but RPC plus simple relational queries.
What you really have beneath all that SBElementArray dross is a single object specifier that describes a one-to-many relationship between 'objects' in the application's Apple Event Object Model, an idealized, virtual representation of the user's data presented in a programmatic user interface.
The application also defines various Apple event handlers for performing operations on its AEOM - creating, deleting, moving, duplicating, etc. - the idea being that you send a request to the app, e.g. duplicate (every track whose artist is "Bjork") to (playlist "Icelandic"), and the receiving handler figures out precisely how to carry out that operation for you.
How well this query-driven approach works in practice depends on how well the app's AEOM support is implemented: often the underlying Model layer implements collections as ordered Arrays rather than unordered Sets, and since you're basically performing set operations of the sort more commonly seen in RDBMSes, well, there's all sorts of opportunities for misorderings and other errors to creep in when moving array elements around in relation to one another. But the basic concept is not unsound (just a PITA to implement reliably); alas, the SB authors seem to think that "Relational Graphs Is Too Hard for Cocoa users" (which no doubt comes a big suprise to CoreData users), so try to hide it all beneath a stinky, incompetent ORM.
Thus there's absolutely no point trying to apply NS[Mutable]Array semantics to the problem as you're doing, because SBElementArrays are not local (or remote) arrays, but crippled obfuscated wrappers around AEOM queries. In other words, to understand why what you're doing doesn't work and how to do it so it does, you need to understand how AEOM actually works, how SB lies about how it works, and how SB translates its lies into [very limited] AEOM behaviors.
Thus, when you apply -[SBElementArray arrayByApplyingSelector:], it isn't actually performing array iteration at all; instead, it's constructing an object specifier of form |selector name| of |elements| of... and sending it to the application in a get event to resolve; the result being a list of values of the specified properties. Of course, this all turns out to be completely useless when you want to perform anything other than a simple get operation, e.g. set (rating of every track of playlist "Icelandic") to 100, because the SB API's too crippled and prejudiced to let you express this, even though it's a perfectly valid request.
...
TL;DR: It's a complete waste of time trying to do anything non-trivial in SB, because the harder you push it, the more its pseudo-OO fakery falls apart. The only [officially supported] way to do Apple events correctly is via AppleScript, and as you say using AS via NSAppleScript is an exercise in groin-punching that's barely less painful than SB (although partly that will be because you're no doubt doing it wrong, i.e. generating custom AS source code via string-mashing and compiling and executing it on the fly instead of calling parameterized handlers in precompiled .scpt files loaded from your app bundle).
Fortunately, 10.6 introduced the AppleScript-ObjC bridge which, while not without some shortcomings of its own, is by far the easiest and quickest way to integrate AS and ObjC code as it allows you to define AppleScript script objects that appear to your ObjC code almost as if they were native Cocoa classes and instances. That would be my recommended approach to you, and forget about SB for anything but trivial tasks (or just forget it altogether and stick with AS, which may be naff but at least it's mostly understood, less dishonest naff).

Related

How to Instance an object in Godot?

So I basically have some fair knowledge of Opengl 4.0. In OpenGL you can render the same object at many places. This is a technique called Instancing. This saves up some CPU calls or something.
I wanted to do this in Godot. So I looked up in the docs and it basically just tells me to duplicate an object. But I think this does not save the CPU calls to the GPU, like how Instancing does (please let me know if I'm wrong about this).
Plus I cannot have all the nodes beforehand. Because the number of times I need to render the object(at different places) is determined during runtime and can change.
Is there a solution to this?
Any help would be appreciated.
Thank you
Instancing can be thought of as making copies of an object from a blueprint. The reason it saves memory and draw calls is that essentially, only the "blueprint" must be kept in memory. The recommended way that Godot addresses this (as per the documentation) is through (packed) scenes.
To do this, create the object as it's own scene - remember that you can right click on the root node of a scene (even an empty one) and change the type to whatever you want. Once you have the object set up the way you like, save it as it's own scene (ex: myInstance.tscn).
From there, you can call upon the instance from your main scene (or whatever scene you need it in). To do this you need to do a couple of things:
First, create a variable for your instance in the script you want to call it from by declaring something like onready var instancedObject = preload("res://myInstance.tscn"). (Using whatever path you used for the scene).
From there, you call the variable from whatever function you need by writing something like: var myObject = instancedObject.instance()
You then must add the instance to the current scene with add_child(myObject)
After this, you can (optionally) specify things like transforms and rotations to determine where the instance gets put (Ex: myObject.transform.origin = Vector3(0,10,0) - For 3D, or myObject.position = Vector2(10,0) for 2D)
Alternatively, you can initialize and instance the object at the same time by writing onready var instancedObject = preload(res://myInstance.tscn).instance(), and then adding it in functions by using add_child(instancedObject), however although it requires fewer steps, there are limitations to doing it this way, and I personally have had much more success using the first approach.
If, however, you are looking to instance multiple thousands of objects (or more) in the same scene, I recommend using Calinou's answer and using a MultiMeshInstance. However, one of the limitations of the MultiMeshInstance is that it uses an all or nothing approach to drawing, meaning all instances will either be all drawn at once, or not drawn at all. There is no in-between. This could be good or bad depending on what you need it for.
Hope this helps.
Instancing in Godot is handled using the MultiMeshInstance node. It's the instanced counterpart to MeshInstance. See Optimization using MultiMeshes in the documentation for more information.
Keep in mind MultiMeshes aren't suited if you need to move the objects in different directions every frame (although you can can achieve this by using INSTANCE_ID in a shader shared among all instances). MultiMeshInstance lets you change how many instances are visible by setting its visible_instance_count property.

NSManagedObject as store with continuous analysis of raw data

This is similar to a question I asked before, but now that I've come much further along I still have a question about "proper" subclassing of NSManagedObject as I was told last night that it's a "bad idea" to put lots of non-persisted properties and ivars inside one. Currently I have TONS of code inside my NSManagedObject, and Apple's docs don't really address the "rightness" of that. FYI: the code works, but I'm asking if there are pitfalls ahead, or if there are obvious improvements to doing it another way.
My "object" is a continuously growing array of incoming data, the properties/ivars that track the progress of the analysis of that data, and the processed data (output). All of this is stored in memory because it grows huge, very quickly, and would not be possible to re-generate/re-analyze continuously. The NSManagedObject properties that are actually persisted are just the raw data (regularly saved, as Core Data doesn't support NSMutableData), a few basic properties and 2 relationships to other NSManagedObjects (1 being a user, the other being a set of snapshots of the data). Only one object is being recorded to at any one time, although dozens can be opened for viewing (which may involve further processing at any time).
It's not possible to have the object that inserts the entity (data manager that manages Core Data) have all of the processing logic/variables inside it, as each object necessitates at least a handful of arrays/properties that are used as intermediaries and tracking values for the analysis. And I, personally, think that it sounds silly to create two objects for each object that is being used (the NSManagedObject that is the store, and another object that is the processing/temp store).
Basically, all of the examples I can find using NSManagedObjects have super simple objects that are things like coordinates, address book entries, pictures: stuff that is basically static. In that case I can see having all of the logic that creates/modifies them outside the object. However, my case is not that simple and I have yet to come up with an alternative that doesn't involve duplication.
Any suggestions would be appreciated.
You might use a 'wrapper', that is to say a class with a reference to one of your managed object instances, this wrapper would contain your algorithms and your non persisted algorithms.

Getting the world's contactListener in Box2D

I'm writing a game for Mac OS using cocos2D and Box2D. I've added a b2ContactListener subclass to my world as follows:
contactListener = new ContactListener();
world->SetContactListener(contactListener);
This works perfectly, but I am unsure of the best/accepted way to access the contact listener from other classes that don't currently have a direct reference to the contact listener.
I know I can pass a reference to other classes that need it, but what I was wondering is if there is a better way. More specifically, although I can't find a method to do this, is there some equivalent of this:
world->GetContactListener();
in Box2D?
The reason I am trying to do this is simply because I would prefer to move some game logic (i.e. whether a body is able to jump based on information from the contact listener) to the relevant classes themselves, rather than putting everything in the main gameplay class.
Thanks!
A contact listener just serves as an entry point for the four functions BeginContact, EndContact, PreSolve and PostSolve. Typically it has no member variables, so there is no reason to get it, because there is nothing to get from it.
When one of these functions is called during a world Step, you can make a note of which two things touched/stopped touching etc, but you should not change anything in the world right away, until the time step is complete.
I think the crux of this question is the method used to 'make a note' of which things touched, but that's really up to you and depends on what kind of information you need. For example if you're only interested in BeginContact, then the absolute simplest way might be to just store which two fixtures touched as a list of pairs:
std::vector< std::pair<b2Fixture*, b2Fixture*> > thingsThatTouched;
//in BeginContact
thingsThatTouched.push_back( make_pair(contact->GetFixtureA(), contact->GetFixtureB()) );
//after the time step
for (int i = 0; i < thingsThatTouched.size(); i++) {
b2Fixture* fixtureA = thingsThatTouched[i].first;
b2Fixture* fixtureB = thingsThatTouched[i].second;
// ... do something clever ...
}
thingsThatTouched.clear(); //important!!
For this to work you'll need to make the thingsThatTouched list visible from the contact listener function, so it could either be a global variable, or you could set a pointer to it in the contact listener class, or maybe have a global function that returns a pointer to the list.
If you need to keep track of more information such as what things stopped touching, or do something after the time step based on how hard things impacted when they touched etc, it will take a bit more work and becomes more specific. You might find these tutorials useful:
This one uses BeginContact/EndContact to update a list of which other things a body is touching, and uses it to decide if a player can jump at any given time:
http://www.iforce2d.net/b2dtut/jumpability
This one uses a similar method to look at what type of surfaces are currently under a car tire, to decide how much friction the surface has:
http://www.iforce2d.net/b2dtut/top-down-car
This one uses PreSolve to decide whether two bodies (arrow and target) should stick together when they collide, based on the speed of the impact. The actual 'sticking together' processing is done after the time step finishes:
http://www.iforce2d.net/b2dtut/sticky-projectiles
I think you simply can call GetContactList and then process all the contacts using iterator if you need to do it in some other place

Communication in component-based game engine

For a 2D game I'm making (for Android) I'm using a component-based system where a GameObject holds several GameComponent objects. GameComponents can be things such as input components, rendering components, bullet emitting components, and so on. Currently, GameComponents have a reference to the object that owns them and can modify it, but the GameObject itself just has a list of components and it doesn't care what the components are as long as they can be updated when the object is updated.
Sometimes a component has some information which the GameObject needs to know. For example, for collision detection a GameObject registers itself with the collision detection subsystem to be notified when it collides with another object. The collision detection subsystem needs to know the object's bounding box. I store x and y in the object directly (because it is used by several components), but width and height are only known to the rendering component which holds the object's bitmap. I would like to have a method getBoundingBox or getWidth in the GameObject that gets that information. Or in general, I want to send some information from a component to the object. However, in my current design the GameObject doesn't know what specific components it has in the list.
I can think of several ways to solve this problem:
Instead of having a completely generic list of components, I can let the GameObject have specific field for some of the important components. For example, it can have a member variable called renderingComponent; whenever I need to get the width of the object I just use renderingComponent.getWidth(). This solution still allows for generic list of components but it treats some of them differently, and I'm afraid I'll end up having several exceptional fields as more components need to be queried. Some objects don't even have rendering components.
Have the required information as members of the GameObject but allow the components to update it. So an object has a width and a height which are 0 or -1 by default, but a rendering component can set them to the correct values in its update loop. This feels like a hack and I might end up pushing many things to the GameObject class for convenience even if not all objects need them.
Have components implement an interface that indicates what type of information they can be queried for. For example, a rendering component would implement the HasSize interface which includes methods such as getWidth and getHeight. When the GameObject needs the width, it loops over its components checking if they implement the HasSize interface (using the instanceof keyword in Java, or is in C#). This seems like a more generic solution, one disadvantage is that searching for the component might take some time (but then, most objects have 3 or 4 components only).
This question isn't about a specific problem. It comes up often in my design and I was wondering what's the best way to handle it. Performance is somewhat important since this is a game, but the number of components per object is generally small (the maximum is 8).
The short version
In a component based system for a game, what is the best way to pass information from the components to the object while keeping the design generic?
We get variations on this question three or four times a week on GameDev.net (where the gameobject is typically called an 'entity') and so far there's no consensus on the best approach. Several different approaches have been shown to be workable however so I wouldn't worry about it too much.
However, usually the problems regard communicating between components. Rarely do people worry about getting information from a component to the entity - if an entity knows what information it needs, then presumably it knows exactly what type of component it needs to access and which property or method it needs to call on that component to get the data. if you need to be reactive rather than active, then register callbacks or have an observer pattern set up with the components to let the entity know when something in the component has changed, and read the value at that point.
Completely generic components are largely useless: they need to provide some sort of known interface otherwise there's little point them existing. Otherwise you may as well just have a large associative array of untyped values and be done with it. In Java, Python, C#, and other slightly-higher-level languages than C++ you can use reflection to give you a more generic way of using specific subclasses without having to encode type and interface information into the components themselves.
As for communication:
Some people are making assumptions that an entity will always contain a known set of component types (where each instance is one of several possible subclasses) and therefore can just grab a direct reference to the other component and read/write via its public interface.
Some people are using publish/subscribe, signals/slots, etc., to create arbitrary connections between components. This seems a bit more flexible but ultimately you still need something with knowledge of these implicit dependencies. (And if this is known at compile time, why not just use the previous approach?)
Or, you can put all shared data in the entity itself and use that as a shared communication area (tenuously related to the blackboard system in AI) that each of the components can read and write to. This usually requires some robustness in the face of certain properties not existing when you expected them to. It also doesn't lend itself to parallelism, although I doubt that's a massive concern on a small embedded system...?
Finally, some people have systems where the entity doesn't exist at all. The components live within their subsystems and the only notion of an entity is an ID value in certain components - if a Rendering component (within the Rendering system) and a Player component (within the Players system) have the same ID, then you can assume the former handles the drawing of the latter. But there isn't any single object that aggregates either of those components.
Like others have said, there's no always right answer here. Different games will lend themselves towards different solutions. If you're building a big complex game with lots of different kinds of entities, a more decoupled generic architecture with some kind of abstract messaging between components may be worth the effort for the maintainability you get. For a simpler game with similar entities, it may make the most sense to just push all of that state up into GameObject.
For your specific scenario where you need to store the bounding box somewhere and only the collision component cares about it, I would:
Store it in the collision component itself.
Make the collision detection code work with the components directly.
So, instead of having the collision engine iterate through a collection of GameObjects to resolve the interaction, have it iterate directly through a collection of CollisionComponents. Once a collision has occurred, it will be up to the component to push that up to its parent GameObject.
This gives you a couple of benefits:
Leaves collision-specific state out of GameObject.
Spares you from iterating over GameObjects that don't have collision components. (If you have a lot of non-interactive objects like visual effects and decoration, this can save a decent number of cycles.)
Spares you from burning cycles walking between the object and its component. If you iterate through the objects then do getCollisionComponent() on each one, that pointer-following can cause a cache miss. Doing that for every frame for every object can burn a lot of CPU.
If you're interested I have more on this pattern here, although it looks like you already understand most of what's in that chapter.
Use an "event bus". (note that you probably can't use the code as is but it should give you the basic idea).
Basically, create a central resource where every object can register itself as a listener and say "If X happens, I want to know". When something happens in the game, the responsible object can simply send an event X to the event bus and all interesting parties will notice.
[EDIT] For a more detailed discussion, see message passing (thanks to snk_kid for pointing this out).
One approach is to initialize a container of components. Each component can provide a service and may also require services from other components. Depending on your programming language and environment you have to come up with a method for providing this information.
In its simplest form you have one-to-one connections between components, but you will also need one-to-many connections. E.g. the CollectionDetector will have a list of components implementing IBoundingBox.
During initialization the container will wire up connections between components, and during run-time there will be no additional cost.
This is close to you solution 3), expect the connections between components are wired only once and are not checked at every iteration of the game loop.
The Managed Extensibility Framework for .NET is a nice solution to this problem. I realize that you intend to develop on Android, but you may still get some inspiration from this framework.

Objective-C wrapper API design methodology

I know there's no one answer to this question, but I'd like to get people's thoughts on how they would approach the situation.
I'm writing an Objective-C wrapper to a C library. My goals are:
1) The wrapper use Objective-C objects. For example, if the C API defines a parameter such as char *name, the Objective-C API should use name:(NSString *).
2) The client using the Objective-C wrapper should not have to have knowledge of the inner-workings of the C library.
Speed is not really any issue.
That's all easy with simple parameters. It's certainly no problem to take in an NSString and convert it to a C string to pass it to the C library.
My indecision comes in when complex structures are involved.
Let's say you have:
struct flow
{
long direction;
long speed;
long disruption;
long start;
long stop;
} flow_t;
And then your C API call is:
void setFlows(flow_t inFlows[4]);
So, some of the choices are:
1) expose the flow_t structure to the client and have the Objective-C API take an array of those structures
2) build an NSArray of four NSDictionaries containing the properties and pass that as a parameter
3) create an NSArray of four "Flow" objects containing the structure's properties and pass that as a parameter
My analysis of the approaches:
Approach 1: Easiest. However, it doesn't meet the design goals
Approach 2: For some reason, this seems to me to be the most "Objective-C" way of doing it. However, each element of the NSDictionary would have to be wrapped in an NSNumber. Now it seems like we're doing an awful lot just to pass the equivalent of a struct.
Approach 3: Seems the cleanest to me from an object-oriented standpoint and the extra encapsulation could come in handy later. However, like #2, it now seems like we're doing an awful lot (creating an array, creating and initializing objects) just to pass a struct.
So, the question is, how would you approach this situation? Are there other choices I'm not considering? Are there additional advantages or disadvantages to the approaches I've presented that I'm not considering?
I think that approach 3 would be the preferred way to do things. When you wrap a library you'll want to create wrappers around any object or structure that the user is expected to deal with.
If you wrap everything, then you are free to change the internal workings of your classes at a later date without affecting the interfaces that your users have become accustomed to. For example, in the future you may realize that you'd like to add some type of error checking or correction... maybe setting a stop that is earlier than the start causes some calculation errors, you could change the stop method in your Flow wrapper to set start equal to stop if stop is less than start (I admit, that's a really bad example).
I'd stick with approach 3. You're "just passing a struct" now, but the Flow object might expand more in the future. You say speed is not an issue and so I'd imagine memory consumption isn't either, or you would be sticking with C anyway.
My answer is not what you were asking, but it is still how I "would approach the situation".
The first question I would ask is, "what value does this wrapper add?" If the answer is, "to use Objective-C syntax" then the answer is "don't change a thing, use the library as-is because C is Objective-C syntax."
I don't know which library you are wrapping, so I'll use SQLite for an off the top of my head example. Using a layered approach, I would do something like this:
A) High level objects (Order, Customer, Vendor...)
B) Base class (Record)
C) SQLite
So the base class is written to call SQLite directly then the other classes work as regular Objective-C classes.
This is apposed to:
1) High level objects (Order, Customer, Vendor...)
2) Base class (Record)
3) SQLite Wrapper (Objective-C)
4) SQLite
The same application is created but there is extra work creating, maintaining and debugging level 3 with very little to show for it.
In the first version, layer B wrapped SQLite so nothing above it called SQLite directly AND it didn't try to provide all of SQLite functionality. It just provides the functionality that layer A needs and uses SQLite to achieve what is needed. It 'wraps' SQLite but in a more application specific manner. The same Record class could be reused in another application later and extended to meet the needs of both applications at that time.
Since Objective-C uses structures, why not leave it as a struct like NSRect?