]> git.plutz.net Git - flarejs/blob - engine.js
Enable map teleporters, process mapmod events, clip map drawing on canvas for much...
[flarejs] / engine.js
1 var gamedata = {
2   // associative array for gamedata files
3   load: function(def) { return this[def] ? this[def] : this[def] = new Textfile(def); }
4 }
5 var gfx = {
6   // associative array for game graphics
7   load: function(def) {
8     if (!this[def]) {
9       this[def] = document.createElement("img");
10       this[def].setAttribute("src", def);
11     }
12     return this[def];
13   }
14 };
15 var map;
16
17 function Textfile(txtfile) {
18   // fetch and parse gamedata file into structured object
19   var lines, fetch = new XMLHttpRequest();
20   fetch.open("GET", txtfile, false);
21   fetch.send();
22
23   var line, key, value, ref = this, section;
24   for (line of fetch.responseText.split('\n')) switch(true) {
25     // section headers that always become array elements
26     case /^\[(npc|event|layer|dialog)\]$/.test(line):
27       section = line.split(/[\]\[]/)[1]; ref = {};
28       if                     (!this[section]) this[section] = [ref];
29       else if ( Array.isArray(this[section])) this[section].push(ref);
30       break;
31     // general section headers (may or may not be unique)
32     case /^\[.*\]$/.test(line):
33       section = line.split(/[\]\[]/)[1]; ref = {};
34       if                     (!this[section]) this[section] = ref;
35       else if (!Array.isArray(this[section])) this[section] = [this[section],ref];
36       else if ( Array.isArray(this[section])) this[section].push(ref);
37       break;
38     // frame definition from animation files
39     // frame=#frame,direction,srcX,srcY,width,height,dstX,dstY
40     case /^frame=[0-9]+,[0-7](,[0-9-]+){6}$/.test(line):
41       key = line.split(/[=,]/).slice(1,3);  value = line.split(/,/).slice(-6);
42       if (!ref.frame) ref.frame = [];
43       if (!ref.frame[key[0]]) ref.frame[key[0]] = [];
44       ref.frame[key[0]][key[1]] = value.map(x => parseInt(x));
45       break;
46     // order of gfx draw from engine/hero_layers.txt
47     // layer=direction,list,of,limbs,...
48     case /^layer=[0-9]+,/.test(line):
49       key = line.split(/[=,]/)[1];  value = line.split(/,/).slice(1);
50       if (!ref.layer) ref.layer = []; ref.layer[key] = value;
51       break;
52     // empty data= line starting map data in map files
53     case /^data=$/.test(line):
54       ref.data = [];
55       break;
56     // map data array
57     case /^[0-9,]+,$/.test(line):
58       value = line.split(/,/).slice(0,-1);
59       ref.data = ref.data.concat(value);
60       break;
61     // map data array (last line)
62     case /^[0-9,]+$/.test(line):
63       value = line.split(/,/);
64       ref.data = ref.data.concat(value);
65       ref.data = ref.data.map(x => parseInt(x));
66       break;
67     // tile description from tiledef file
68     // tile=#tile,srcX,srcY,width,height,dstX,dstY
69     case /^tile=[0-9]+,/.test(line):
70       key = line.split(/[=,]/)[1];  value = line.split(/,/).slice(1);
71       if (!ref.tile) ref.tile = []; ref.tile[key] = value.map(x => parseInt(x));
72       break;
73     // animated tile from tiledef file
74     // animation=#tile;(srcX,srcY,duration;)...
75     case /^animation=[0-9]+;.*;$/.test(line):
76       key = line.split(/[=;]/)[1];  value = line.split(/;/).slice(1,-1);
77       value = value.map(x => x.split(/,/));
78       value.forEach(x => x[2] = parseInt(x[2]));
79       if (!ref.animation) ref.animation = []; ref.animation[key] = value;
80       break;
81     // frame duration from animation file (im millisec)
82     case /^duration=[0-9]+ms$/.test(line):
83       ref.duration = line.split(/=|ms$/)[1];
84       break;
85     // frame duration from animation file (in whole seconds)
86     case /^duration=[0-9]+s$/.test(line):
87       ref.duration = line.split(/=|s$/)[1] * 1000;
88       break;
89     // mapmod events
90     case /^mapmod=.*$/.test(line):
91       ref.mapmod = line.split(/[=]/)[1].split(/[;]/).map( m => m.split(/[,]/).map( n => n * 1 ? n * 1 : n) );
92       break;
93     // general array type, will not be aggregated
94     case /^[^#].*=.*,.*$/.test(line):
95       key = line.split(/[=]/)[0]; value = line.split(/[=]/)[1].split(/,/);
96       ref[key] = value.map(m => m * 1 ? m * 1 : m);  // parse numerics
97       break;
98     // general key=value
99     case /^[^#].*=.+$/.test(line):
100       key = line.split(/[=]/)[0];
101       value = line.split(/=/).slice(1).join("=");
102       value = value * 1 ? value * 1 : value;  // try to parse as numeric
103       if                     (!ref[key]) ref[key] = value;
104       else if (!Array.isArray(ref[key])) ref[key] = [ref[key],value];
105       else if ( Array.isArray(ref[key])) ref[key].push(value);
106       break;
107   }
108 }
109
110 function Map(textdef) {
111   // object for map operations (drawing coorinate transformation, etc.)
112   this.info = gamedata.load(textdef);
113   const tileset = gamedata.load(this.info.header.tileset);
114   const frametime = performance.now();
115   gfx.load(tileset.img);
116
117   const  h = this.info.header.height,      w = this.info.header.width;
118   const th = this.info.header.tileheight, tw = this.info.header.tilewidth;
119   var posx = canvas.canvas.width / 2, posy = canvas.canvas.height / 2 - h * th/2;
120
121   canvas.fillStyle = "rgba("+this.info.header.background_color+")";
122
123   // precalculated tile positions
124   // assign x/y coordinates to each tile index
125   // looks dumb but is faster than on the fly isometric calculations
126   const dx = [], dy = [];
127   for ( let y = 0; y < h; y++ ) for ( let x = 0; x < w; x++ ) {
128     dx[y * w + x] = (w + x - y) * tw / 2;
129     dy[y * w + x] = (x + y) * th / 2;
130   }
131
132   const npcs = [];
133   if (this.info.npc) for (let def of this.info.npc) {
134     let loc = def.location[1] * w + def.location[0];
135     npcs[loc] = new Npc(def.filename)
136     npcs[loc].place(dx[loc], dy[loc]);
137     this.info.layer.find(l => l.type == "collision").data[loc] = 1;
138   }
139
140   this.events = [];
141   for (let ev of this.info.event) {
142     for (let x = ev.location[0]; x < ev.location[0] + ev.location[2]; x++)
143       for (let y = ev.location[1]; y < ev.location[1] + ev.location[3]; y++) {
144         let loc = y * w + x;
145         if (!this.events[loc]) this.events[loc] = [];
146         this.events[loc].push(ev);
147       }
148   }
149
150   // tile index for pixel position on map
151   this.tileAt = function(x, y) {
152     var r = (y + th / 2) / th; var c = (x - w * tw /2) / tw;
153     var nx = r + c |0; var ny = r - c |0;
154     return ny * w + nx;
155   }
156
157   // vice versa the pixel coordinates of a given map tile
158   this.positionOf = (tl, ty = -1) => (~ty) ? [dx[ty * w + tl], dy[ty * w + tl]] : [ dx[tl], dy[tl] ];
159   this.xOf = (tl, ty = -1) => (~ty) ? dx[ty * w + tl] : dx[tl];
160   this.yOf = (tl, ty = -1) => (~ty) ? dy[ty * w + tl] : dy[tl]; 
161
162   // center map to pixel position (by setting drawing offsets)
163   this.center = function(x, y) {
164     posx = canvas.canvas.width  / 2 - x;
165     posy = canvas.canvas.height / 2 - y;
166     return this;
167   }
168
169   // draw the entire map, including all mobs
170   // mobs in an array of all heros, enemies, loot, npcs, etc.
171   this.draw = function(mobs) {
172     const bg = this.info.layer.find(l => l.type == "background").data;
173     const ob = this.info.layer.find(l => l.type == "object").data;
174     var i, mm = [];
175     //var is = (posx > w * tw - canvas.canvas.width || posy < 0) ? 0 : this.tileAt(posx + canvas.canvas.width, posy);
176     // var ie = this.tileAt(posx, + canvas.canvas.height - posy);
177
178     // mobs only have x/y pixel positions,
179     // to draw them in order with map tiles we set up
180     // an array with current tile positions of mobs
181     mobs.forEach(m => {
182       let i = this.tileAt(m.position[0], m.position[1]);
183       mm[i] = mobs.filter(m => i == this.tileAt(m.position[0], m.position[1]));
184     });
185     canvas.fillRect(0,0, canvas.canvas.width, canvas.canvas.height);
186
187     // draw background layer first
188     for ( i = 0; i < h * w; i++ ) draw_tile(bg[i], posx + dx[i], posy + dy[i]);
189     // for ( i = is; i < ie; i++ ) draw_tile(bg[i], posx + dx[i], posy + dy[i]);
190
191     // draw object layer and mobs
192     for ( i = 0; i < h * w; i++ ) {
193     // for ( i = is; i < ie; i++ ) {
194       draw_tile(ob[i], posx + dx[i], posy + dy[i]);
195       if (mm[i]) mm[i].forEach(m => m.draw(posx + m.position[0], posy + m.position[1]));
196       if (npcs[i]) npcs[i].draw(posx + dx[i], posy + dy[i]);
197     }
198   }
199
200   // draw a single map tile at screen position x/y
201   // tile may be animated, if so defined in tiledef
202   function draw_tile(tile, x, y) {
203     const t = tileset.tile[tile];
204     const f = tileset.animation[tile];
205     x = x |0; y = y |0;
206
207     if (t && f) {
208       frame = ((performance.now() - frametime) / f[0][2] |0) % f.length;
209       if ( x + t[2] - t[4] > 0 && y + t[3] - t[5] > 0 && x - t[4] < canvas.canvas.width && y - t[5] < canvas.canvas.height)
210       canvas.drawImage(gfx[tileset.img], f[frame][0], f[frame][1], t[2], t[3],
211                                                x - t[4], y - t[5], t[2], t[3]);
212     } else if (t) {
213       if ( x + t[2] - t[4] > 0 && y + t[3] - t[5] > 0 && x - t[4] < canvas.canvas.width && y - t[5] < canvas.canvas.height)
214       canvas.drawImage(gfx[tileset.img], t[0], t[1], t[2], t[3],
215                                  x - t[4], y - t[5], t[2], t[3]);
216     }
217   }
218 }
219
220 function Mob(textdef) {
221   // any mobile object, mostly for gfx representation
222   // may be hero, enemy, loot, npc, etc.
223   this.position = [0, 0];
224   const info = gamedata.load(textdef);
225   var direction = 0;
226   var animation = "stance";
227   var previous_animation = "";
228   var frametime = performance.now();
229   gfx.load(info.image)
230
231   // some simplified npc files do not define animation frames
232   // render size and offset are given instead, and we
233   // assume, that we can just loop horizontally over the image
234   if (!info[animation].frame){
235     info[animation].frame = [];
236     let rs = info.render_size, ro = info.render_offset;
237
238     for (let i = 0; i < info[animation].frames; i++ )
239       info[animation].frame[i] = [[ i * rs[0], 0, rs[0], rs[1], ro[0], ro[1]]];
240   }
241
242   // place mob on x/y pixel coordinates
243   // e.g. when spawning, walking, etc.
244   this.place = function(x, y) {
245     this.position[0] = x, this.position[1] = y;
246     return this;
247   }
248
249   // change facing direction of mob
250   this.direct = function(d) { direction = d % 8; return this; }
251
252   // set animation cycle for drawing
253   // play_once animations will automatically fall back
254   // to previous loop after completion
255   this.animate = function(a) {
256     if ( a != animation ) {
257       previous_animation = animation;
258       animation = a;
259       frametime = performance.now();
260     }
261     return this;
262   }
263
264   // draw this mob to screen position x/y
265   this.draw = function(x, y){
266     var f, a = info[animation];
267     var f, frame = ( performance.now() - frametime ) * a.frames / a.duration | 0;
268
269     // determine current animation frame
270     switch(a.type){
271       case "looped":
272         frame = frame % a.frames;
273         break;
274       case "play_once":
275         if ( frame >= a.frames ){
276           animation = previous_animation;
277           previous_animation = "";
278           frametime = performance.now();
279           a = info[animation];
280           frame = 0;
281         }
282         break;
283       case "back_forth":
284         frame = frame % (a.frames * 2 - 2);
285         if ( frame >= a.frames ){
286          frame = a.frames - frame % a.frames - 1;
287         }
288         break;
289       default: break;
290     }
291     f = a.frame[frame][direction];
292
293     canvas.drawImage(gfx[info.image], f[0], f[1], f[2], f[3],
294                      x - f[4], y - f[5],
295                      f[2], f[3]);
296   }
297
298   // shortcut functions for specific animations
299   this.block  = () => this.animate("block" );
300   this.cast   = () => this.animate("cast"  );
301   this.die    = () => this.animate("die"   );
302   this.hit    = () => this.animate("hit"   );
303   this.run    = () => this.animate("run"   );
304   this.shoot  = () => this.animate("shoot" );
305   this.stance = () => this.animate("stance");
306   this.swing  = () => this.animate("swing" );
307 }
308
309 function Npc(textdef){
310   this.info = gamedata.load(textdef);
311   const avatar = new Mob(this.info.gfx);
312
313   this.place = function(x, y) {
314     avatar.place(x,y);
315     return this;
316   }
317
318   this.draw = function(x, y) {
319     avatar.draw(x, y);
320     return this;
321   }
322 }
323
324 function Hero(gender = "female", hair = "short"){
325   // Object for player character
326   // unique in single player
327   this.position = [0,0];
328   this.stats = gamedata.load("/engine/stats.txt");
329   const layers = gamedata.load("/engine/hero_layers.txt");
330   var direction = 0, animation = "stance";
331   hair = (gender == "female")?"long":hair;
332
333   // hero consists of multiple mobs, one for each clothing/item overlay
334   var limbs = {
335     head : new Mob("/animations/avatar/"+gender+"/head_"+hair+".txt"),
336     chest: new Mob("/animations/avatar/"+gender+"/cloth_shirt.txt"),
337     hands: new Mob("/animations/avatar/"+gender+"/default_hands.txt"),
338     legs : new Mob("/animations/avatar/"+gender+"/cloth_pants.txt"),
339     feet : new Mob("/animations/avatar/"+gender+"/default_feet.txt"),
340     main : null, // main hand, e.g. melee weapon, magic weapon
341     off  : null  // off hand, e.g. shield, ranged weapon
342   }
343
344   // "dress" the player, i.e. assign clothing/item to limb
345   this.dress = function(limb, item) {
346     limbs[limb] = new Mob("/animations/avatar/"+gender+"/"+item+".txt")
347     limbs[limb].place(this.position[0], this.position[1]).direct(direction);
348     this.animate(animation);
349     return this;
350   }
351
352   // // Wrapper functions for Mob class // //
353
354   // place all mobs beloning to hero (when spawning, walking, teleporting, etc.)
355   this.place   = function(x,y) {
356     this.position[0] = x, this.position[1] = y;
357     for (var limb in limbs) limbs[limb] && limbs[limb].place(x,y);
358     return this;
359   }
360   // change facing direction of hero (i.e. of all mobs)
361   this.direct  = function(d)   {
362     direction = d;
363     for (var limb in limbs) limbs[limb] && limbs[limb].direct(d);
364     return this;
365   }
366   // start animation cycle
367   this.animate = function(anim){
368     animation = anim;
369     for (var limb in limbs) limbs[limb] && limbs[limb].animate(anim);
370     return this;
371   }
372   this.draw    = function(x, y){
373     layers.layer[direction].forEach(limb => limbs[limb] && limbs[limb].draw(x, y));
374     return this;
375   }
376
377   // shortcuts for animation
378   this.block  = () => this.animate("block" );
379   this.cast   = () => this.animate("cast"  );
380   this.die    = () => this.animate("die"   );
381   this.hit    = () => this.animate("hit"   );
382   this.run    = () => this.animate("run"   );
383   this.shoot  = () => this.animate("shoot" );
384   this.stance = () => this.animate("stance");
385   this.swing  = () => this.animate("swing" );
386 }
387
388 function Controls(hero){
389   // processes keyboard / touch / mouse
390   // causes according player actions
391   // single player only, conrol will be assigned to server in multi player
392   var kbdmap = {
393        up: 87,    altup: 38,
394      down: 83,  altdown: 40,
395      left: 65,  altleft: 37,
396     right: 68, altright: 39,
397   }
398   var keys = [];
399
400   window.addEventListener("keydown", e => keys[e.keyCode] = true );
401   window.addEventListener("keyup"  , e => keys[e.keyCode] = false);
402   setInterval(() => input(), 33.33)
403
404   // cause player to walk, processes blocked terrain and player speed
405   // x/y are factors of speed and direction
406   //     i.e. +/-1 for diagonal movement
407   //     and  +/-1.4 for horizontal/vertical movement
408   function translate(x, y){
409     var sx = map.info.header.tilewidth  * hero.stats.speed / 33.33;
410     var sy = map.info.header.tileheight * hero.stats.speed / 33.33;
411     var dx = x * sx, hx = hero.position[0];
412     var dy = y * sy, hy = hero.position[1];
413     var f = 2.1;
414     const col = map.info.layer.find(l => l.type == "collision").data;
415
416     if (col[map.tileAt(hx + dx, hy + dy)] == 0 )
417             hero.place(hx + dx, hy + dy);
418     else if ( dy == 0 && col[map.tileAt(hx + dx / f, hy + sy / 1.5)] == 0 )
419                              hero.place(hx + dx / f, hy + sy / 1.5);
420     else if ( dy == 0 && col[map.tileAt(hx + dx / f, hy - sy / 1.5)] == 0 )
421                              hero.place(hx + dx / f, hy - sy / 1.5);
422     else if ( dx == 0 && col[map.tileAt(hx + sx / 1.5, hy + dy / f)] == 0 )
423                              hero.place(hx + sx / 1.5, hy + dy / f);
424     else if ( dx == 0 && col[map.tileAt(hx - sx / 1.5, hy + dy / f)] == 0 )
425                              hero.place(hx - sx / 1.5, hy + dy / f);
426     else player.stance();
427
428     map.center(hero.position[0], hero.position[1]);
429     events(hero.position[0], hero.position[1]);
430   }
431
432   function events(x, y) {
433     const i = map.tileAt(x,y); let ev, e, n;
434     if (map.events[i]) {
435       // intramap (teleporters)
436       if ( ev = map.events[i].find(e => (e.activate == "on_trigger" && e.intramap)) ){
437         ev = ev.intramap;
438         hero.place( map.xOf(ev[0], ev[1]), map.yOf(ev[0], ev[1]) );
439         map.center( map.xOf(ev[0], ev[1]), map.yOf(ev[0], ev[1]) );
440       }
441       // mapmod (e.g. opening doors, activating platforms, changing terrain, ...)
442       for (ev of map.events[i].filter(e => (e.activate == "on_trigger" && e.mapmod)) ){
443         for (ev of ev.mapmod)
444           map.info.layer.find(l => l.type == ev[0]).data[ev[2] * map.info.header.width + ev[1]] = ev[3];
445       }
446       // intermap (must be last because loading new map breaks further event search)
447       if ( ev = map.events[i].find(e => (e.activate == "on_trigger" && e.intermap)) ){
448         ev = ev.intermap;
449         map = new Map(ev[0]);
450         hero.place( map.xOf(ev[1], ev[2]), map.yOf(ev[1], ev[2]) );
451         map.center( map.xOf(ev[1], ev[2]), map.yOf(ev[1], ev[2]) );
452       }
453     }
454   }
455
456   // process input and decide on according action
457   function input(){
458     // facing directions, indexed by OR of key press combinations
459     const dir   = [ -1, 0, 4, -1, 2, 1, 3, 2, 6, 7, 5, 6, -1, 0, 4, -1 ];
460     // translation speed and direction, indexed by facing direction of movement
461     const trans = [ [-1.4,0], [-1,-1], [0,-1.4], [1,-1], [1.4,0], [1,1], [0,1.4], [-1,1] ];
462     var k = 0;
463
464     // OR of direction key presses
465     k += (keys[kbdmap.left]  || keys[kbdmap.altleft])  ? 1 : 0;
466     k += (keys[kbdmap.right] || keys[kbdmap.altright]) ? 2 : 0;
467     k += (keys[kbdmap.up]    || keys[kbdmap.altup])    ? 4 : 0;
468     k += (keys[kbdmap.down]  || keys[kbdmap.altdown])  ? 8 : 0;
469
470     if (~dir[k]) {
471       hero.direct(dir[k]).run();
472       translate(trans[dir[k]][0], trans[dir[k]][1]);
473     } else hero.stance();
474   }
475 }
476
477 document.querySelector("body").setAttribute("style", "margin: 0; padding: 0;");
478 canvas = document.createElement("canvas").getContext("2d");
479 canvas.canvas.setAttribute("style", "display: block; border: 0; margin: 0; padding: 0;");
480 document.querySelector("body").appendChild(canvas.canvas);
481
482 canvas.canvas.width  = window.innerWidth;
483 canvas.canvas.height = window.innerHeight;
484 window.addEventListener("resize", function(){
485   canvas.canvas.width  = window.innerWidth;
486   canvas.canvas.height = window.innerHeight;
487 });
488
489 // player = new Mob("animations/enemies/zombie.txt"); player.stats = { speed: 3 };
490 player = new Hero();
491 map = new Map("/maps/perdition_harbor.txt");
492 player.place(map.xOf(map.info.header.hero_pos[0], map.info.header.hero_pos[1]),
493              map.yOf(map.info.header.hero_pos[0], map.info.header.hero_pos[1]));
494 player.direct(6).stance();
495
496 map.center(player.position[0], player.position[1]);
497 c = new Controls(player);
498
499 setInterval (() => map.draw([player]), 33.33 );