melonJS icon indicating copy to clipboard operation
melonJS copied to clipboard

Anchor point always 0.5/0.5 even if defined

Open agmcleod opened this issue 13 years ago • 41 comments

https://github.com/melonjs/melonJS/blob/master/src/renderable/base.js#L136

Should that not be in the if === null constructor instead? Otherwise just depend that the developer has set it manually? Something I've run into with spine on setting the anchorpoint.

agmcleod avatar Nov 13 '13 16:11 agmcleod

This is another case where the classical inheritance pattern fails us. Actually, this case pinpoints the biggest issue with property-overrides as an inheritance pattern;

Imagine we were to allow something like this:

var MyClass = me.Renderable.extend({
    anchorPoint : new Vector2d(0.5, 1.0),

    // ...
});

This seems like it should be ok. But when you instantiate multiple objects with a class like this, they will all reference the same anchorPoint Vector2d object. Such that all objects will see the changes made to it. And even worse, subclasses also inherit this bad behavior.

It is also not possible to use simple objects for the same reason. So using { x : 0.5, y : 1.0 } in place of new Vector2d(0.5, 1.0) has the same exact problem.

Numbers and Booleans can be used this way, because they cannot be referenced in JavaScript. String laterals are also ok, because they are immutable. But String objects are objects, so also cannot be used this way.

If you have a better recommendation than overriding the constructor and taking care to update object properties after calling the superconstructor, I would be interested. :)

parasyte avatar Nov 13 '13 18:11 parasyte

Write it in C?

Yeah i agree that kinda property thing is a pain. It's why i've mostly setup properties for my own classes inside the constructor. Your last sentence is what I'm trying to avoid lol. I need to set the anchorPoint properly before I call the parent constructor, so the me.Spine.Entity constructor is called (it sets up the collision rectangle based on the anchorPoint). I agree we will continue to run into issues, but is there an issue with setting the value to 0.5,0.5 only when it invokes a new Vector2d() ?

Referring to https://github.com/melonjs/melonJS/blob/master/src/renderable/base.js#L134

agmcleod avatar Nov 13 '13 18:11 agmcleod

Okay i see exactly what you mean. X is 1 on both outputs.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title></title>
    <meta name="viewport" content="width=device-width, minimum-scale=1.0" />
    <script>
      Object.extend = function(prop) {
        // _super rename to parent to ease code reading
        var parent = this.prototype;

        // Instantiate a base class (but only create the instance,
        // don't run the init constructor)
        initializing = true;
        var proto = new this();
        initializing = false;

        // Copy the properties over onto the new prototype
        for ( var name in prop) {
          // Check if we're overwriting an existing function
          proto[name] = typeof prop[name] === "function" &&
                  typeof parent[name] === "function" &&
                  fnTest.test(prop[name]) ? (function(name, fn) {
            return function() {
              var tmp = this.parent;

              // Add a new ._super() method that is the same method
              // but on the super-class
              this.parent = parent[name];

              // The method only need to be bound temporarily, so we
              // remove it when we're done executing
              var ret = fn.apply(this, arguments);
              this.parent = tmp;

              return ret;
            };
          })(name, prop[name]) : prop[name];
        }

        // The dummy class constructor
        function Class() {
          if (!initializing && this.init) {
            this.init.apply(this, arguments);
          }
          //return this;
        }
        // Populate our constructed prototype object
        Class.prototype = proto;
        // Enforce the constructor to be what we expect
        Class.constructor = Class;
        // And make this class extendable
        Class.extend = Object.extend;//arguments.callee;

        return Class;
      };

      var me = {};
      me.Vector2d = Object.extend({
        init : function(x, y) {
          this.x = x;
          this.y = y;
        }
      });

      me.Sprite = Object.extend({
        anchorPoint : new me.Vector2d(10, 10),

        init : function() {

        }
      });

      var one = new me.Sprite();
      var two = new me.Sprite();
      one.anchorPoint.x = 1;

      console.log(one.anchorPoint);
      console.log(two.anchorPoint);
    </script>
  </head>
  <body>
  </body>
</html>

Damn it.

agmcleod avatar Nov 13 '13 19:11 agmcleod

Yes. We have hit this issue many times before:

  • https://github.com/melonjs/melonJS/commit/3154d9b8cabc459cc96c23c357e3581f6be0a684
  • https://github.com/melonjs/melonJS/commit/40248f1178ee87072450c5881bd3c4cf31db33c4#commitcomment-2686100

parasyte avatar Nov 13 '13 23:11 parasyte

The "maybe-initialize-and-always-reset" pattern mostly showed up in a27f084b9f75012782331c779f2d0053af49f48f - It's a way to reset the vectors for the entity pool. Rather than tearing down the object completely, its composed objects are simply reset to defaults without initiating the GC more than necessary.

I've assigned this ticket to the 0.9.11 Milestone. We have some time to decide how to handle it.

Here are some comments from IRC about this a few days ago:

[16:15.01] <agmcleod> Might be a good idea for us to put together some coding/style guidelines for contributors, including ourselves
[16:15.04] <agmcleod> keeping note of things like that
[16:16.31] <pubjay> I'm wondering if the extend method should just make deep copies of non-function keys, and be done with it...
[16:16.56] <agmcleod> yeah perhaps
[16:17.09] <agmcleod> any pitfalls?
[16:17.17] <agmcleod> Not sure if that would cause us any GC hell
[16:17.30] <pubjay> When it comes across `anchorPoint` which is an instantiation of me.Vector2d ...
[16:18.03] <pubjay> It would have to know that it can deep-copy by calling its .copy() method.
[16:18.11] <agmcleod> right
[16:20.10] <pubjay> That could be by convention, though
[16:20.50] <pubjay> It won't be any harder on the GC than the constructor creating these objects. :)
[16:23.17] <agmcleod> yeah you're probably right

But really, there are two conflicting ideas at play here:

  1. Resetting objects in the entity pool
  2. Instantiating objects using class definition

The first one is probably best solved with a separate method. ScreenObject has an onResetEvent() method, it makes sense for entity pool to use the same pattern.

The second one is a bit trickier, but could be solved directly in Object.extend() using a "smart" deep-copy function that knows when to recursively iterate native JS Objects and Arrays, and when to call a copy() method on melonJS objects. This will at least allow the class definition pattern that I described above: https://github.com/melonjs/melonJS/issues/307#issuecomment-28419276

@obiot Any thoughts?

parasyte avatar Nov 17 '13 22:11 parasyte

sorry guys for the late feedback !

from my viewpoint, unless we do a major rewrite of the inheritance mechanism in melonJS, I think that we should just state that we cannot trust property definition in the class itself, as Jason you explained it very well two or three messages earlier.

In the mean time, I think that the mix of the 2 following improvements could greatly help with all this :

  • the global reference issue shoul be fixable by adding the missing deep-copy here before the call to init : https://github.com/melonjs/melonJS/blob/master/src/core.js#L364
  • the onResetEvent() could however and effectively be used to at least re-initialize the object default properties when using object pooling feature.

obiot avatar Nov 25 '13 09:11 obiot

There an easy way for point 2 though? I suppose we'd have a "defaults" hash or something that could be referred to for each object, but no doubt that would have to be constructed. Personally, I like the solution of keeping the properties initialized in a constructor, much like how you would do it in most static-typed languages. At least it's how I do it :)

agmcleod avatar Nov 25 '13 13:11 agmcleod

https://github.com/melonjs/melonJS/blob/0d5527c5379480cac694216931113beac6dac725/src/core.js#L371

... : deepcopy(prop[name]) ...

parasyte avatar Nov 25 '13 23:11 parasyte

after spending one hour on stackoverflow, here is what I think is a mix of the best of the best on the topic :

 function deepcopy( obj ) {

    if (null == obj || "object" != typeof obj) {
        return obj;
    } 

    // Array copy
    if( obj instanceof Array ) {
        var copy = [];
        for( var i = 0, l = obj.length; i < l; i++) {
            copy[i] = deepcopy(obj[i]);
        }
        return copy;
    }

    // Date copy
    if (obj instanceof Date) {
        var copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }

    // else instanceof Object
    var copy = {};
    for( var attr in obj ) {
        if (obj.hasOwnProperty(attr)) copy[attr] = deepcopy(obj[attr]);
    }
    return copy;
}

i have not tried it, but the code is simple enough, and should basically do the trick ;)

who wants to give it a try ?? :):):)

obiot avatar Nov 26 '13 02:11 obiot

@obiot Looks good for normal JavaScript objects, but will not work well with melonJS objects! Try for example:

var orig = new me.Vector2d(50, 50);
var copy = deepcopy(orig);

console.log(orig.add); // function (a){return this.x+=a.x,this.y+=a.y,this}
console.log(orig instanceof me.Vector2d); // true

console.log(copy.add); // undefined
console.log(copy instanceof me.Vector2d); // false

We would need to use Eg.:

else if (obj instanceof me.Vector2d || obj instanceof me.Shape) {
    return obj.copy();
}

parasyte avatar Nov 26 '13 02:11 parasyte

hmm...

what about removing the test on hasOwnProperty for the last case then :

 // else instanceof Object
    var copy = {};
    for( var attr in obj ) {
        copy[attr] = deepcopy(obj[attr]);
    }
    return copy;

obiot avatar Nov 26 '13 03:11 obiot

Functionally, that works, but the instanceof operator will fail. I'm not sure if it will break anything.

parasyte avatar Nov 26 '13 03:11 parasyte

with this last commit, and based on my test and understanding, this is now fully working :

as the below test : https://github.com/melonjs/melonJS/blob/deepcopy/examples/deepcopy/main.js

correctly generates the following output :

Object {x: 0.5, y: 0.5, init: function, set: function, setZero: function…}
true 
true 
Object {x: 1.5, y: 1.5, init: function, set: function, setZero: function…}
true 
true 
true 
1 !== 3 
true 
true

obiot avatar Nov 26 '13 06:11 obiot

Weird. The last three fail for me.

3 !== 3 main.js:42
false main.js:43
false main.js:44

parasyte avatar Nov 26 '13 06:11 parasyte

sorry but I need to ask : did you recompile before testing ? (and pulled the last version)

obiot avatar Nov 26 '13 06:11 obiot

HA! I did not. ;) That also explains why my other tests unexpectedly succeeded...

// Expected
console.log(vec1.a instanceof me.Vector2d); // true
console.log(vec2.a instanceof me.Vector2d); // true

Both return false.

parasyte avatar Nov 26 '13 06:11 parasyte

just wondering, now that property deep copy is working as expected, what is the status of this one, in regards to the initial ticket content ?

obiot avatar Nov 26 '13 11:11 obiot

@obiot Part one is solved by deepcopy; code like https://github.com/melonjs/melonJS/issues/307#issuecomment-28419276 is acceptable now. But the original report was about properties like anchorPoint and pos getting wiped out by the constructors.

Here's a test to try out:

var AnchoredRenderable = me.Renderable.extend({
    anchorPoint : new me.Vector2d(0.5, 1.0)
});

it("is anchored at 0.5,1.0", function () {
    var obj = new AnchoredRenderable(
        new me.Vector2d(),
        20,
        20
    );
    expect(obj.anchorPoint.x).toEqual(0.5);
    expect(obj.anchorPoint.y).toEqual(1.0);
});

parasyte avatar Nov 26 '13 11:11 parasyte

so my last thoughts on this one :

now that we can properly do something like this in melonJS :

me.Rect = Object.extend(
    /** @scope me.Rect.prototype */ {

        /**
         * position of the Rectange
         * @public
         * @type me.Vector2d
         * @name pos
         * @memberOf me.Rect
         */
        pos : new me.Vector2d(),
    // ...
});

we can remove all properties object initialization from the constructor, so typically this kind of line :

    /** @ignore */
    init : function(v, w, h) {
       if (this.pos === null) { 
            this.pos = new me.Vector2d();
       }
       .....
    }

With this code removed, we can both defined the default value we want in the default object, while letting full liberty to anyone to overwrite it (either by extending the object and redefining the porperty, or by just changing the default value in the constructor).

the only cons I see is when using the entity pool mechanism, as we don't provide anymore any built-in way to restore objects to their default value.

In my opinion, the last point is acceptable, as anyway it's impossible to provide such a default "restorable" state for all object easily, and since it's the user choice to use entity pooling, it's also kind of it's responsibility to ensure objects are restored when required to their default state?

now as a compromised we could add a empty function onRecyling (with a better name) that would be call each time an object is re-instantiated from the pool ? so that user are then free to do whatever they need from inside ?

obiot avatar Nov 28 '13 07:11 obiot

@obiot Good points. I'm ok with using the onResetEvent name for this kind of callback, but I really think it is necessary; not just a nice feature. I was thinking about it just this morning. You remember the old HUD_Object class that had a reset() method for resetting to the default value? It's a useful pattern in a lot of cases! I would like to see a callback like onResetEvent available for any object that can be reset to a default value. My thoughts went something like this:

/** me.Vector2d */
init : function (x, y) {
    this._defaults = arguments;
    this.onResetEvent();
},

onResetEvent : function () {
    this.x = this._defaults[0];
    this.y = this._defaults[1];
}
/** me.ObjectEntity */
onResetEvent : function () {
    this.pos.onResetEvent();
    // ...
}

parasyte avatar Nov 28 '13 07:11 parasyte