lychees's picture
Upload 569 files
87b3b3a
/**
* @class Hexagonal backend
* @private
*/
ROT.Display.Hex = function(context) {
ROT.Display.Backend.call(this, context);
this._spacingX = 0;
this._spacingY = 0;
this._hexSize = 0;
this._options = {};
}
ROT.Display.Hex.extend(ROT.Display.Backend);
ROT.Display.Hex.prototype.compute = function(options) {
this._options = options;
var charWidth = Math.ceil(this._context.measureText("W").width);
this._hexSize = Math.floor(options.spacing * (options.fontSize + charWidth/Math.sqrt(3)) / 2);
this._spacingX = this._hexSize * Math.sqrt(3) / 2;
this._spacingY = this._hexSize * 1.5;
this._context.canvas.width = Math.ceil( (options.width + 1) * this._spacingX );
this._context.canvas.height = Math.ceil( (options.height - 1) * this._spacingY + 2*this._hexSize );
}
ROT.Display.Hex.prototype.draw = function(data, clearBefore) {
var x = data[0];
var y = data[1];
var ch = data[2];
var fg = data[3];
var bg = data[4];
var cx = (x+1) * this._spacingX;
var cy = y * this._spacingY + this._hexSize;
if (clearBefore) {
this._context.fillStyle = bg;
this._fill(cx, cy);
}
if (!ch) { return; }
this._context.fillStyle = fg;
this._context.fillText(ch, cx, cy);
}
ROT.Display.Hex.prototype.computeSize = function(availWidth, availHeight) {
var width = Math.floor(availWidth / this._spacingX) - 1;
var height = Math.floor((availHeight - 2*this._hexSize) / this._spacingY + 1);
return [width, height];
}
ROT.Display.Hex.prototype.computeFontSize = function(availWidth, availHeight) {
var hexSizeWidth = 2*availWidth / ((this._options.width+1) * Math.sqrt(3)) - 1;
var hexSizeHeight = availHeight / (2 + 1.5*(this._options.height-1));
var hexSize = Math.min(hexSizeWidth, hexSizeHeight);
/* compute char ratio */
var oldFont = this._context.font;
this._context.font = "100px " + this._options.fontFamily;
var width = Math.ceil(this._context.measureText("W").width);
this._context.font = oldFont;
var ratio = width / 100;
hexSize = Math.floor(hexSize)+1; /* closest larger hexSize */
var fontSize = 2*hexSize / (this._options.spacing * (1 + ratio / Math.sqrt(3)));
/* closest smaller fontSize */
return Math.ceil(fontSize)-1;
}
ROT.Display.Hex.prototype._fill = function(cx, cy) {
var a = this._hexSize;
var b = this._options.border;
this._context.beginPath();
this._context.moveTo(cx, cy-a+b);
this._context.lineTo(cx + this._spacingX - b, cy-a/2+b);
this._context.lineTo(cx + this._spacingX - b, cy+a/2-b);
this._context.lineTo(cx, cy+a-b);
this._context.lineTo(cx - this._spacingX + b, cy+a/2-b);
this._context.lineTo(cx - this._spacingX + b, cy-a/2+b);
this._context.lineTo(cx, cy-a+b);
this._context.fill();
}