Files
cell/scripts/modules/lcdsprite.js
John Alanbrook a85b1873dd
Some checks failed
Build and Deploy / package-dist (push) Has been cancelled
Build and Deploy / deploy-itch (push) Has been cancelled
Build and Deploy / deploy-gitea (push) Has been cancelled
Build and Deploy / build-windows (CLANG64) (push) Has been cancelled
Build and Deploy / build-linux (push) Has been cancelled
sprite rework
2025-05-04 11:28:45 -05:00

108 lines
2.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* Sprite façade (JS) ↔ struct sprite (C)
* The C side exposes per-field getters/setters plus
* `set_affine(m)` which (re)calculates the 2×2 matrix from
* scale / skew / rotation.
* We mirror every exposed field and make sure the C
* matrix is refreshed whenever one of the three factors
* changes.
*/
var sprite = {}
var graphics = use('graphics')
var render = use('render')
var draw2d = use('draw2d')
var SPRITE = Symbol() /* raw C sprite */
var POS = Symbol() /* cached JS copies of simple data */
var ROT = Symbol()
var SCALE = Symbol()
var SKEW = Symbol()
var CENTER = Symbol()
var COLOR = Symbol()
var ursprite = {
get pos() { return this[POS] },
set pos(v) {
this[POS] = v
this[SPRITE].pos = v
},
get center() { return this[CENTER] },
set center(v){
this[CENTER] = v
this[SPRITE].center = v
},
get rotation() { return this[ROT] },
set rotation(t){
this[ROT] = t
this[SPRITE].rotation = t * 2*Math.PI /* C expects radians */
this[SPRITE].set_affine()
},
get scale() { return this[SCALE] },
set scale(v){
this[SCALE] = v
this[SPRITE].scale = v
this[SPRITE].set_affine()
},
get skew() { return this[SKEW] },
set skew(v){
this[SKEW] = v
this[SPRITE].skew = v
this[SPRITE].set_affine()
},
get layer() { return this[SPRITE].layer },
set layer(n){ this[SPRITE].layer = n },
get color() { return this[COLOR] },
set color(v){
this[COLOR] = v
this[SPRITE].color = v
},
move(mv){
this.pos = {x:this.pos.x+mv.x, y:this.pos.y+mv.y}
},
moveto(p){
this.pos = p
}
}
var _sprites = []
sprite.create = function(image, pos, anchor=[0,0], layer=0, props={}) {
var sp = Object.create(ursprite)
var raw = graphics.make_sprite()
sp[SPRITE] = raw
sp.pos = pos
sp.rotation = 0
sp.scale = [1,1]
sp.skew = [0,0]
sp.center = anchor
sp.color = [1,1,1,1]
var tex = graphics.texture(image)
raw.set_image(tex)
sp.image = tex
sp.layer = layer
sp.props = props
sp.anchor = anchor
_sprites.push(sp)
return sp
}
sprite.forEach = fn => { for (let s of _sprites) fn(s) }
sprite.values = () => _sprites.slice()
sprite.geometry= () => graphics.make_sprite_mesh(_sprites)
sprite.queue = () => graphics.make_sprite_queue(_sprites)
return sprite