/*! p5.p5.Typography.js v0.5.11 July 21, 2017 */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.p5 = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice var len = b64.length placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 // base64 is 4/3 + up to two characters of the original data arr = new Arr(b64.length * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? b64.length - 4 : b64.length var L = 0 function push (v) { arr[L++] = v } for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) push((tmp & 0xFF0000) >> 16) push((tmp & 0xFF00) >> 8) push(tmp & 0xFF) } if (placeHolders === 2) { tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) push(tmp & 0xFF) } else if (placeHolders === 1) { tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) push((tmp >> 8) & 0xFF) push(tmp & 0xFF) } return arr } function uint8ToBase64 (uint8) { var i, extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes output = "", temp, length function encode (num) { return lookup.charAt(num) } function tripletToBase64 (num) { return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) } // go through the array every three bytes, we'll deal with trailing stuff later for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output += tripletToBase64(temp) } // pad the end with zeros, but make sure to not forget the extra bytes switch (extraBytes) { case 1: temp = uint8[uint8.length - 1] output += encode(temp >> 2) output += encode((temp << 4) & 0x3F) output += '==' break case 2: temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) output += encode(temp >> 10) output += encode((temp >> 4) & 0x3F) output += encode((temp << 2) & 0x3F) output += '=' break } return output } exports.toByteArray = b64ToByteArray exports.fromByteArray = uint8ToBase64 }(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) },{}],2:[function(_dereq_,module,exports){ },{}],3:[function(_dereq_,module,exports){ (function (global){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = _dereq_('base64-js') var ieee754 = _dereq_('ieee754') var isArray = _dereq_('isarray') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 // not used by this implementation var rootParent = {} /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property * on objects. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : typedArraySupport() function typedArraySupport () { function Bar () {} try { var arr = new Uint8Array(1) arr.foo = function () { return 42 } arr.constructor = Bar return arr.foo() === 42 && // typed array instances can be augmented arr.constructor === Bar && // constructor can be set typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } } function kMaxLength () { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } /** * Class: Buffer * ============= * * The Buffer constructor returns instances of `Uint8Array` that are augmented * with function properties for all the node `Buffer` API functions. We use * `Uint8Array` so that square bracket notation works as expected -- it returns * a single octet. * * By augmenting the instances, we can avoid modifying the `Uint8Array` * prototype. */ function Buffer (arg) { if (!(this instanceof Buffer)) { // Avoid going through an ArgumentsAdaptorTrampoline in the common case. if (arguments.length > 1) return new Buffer(arg, arguments[1]) return new Buffer(arg) } if (!Buffer.TYPED_ARRAY_SUPPORT) { this.length = 0 this.parent = undefined } // Common case. if (typeof arg === 'number') { return fromNumber(this, arg) } // Slightly less common case. if (typeof arg === 'string') { return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') } // Unusual. return fromObject(this, arg) } function fromNumber (that, length) { that = allocate(that, length < 0 ? 0 : checked(length) | 0) if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < length; i++) { that[i] = 0 } } return that } function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' // Assumption: byteLength() return value is always < kMaxLength. var length = byteLength(string, encoding) | 0 that = allocate(that, length) that.write(string, encoding) return that } function fromObject (that, object) { if (Buffer.isBuffer(object)) return fromBuffer(that, object) if (isArray(object)) return fromArray(that, object) if (object == null) { throw new TypeError('must start with number, buffer, array or string') } if (typeof ArrayBuffer !== 'undefined') { if (object.buffer instanceof ArrayBuffer) { return fromTypedArray(that, object) } if (object instanceof ArrayBuffer) { return fromArrayBuffer(that, object) } } if (object.length) return fromArrayLike(that, object) return fromJsonObject(that, object) } function fromBuffer (that, buffer) { var length = checked(buffer.length) | 0 that = allocate(that, length) buffer.copy(that, 0, 0, length) return that } function fromArray (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } // Duplicate of fromArray() to keep fromArray() monomorphic. function fromTypedArray (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) // Truncating the elements is probably not what people expect from typed // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior // of the old Buffer constructor. for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function fromArrayBuffer (that, array) { if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance array.byteLength that = Buffer._augment(new Uint8Array(array)) } else { // Fallback: Return an object instance of the Buffer class that = fromTypedArray(that, new Uint8Array(array)) } return that } function fromArrayLike (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } // Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. // Returns a zero-length buffer for inputs that don't conform to the spec. function fromJsonObject (that, object) { var array var length = 0 if (object.type === 'Buffer' && isArray(object.data)) { array = object.data length = checked(array.length) | 0 } that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array } else { // pre-set for values that may exist in the future Buffer.prototype.length = undefined Buffer.prototype.parent = undefined } function allocate (that, length) { if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = Buffer._augment(new Uint8Array(length)) that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class that.length = length that._isBuffer = true } var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 if (fromPool) that.parent = rootParent return that } function checked (length) { // Note: cannot use `length < kMaxLength` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } return length | 0 } function SlowBuffer (subject, encoding) { if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) var buf = new Buffer(subject, encoding) delete buf.parent return buf } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length var i = 0 var len = Math.min(x, y) while (i < len) { if (a[i] !== b[i]) break ++i } if (i !== len) { x = a[i] y = b[i] } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'raw': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') if (list.length === 0) { return new Buffer(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; i++) { length += list[i].length } } var buf = new Buffer(length) var pos = 0 for (i = 0; i < list.length; i++) { var item = list[i] item.copy(buf, pos) pos += item.length } return buf } function byteLength (string, encoding) { if (typeof string !== 'string') string = '' + string var len = string.length if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'binary': // Deprecated case 'raw': case 'raws': return len case 'utf8': case 'utf-8': return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false start = start | 0 end = end === undefined || end === Infinity ? this.length : end | 0 if (!encoding) encoding = 'utf8' if (start < 0) start = 0 if (end > this.length) end = this.length if (end <= start) return '' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'binary': return binarySlice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } Buffer.prototype.toString = function toString () { var length = this.length | 0 if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '' } Buffer.prototype.compare = function compare (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return 0 return Buffer.compare(this, b) } Buffer.prototype.indexOf = function indexOf (val, byteOffset) { if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff else if (byteOffset < -0x80000000) byteOffset = -0x80000000 byteOffset >>= 0 if (this.length === 0) return -1 if (byteOffset >= this.length) return -1 // Negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) if (typeof val === 'string') { if (val.length === 0) return -1 // special case: looking for empty string always fails return String.prototype.indexOf.call(this, val, byteOffset) } if (Buffer.isBuffer(val)) { return arrayIndexOf(this, val, byteOffset) } if (typeof val === 'number') { if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { return Uint8Array.prototype.indexOf.call(this, val, byteOffset) } return arrayIndexOf(this, [ val ], byteOffset) } function arrayIndexOf (arr, val, byteOffset) { var foundIndex = -1 for (var i = 0; byteOffset + i < arr.length; i++) { if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex } else { foundIndex = -1 } } return -1 } throw new TypeError('val must be string, number or Buffer') } // `get` is deprecated Buffer.prototype.get = function get (offset) { console.log('.get() is deprecated. Access using array indexes instead.') return this.readUInt8(offset) } // `set` is deprecated Buffer.prototype.set = function set (v, offset) { console.log('.set() is deprecated. Access using array indexes instead.') return this.writeUInt8(v, offset) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new Error('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; i++) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) throw new Error('Invalid hex string') buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function binaryWrite (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0 if (isFinite(length)) { length = length | 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { var swap = encoding encoding = offset offset = length | 0 length = swap } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'binary': return binaryWrite(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function binarySlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; i++) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = Buffer._augment(this.subarray(start, end)) } else { var sliceLen = end - start newBuf = new Buffer(sliceLen, undefined) for (var i = 0; i < sliceLen; i++) { newBuf[i] = this[i + start] } } if (newBuf.length) newBuf.parent = this.parent || this return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') if (value > max || value < min) throw new RangeError('value is out of bounds') if (offset + ext > buf.length) throw new RangeError('index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = (value & 0xff) return offset + 1 } function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = value < 0 ? 1 : 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = value < 0 ? 1 : 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (value > max || value < min) throw new RangeError('value is out of bounds') if (offset + ext > buf.length) throw new RangeError('index out of range') if (offset < 0) throw new RangeError('index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start var i if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; i--) { target[i + targetStart] = this[i + start] } } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; i++) { target[i + targetStart] = this[i + start] } } else { target._set(this.subarray(start, start + len), targetStart) } return len } // fill(value, start=0, end=buffer.length) Buffer.prototype.fill = function fill (value, start, end) { if (!value) value = 0 if (!start) start = 0 if (!end) end = this.length if (end < start) throw new RangeError('end < start') // Fill 0 bytes; we're done if (end === start) return if (this.length === 0) return if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') if (end < 0 || end > this.length) throw new RangeError('end out of bounds') var i if (typeof value === 'number') { for (i = start; i < end; i++) { this[i] = value } } else { var bytes = utf8ToBytes(value.toString()) var len = bytes.length for (i = start; i < end; i++) { this[i] = bytes[i % len] } } return this } /** * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. * Added in Node 0.12. Only available in browsers that support ArrayBuffer. */ Buffer.prototype.toArrayBuffer = function toArrayBuffer () { if (typeof Uint8Array !== 'undefined') { if (Buffer.TYPED_ARRAY_SUPPORT) { return (new Buffer(this)).buffer } else { var buf = new Uint8Array(this.length) for (var i = 0, len = buf.length; i < len; i += 1) { buf[i] = this[i] } return buf.buffer } } else { throw new TypeError('Buffer.toArrayBuffer not supported in this browser') } } // HELPER FUNCTIONS // ================ var BP = Buffer.prototype /** * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods */ Buffer._augment = function _augment (arr) { arr.constructor = Buffer arr._isBuffer = true // save reference to original Uint8Array set method before overwriting arr._set = arr.set // deprecated arr.get = BP.get arr.set = BP.set arr.write = BP.write arr.toString = BP.toString arr.toLocaleString = BP.toString arr.toJSON = BP.toJSON arr.equals = BP.equals arr.compare = BP.compare arr.indexOf = BP.indexOf arr.copy = BP.copy arr.slice = BP.slice arr.readUIntLE = BP.readUIntLE arr.readUIntBE = BP.readUIntBE arr.readUInt8 = BP.readUInt8 arr.readUInt16LE = BP.readUInt16LE arr.readUInt16BE = BP.readUInt16BE arr.readUInt32LE = BP.readUInt32LE arr.readUInt32BE = BP.readUInt32BE arr.readIntLE = BP.readIntLE arr.readIntBE = BP.readIntBE arr.readInt8 = BP.readInt8 arr.readInt16LE = BP.readInt16LE arr.readInt16BE = BP.readInt16BE arr.readInt32LE = BP.readInt32LE arr.readInt32BE = BP.readInt32BE arr.readFloatLE = BP.readFloatLE arr.readFloatBE = BP.readFloatBE arr.readDoubleLE = BP.readDoubleLE arr.readDoubleBE = BP.readDoubleBE arr.writeUInt8 = BP.writeUInt8 arr.writeUIntLE = BP.writeUIntLE arr.writeUIntBE = BP.writeUIntBE arr.writeUInt16LE = BP.writeUInt16LE arr.writeUInt16BE = BP.writeUInt16BE arr.writeUInt32LE = BP.writeUInt32LE arr.writeUInt32BE = BP.writeUInt32BE arr.writeIntLE = BP.writeIntLE arr.writeIntBE = BP.writeIntBE arr.writeInt8 = BP.writeInt8 arr.writeInt16LE = BP.writeInt16LE arr.writeInt16BE = BP.writeInt16BE arr.writeInt32LE = BP.writeInt32LE arr.writeInt32BE = BP.writeInt32BE arr.writeFloatLE = BP.writeFloatLE arr.writeFloatBE = BP.writeFloatBE arr.writeDoubleLE = BP.writeDoubleLE arr.writeDoubleBE = BP.writeDoubleBE arr.fill = BP.fill arr.inspect = BP.inspect arr.toArrayBuffer = BP.toArrayBuffer return arr } var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; i++) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; i++) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; i++) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; i++) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"base64-js":1,"ieee754":4,"isarray":5}],4:[function(_dereq_,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],5:[function(_dereq_,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; },{}],6:[function(_dereq_,module,exports){ // The Bounding Box object 'use strict'; function derive(v0, v1, v2, v3, t) { return Math.pow(1 - t, 3) * v0 + 3 * Math.pow(1 - t, 2) * t * v1 + 3 * (1 - t) * Math.pow(t, 2) * v2 + Math.pow(t, 3) * v3; } /** * A bounding box is an enclosing box that describes the smallest measure within which all the points lie. * It is used to calculate the bounding box of a glyph or text path. * * On initialization, x1/y1/x2/y2 will be NaN. Check if the bounding box is empty using `isEmpty()`. * * @exports opentype.BoundingBox * @class * @constructor */ function BoundingBox() { this.x1 = Number.NaN; this.y1 = Number.NaN; this.x2 = Number.NaN; this.y2 = Number.NaN; } /** * Returns true if the bounding box is empty, that is, no points have been added to the box yet. */ BoundingBox.prototype.isEmpty = function() { return isNaN(this.x1) || isNaN(this.y1) || isNaN(this.x2) || isNaN(this.y2); }; /** * Add the point to the bounding box. * The x1/y1/x2/y2 coordinates of the bounding box will now encompass the given point. * @param {number} x - The X coordinate of the point. * @param {number} y - The Y coordinate of the point. */ BoundingBox.prototype.addPoint = function(x, y) { if (typeof x === 'number') { if (isNaN(this.x1) || isNaN(this.x2)) { this.x1 = x; this.x2 = x; } if (x < this.x1) { this.x1 = x; } if (x > this.x2) { this.x2 = x; } } if (typeof y === 'number') { if (isNaN(this.y1) || isNaN(this.y2)) { this.y1 = y; this.y2 = y; } if (y < this.y1) { this.y1 = y; } if (y > this.y2) { this.y2 = y; } } }; /** * Add a X coordinate to the bounding box. * This extends the bounding box to include the X coordinate. * This function is used internally inside of addBezier. * @param {number} x - The X coordinate of the point. */ BoundingBox.prototype.addX = function(x) { this.addPoint(x, null); }; /** * Add a Y coordinate to the bounding box. * This extends the bounding box to include the Y coordinate. * This function is used internally inside of addBezier. * @param {number} y - The Y coordinate of the point. */ BoundingBox.prototype.addY = function(y) { this.addPoint(null, y); }; /** * Add a Bézier curve to the bounding box. * This extends the bounding box to include the entire Bézier. * @param {number} x0 - The starting X coordinate. * @param {number} y0 - The starting Y coordinate. * @param {number} x1 - The X coordinate of the first control point. * @param {number} y1 - The Y coordinate of the first control point. * @param {number} x2 - The X coordinate of the second control point. * @param {number} y2 - The Y coordinate of the second control point. * @param {number} x - The ending X coordinate. * @param {number} y - The ending Y coordinate. */ BoundingBox.prototype.addBezier = function(x0, y0, x1, y1, x2, y2, x, y) { // This code is based on http://nishiohirokazu.blogspot.com/2009/06/how-to-calculate-bezier-curves-bounding.html // and https://github.com/icons8/svg-path-bounding-box var p0 = [x0, y0]; var p1 = [x1, y1]; var p2 = [x2, y2]; var p3 = [x, y]; this.addPoint(x0, y0); this.addPoint(x, y); for (var i = 0; i <= 1; i++) { var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]; var c = 3 * p1[i] - 3 * p0[i]; if (a === 0) { if (b === 0) continue; var t = -c / b; if (0 < t && t < 1) { if (i === 0) this.addX(derive(p0[i], p1[i], p2[i], p3[i], t)); if (i === 1) this.addY(derive(p0[i], p1[i], p2[i], p3[i], t)); } continue; } var b2ac = Math.pow(b, 2) - 4 * c * a; if (b2ac < 0) continue; var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); if (0 < t1 && t1 < 1) { if (i === 0) this.addX(derive(p0[i], p1[i], p2[i], p3[i], t1)); if (i === 1) this.addY(derive(p0[i], p1[i], p2[i], p3[i], t1)); } var t2 = (-b - Math.sqrt(b2ac)) / (2 * a); if (0 < t2 && t2 < 1) { if (i === 0) this.addX(derive(p0[i], p1[i], p2[i], p3[i], t2)); if (i === 1) this.addY(derive(p0[i], p1[i], p2[i], p3[i], t2)); } } }; /** * Add a quadratic curve to the bounding box. * This extends the bounding box to include the entire quadratic curve. * @param {number} x0 - The starting X coordinate. * @param {number} y0 - The starting Y coordinate. * @param {number} x1 - The X coordinate of the control point. * @param {number} y1 - The Y coordinate of the control point. * @param {number} x - The ending X coordinate. * @param {number} y - The ending Y coordinate. */ BoundingBox.prototype.addQuad = function(x0, y0, x1, y1, x, y) { var cp1x = x0 + 2 / 3 * (x1 - x0); var cp1y = y0 + 2 / 3 * (y1 - y0); var cp2x = cp1x + 1 / 3 * (x - x0); var cp2y = cp1y + 1 / 3 * (y - y0); this.addBezier(x0, y0, cp1x, cp1y, cp2x, cp2y, x, y); }; exports.BoundingBox = BoundingBox; },{}],7:[function(_dereq_,module,exports){ // Run-time checking of preconditions. 'use strict'; exports.fail = function(message) { throw new Error(message); }; // Precondition function that checks if the given predicate is true. // If not, it will throw an error. exports.argument = function(predicate, message) { if (!predicate) { exports.fail(message); } }; // Precondition function that checks if the given assertion is true. // If not, it will throw an error. exports.assert = exports.argument; },{}],8:[function(_dereq_,module,exports){ // Drawing utility functions. 'use strict'; // Draw a line on the given context from point `x1,y1` to point `x2,y2`. function line(ctx, x1, y1, x2, y2) { ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); } exports.line = line; },{}],9:[function(_dereq_,module,exports){ // Glyph encoding 'use strict'; var cffStandardStrings = [ '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl', 'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', 'questiondown', 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae', 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu', 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters', 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright', 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron', 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla', 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex', 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', '266 ff', 'onedotenleader', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', 'tsuperior', 'ff', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall', 'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', 'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall', '001.000', '001.001', '001.002', '001.003', 'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold']; var cffStandardEncoding = [ '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', '', 'endash', 'dagger', 'daggerdbl', 'periodcentered', '', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', '', 'questiondown', '', 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', '', 'ring', 'cedilla', '', 'hungarumlaut', 'ogonek', 'caron', 'emdash', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'AE', '', 'ordfeminine', '', '', '', '', 'Lslash', 'Oslash', 'OE', 'ordmasculine', '', '', '', '', '', 'ae', '', '', '', 'dotlessi', '', '', 'lslash', 'oslash', 'oe', 'germandbls']; var cffExpertEncoding = [ '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader', 'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon', 'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', '', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior', 'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior', '', 'ff', 'fi', 'fl', 'ffi', 'ffl', 'parenleftinferior', '', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall', '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '', 'figuredash', 'hypheninferior', '', '', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters', 'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', '', '', 'zerosuperior', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall']; var standardNames = [ '.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave', 'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis', 'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis', 'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section', 'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute', 'dieresis', 'notequal', 'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation', 'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash', 'questiondown', 'exclamdown', 'logicalnot', 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft', 'guillemotright', 'ellipsis', 'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft', 'quotedblright', 'quoteleft', 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction', 'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase', 'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute', 'Ucircumflex', 'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar', 'Eth', 'eth', 'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply', 'onesuperior', 'twosuperior', 'threesuperior', 'onehalf', 'onequarter', 'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla', 'scedilla', 'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat']; /** * This is the encoding used for fonts created from scratch. * It loops through all glyphs and finds the appropriate unicode value. * Since it's linear time, other encodings will be faster. * @exports opentype.DefaultEncoding * @class * @constructor * @param {opentype.Font} */ function DefaultEncoding(font) { this.font = font; } DefaultEncoding.prototype.charToGlyphIndex = function(c) { var code = c.charCodeAt(0); var glyphs = this.font.glyphs; if (glyphs) { for (var i = 0; i < glyphs.length; i += 1) { var glyph = glyphs.get(i); for (var j = 0; j < glyph.unicodes.length; j += 1) { if (glyph.unicodes[j] === code) { return i; } } } } else { return null; } }; /** * @exports opentype.CmapEncoding * @class * @constructor * @param {Object} cmap - a object with the cmap encoded data */ function CmapEncoding(cmap) { this.cmap = cmap; } /** * @param {string} c - the character * @return {number} The glyph index. */ CmapEncoding.prototype.charToGlyphIndex = function(c) { return this.cmap.glyphIndexMap[c.charCodeAt(0)] || 0; }; /** * @exports opentype.CffEncoding * @class * @constructor * @param {string} encoding - The encoding * @param {Array} charset - The charcater set. */ function CffEncoding(encoding, charset) { this.encoding = encoding; this.charset = charset; } /** * @param {string} s - The character * @return {number} The index. */ CffEncoding.prototype.charToGlyphIndex = function(s) { var code = s.charCodeAt(0); var charName = this.encoding[code]; return this.charset.indexOf(charName); }; /** * @exports opentype.GlyphNames * @class * @constructor * @param {Object} post */ function GlyphNames(post) { var i; switch (post.version) { case 1: this.names = exports.standardNames.slice(); break; case 2: this.names = new Array(post.numberOfGlyphs); for (i = 0; i < post.numberOfGlyphs; i++) { if (post.glyphNameIndex[i] < exports.standardNames.length) { this.names[i] = exports.standardNames[post.glyphNameIndex[i]]; } else { this.names[i] = post.names[post.glyphNameIndex[i] - exports.standardNames.length]; } } break; case 2.5: this.names = new Array(post.numberOfGlyphs); for (i = 0; i < post.numberOfGlyphs; i++) { this.names[i] = exports.standardNames[i + post.glyphNameIndex[i]]; } break; case 3: this.names = []; break; } } /** * Gets the index of a glyph by name. * @param {string} name - The glyph name * @return {number} The index */ GlyphNames.prototype.nameToGlyphIndex = function(name) { return this.names.indexOf(name); }; /** * @param {number} gid * @return {string} */ GlyphNames.prototype.glyphIndexToName = function(gid) { return this.names[gid]; }; /** * @alias opentype.addGlyphNames * @param {opentype.Font} */ function addGlyphNames(font) { var glyph; var glyphIndexMap = font.tables.cmap.glyphIndexMap; var charCodes = Object.keys(glyphIndexMap); for (var i = 0; i < charCodes.length; i += 1) { var c = charCodes[i]; var glyphIndex = glyphIndexMap[c]; glyph = font.glyphs.get(glyphIndex); glyph.addUnicode(parseInt(c)); } for (i = 0; i < font.glyphs.length; i += 1) { glyph = font.glyphs.get(i); if (font.cffEncoding) { if (font.isCIDFont) { glyph.name = 'gid' + i; } else { glyph.name = font.cffEncoding.charset[i]; } } else if (font.glyphNames.names) { glyph.name = font.glyphNames.glyphIndexToName(i); } } } exports.cffStandardStrings = cffStandardStrings; exports.cffStandardEncoding = cffStandardEncoding; exports.cffExpertEncoding = cffExpertEncoding; exports.standardNames = standardNames; exports.DefaultEncoding = DefaultEncoding; exports.CmapEncoding = CmapEncoding; exports.CffEncoding = CffEncoding; exports.GlyphNames = GlyphNames; exports.addGlyphNames = addGlyphNames; },{}],10:[function(_dereq_,module,exports){ // The Font object 'use strict'; var path = _dereq_('./path'); var sfnt = _dereq_('./tables/sfnt'); var encoding = _dereq_('./encoding'); var glyphset = _dereq_('./glyphset'); var Substitution = _dereq_('./substitution'); var util = _dereq_('./util'); var HintingTrueType = _dereq_('./hintingtt'); /** * @typedef FontOptions * @type Object * @property {Boolean} empty - whether to create a new empty font * @property {string} familyName * @property {string} styleName * @property {string=} fullName * @property {string=} postScriptName * @property {string=} designer * @property {string=} designerURL * @property {string=} manufacturer * @property {string=} manufacturerURL * @property {string=} license * @property {string=} licenseURL * @property {string=} version * @property {string=} description * @property {string=} copyright * @property {string=} trademark * @property {Number} unitsPerEm * @property {Number} ascender * @property {Number} descender * @property {Number} createdTimestamp * @property {string=} weightClass * @property {string=} widthClass * @property {string=} fsSelection */ /** * A Font represents a loaded OpenType font file. * It contains a set of glyphs and methods to draw text on a drawing context, * or to get a path representing the text. * @exports opentype.Font * @class * @param {FontOptions} * @constructor */ function Font(options) { options = options || {}; if (!options.empty) { // Check that we've provided the minimum set of names. util.checkArgument(options.familyName, 'When creating a new Font object, familyName is required.'); util.checkArgument(options.styleName, 'When creating a new Font object, styleName is required.'); util.checkArgument(options.unitsPerEm, 'When creating a new Font object, unitsPerEm is required.'); util.checkArgument(options.ascender, 'When creating a new Font object, ascender is required.'); util.checkArgument(options.descender, 'When creating a new Font object, descender is required.'); util.checkArgument(options.descender < 0, 'Descender should be negative (e.g. -512).'); // OS X will complain if the names are empty, so we put a single space everywhere by default. this.names = { fontFamily: {en: options.familyName || ' '}, fontSubfamily: {en: options.styleName || ' '}, fullName: {en: options.fullName || options.familyName + ' ' + options.styleName}, postScriptName: {en: options.postScriptName || options.familyName + options.styleName}, designer: {en: options.designer || ' '}, designerURL: {en: options.designerURL || ' '}, manufacturer: {en: options.manufacturer || ' '}, manufacturerURL: {en: options.manufacturerURL || ' '}, license: {en: options.license || ' '}, licenseURL: {en: options.licenseURL || ' '}, version: {en: options.version || 'Version 0.1'}, description: {en: options.description || ' '}, copyright: {en: options.copyright || ' '}, trademark: {en: options.trademark || ' '} }; this.unitsPerEm = options.unitsPerEm || 1000; this.ascender = options.ascender; this.descender = options.descender; this.createdTimestamp = options.createdTimestamp; this.tables = { os2: { usWeightClass: options.weightClass || this.usWeightClasses.MEDIUM, usWidthClass: options.widthClass || this.usWidthClasses.MEDIUM, fsSelection: options.fsSelection || this.fsSelectionValues.REGULAR } }; } this.supported = true; // Deprecated: parseBuffer will throw an error if font is not supported. this.glyphs = new glyphset.GlyphSet(this, options.glyphs || []); this.encoding = new encoding.DefaultEncoding(this); this.substitution = new Substitution(this); this.tables = this.tables || {}; Object.defineProperty(this, 'hinting', { get: function() { if (this._hinting) return this._hinting; if (this.outlinesFormat === 'truetype') { return (this._hinting = new HintingTrueType(this)); } } }); } /** * Check if the font has a glyph for the given character. * @param {string} * @return {Boolean} */ Font.prototype.hasChar = function(c) { return this.encoding.charToGlyphIndex(c) !== null; }; /** * Convert the given character to a single glyph index. * Note that this function assumes that there is a one-to-one mapping between * the given character and a glyph; for complex scripts this might not be the case. * @param {string} * @return {Number} */ Font.prototype.charToGlyphIndex = function(s) { return this.encoding.charToGlyphIndex(s); }; /** * Convert the given character to a single Glyph object. * Note that this function assumes that there is a one-to-one mapping between * the given character and a glyph; for complex scripts this might not be the case. * @param {string} * @return {opentype.Glyph} */ Font.prototype.charToGlyph = function(c) { var glyphIndex = this.charToGlyphIndex(c); var glyph = this.glyphs.get(glyphIndex); if (!glyph) { // .notdef glyph = this.glyphs.get(0); } return glyph; }; /** * Convert the given text to a list of Glyph objects. * Note that there is no strict one-to-one mapping between characters and * glyphs, so the list of returned glyphs can be larger or smaller than the * length of the given string. * @param {string} * @param {GlyphRenderOptions} [options] * @return {opentype.Glyph[]} */ Font.prototype.stringToGlyphs = function(s, options) { options = options || this.defaultRenderOptions; var i; // Get glyph indexes var indexes = []; for (i = 0; i < s.length; i += 1) { var c = s[i]; indexes.push(this.charToGlyphIndex(c)); } var length = indexes.length; // Apply substitutions on glyph indexes if (options.features) { var script = options.script || this.substitution.getDefaultScriptName(); var manyToOne = []; if (options.features.liga) manyToOne = manyToOne.concat(this.substitution.getFeature('liga', script, options.language)); if (options.features.rlig) manyToOne = manyToOne.concat(this.substitution.getFeature('rlig', script, options.language)); for (i = 0; i < length; i += 1) { for (var j = 0; j < manyToOne.length; j++) { var ligature = manyToOne[j]; var components = ligature.sub; var compCount = components.length; var k = 0; while (k < compCount && components[k] === indexes[i + k]) k++; if (k === compCount) { indexes.splice(i, compCount, ligature.by); length = length - compCount + 1; } } } } // convert glyph indexes to glyph objects var glyphs = new Array(length); var notdef = this.glyphs.get(0); for (i = 0; i < length; i += 1) { glyphs[i] = this.glyphs.get(indexes[i]) || notdef; } return glyphs; }; /** * @param {string} * @return {Number} */ Font.prototype.nameToGlyphIndex = function(name) { return this.glyphNames.nameToGlyphIndex(name); }; /** * @param {string} * @return {opentype.Glyph} */ Font.prototype.nameToGlyph = function(name) { var glyphIndex = this.nameToGlyphIndex(name); var glyph = this.glyphs.get(glyphIndex); if (!glyph) { // .notdef glyph = this.glyphs.get(0); } return glyph; }; /** * @param {Number} * @return {String} */ Font.prototype.glyphIndexToName = function(gid) { if (!this.glyphNames.glyphIndexToName) { return ''; } return this.glyphNames.glyphIndexToName(gid); }; /** * Retrieve the value of the kerning pair between the left glyph (or its index) * and the right glyph (or its index). If no kerning pair is found, return 0. * The kerning value gets added to the advance width when calculating the spacing * between glyphs. * @param {opentype.Glyph} leftGlyph * @param {opentype.Glyph} rightGlyph * @return {Number} */ Font.prototype.getKerningValue = function(leftGlyph, rightGlyph) { leftGlyph = leftGlyph.index || leftGlyph; rightGlyph = rightGlyph.index || rightGlyph; var gposKerning = this.getGposKerningValue; return gposKerning ? gposKerning(leftGlyph, rightGlyph) : (this.kerningPairs[leftGlyph + ',' + rightGlyph] || 0); }; /** * @typedef GlyphRenderOptions * @type Object * @property {string} [script] - script used to determine which features to apply. By default, 'DFLT' or 'latn' is used. * See https://www.microsoft.com/typography/otspec/scripttags.htm * @property {string} [language='dflt'] - language system used to determine which features to apply. * See https://www.microsoft.com/typography/developers/opentype/languagetags.aspx * @property {boolean} [kerning=true] - whether to include kerning values * @property {object} [features] - OpenType Layout feature tags. Used to enable or disable the features of the given script/language system. * See https://www.microsoft.com/typography/otspec/featuretags.htm */ Font.prototype.defaultRenderOptions = { kerning: true, features: { liga: true, rlig: true } }; /** * Helper function that invokes the given callback for each glyph in the given text. * The callback gets `(glyph, x, y, fontSize, options)`.* @param {string} text * @param {string} text - The text to apply. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @param {Function} callback */ Font.prototype.forEachGlyph = function(text, x, y, fontSize, options, callback) { x = x !== undefined ? x : 0; y = y !== undefined ? y : 0; fontSize = fontSize !== undefined ? fontSize : 72; options = options || this.defaultRenderOptions; var fontScale = 1 / this.unitsPerEm * fontSize; var glyphs = this.stringToGlyphs(text, options); for (var i = 0; i < glyphs.length; i += 1) { var glyph = glyphs[i]; callback.call(this, glyph, x, y, fontSize, options); if (glyph.advanceWidth) { x += glyph.advanceWidth * fontScale; } if (options.kerning && i < glyphs.length - 1) { var kerningValue = this.getKerningValue(glyph, glyphs[i + 1]); x += kerningValue * fontScale; } if (options.letterSpacing) { x += options.letterSpacing * fontSize; } else if (options.tracking) { x += (options.tracking / 1000) * fontSize; } } return x; }; /** * Create a Path object that represents the given text. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @return {opentype.Path} */ Font.prototype.getPath = function(text, x, y, fontSize, options) { var fullPath = new path.Path(); this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); fullPath.extend(glyphPath); }); return fullPath; }; /** * Create an array of Path objects that represent the glyps of a given text. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @return {opentype.Path[]} */ Font.prototype.getPaths = function(text, x, y, fontSize, options) { var glyphPaths = []; this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { var glyphPath = glyph.getPath(gX, gY, gFontSize); glyphPaths.push(glyphPath); }); return glyphPaths; }; /** * Returns the advance width of a text. * * This is something different than Path.getBoundingBox() as for example a * suffixed whitespace increases the advancewidth but not the bounding box * or an overhanging letter like a calligraphic 'f' might have a quite larger * bounding box than its advance width. * * This corresponds to canvas2dContext.measureText(text).width * * @param {string} text - The text to create. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @return advance width */ Font.prototype.getAdvanceWidth = function(text, fontSize, options) { return this.forEachGlyph(text, 0, 0, fontSize, options, function() {}); }; /** * Draw the text on the given drawing context. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */ Font.prototype.draw = function(ctx, text, x, y, fontSize, options) { this.getPath(text, x, y, fontSize, options).draw(ctx); }; /** * Draw the points of all glyphs in the text. * On-curve points will be drawn in blue, off-curve points will be drawn in red. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */ Font.prototype.drawPoints = function(ctx, text, x, y, fontSize, options) { this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { glyph.drawPoints(ctx, gX, gY, gFontSize); }); }; /** * Draw lines indicating important font measurements for all glyphs in the text. * Black lines indicate the origin of the coordinate system (point 0,0). * Blue lines indicate the glyph bounding box. * Green line indicates the advance width of the glyph. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */ Font.prototype.drawMetrics = function(ctx, text, x, y, fontSize, options) { this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { glyph.drawMetrics(ctx, gX, gY, gFontSize); }); }; /** * @param {string} * @return {string} */ Font.prototype.getEnglishName = function(name) { var translations = this.names[name]; if (translations) { return translations.en; } }; /** * Validate */ Font.prototype.validate = function() { var warnings = []; var _this = this; function assert(predicate, message) { if (!predicate) { warnings.push(message); } } function assertNamePresent(name) { var englishName = _this.getEnglishName(name); assert(englishName && englishName.trim().length > 0, 'No English ' + name + ' specified.'); } // Identification information assertNamePresent('fontFamily'); assertNamePresent('weightName'); assertNamePresent('manufacturer'); assertNamePresent('copyright'); assertNamePresent('version'); // Dimension information assert(this.unitsPerEm > 0, 'No unitsPerEm specified.'); }; /** * Convert the font object to a SFNT data structure. * This structure contains all the necessary tables and metadata to create a binary OTF file. * @return {opentype.Table} */ Font.prototype.toTables = function() { return sfnt.fontToTable(this); }; /** * @deprecated Font.toBuffer is deprecated. Use Font.toArrayBuffer instead. */ Font.prototype.toBuffer = function() { console.warn('Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.'); return this.toArrayBuffer(); }; /** * Converts a `opentype.Font` into an `ArrayBuffer` * @return {ArrayBuffer} */ Font.prototype.toArrayBuffer = function() { var sfntTable = this.toTables(); var bytes = sfntTable.encode(); var buffer = new ArrayBuffer(bytes.length); var intArray = new Uint8Array(buffer); for (var i = 0; i < bytes.length; i++) { intArray[i] = bytes[i]; } return buffer; }; /** * Initiate a download of the OpenType font. */ Font.prototype.download = function(fileName) { var familyName = this.getEnglishName('fontFamily'); var styleName = this.getEnglishName('fontSubfamily'); fileName = fileName || familyName.replace(/\s/g, '') + '-' + styleName + '.otf'; var arrayBuffer = this.toArrayBuffer(); if (util.isBrowser()) { window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.requestFileSystem(window.TEMPORARY, arrayBuffer.byteLength, function(fs) { fs.root.getFile(fileName, {create: true}, function(fileEntry) { fileEntry.createWriter(function(writer) { var dataView = new DataView(arrayBuffer); var blob = new Blob([dataView], {type: 'font/opentype'}); writer.write(blob); writer.addEventListener('writeend', function() { // Navigating to the file will download it. location.href = fileEntry.toURL(); }, false); }); }); }, function(err) { throw new Error(err.name + ': ' + err.message); }); } else { var fs = _dereq_('fs'); var buffer = util.arrayBufferToNodeBuffer(arrayBuffer); fs.writeFileSync(fileName, buffer); } }; /** * @private */ Font.prototype.fsSelectionValues = { ITALIC: 0x001, //1 UNDERSCORE: 0x002, //2 NEGATIVE: 0x004, //4 OUTLINED: 0x008, //8 STRIKEOUT: 0x010, //16 BOLD: 0x020, //32 REGULAR: 0x040, //64 USER_TYPO_METRICS: 0x080, //128 WWS: 0x100, //256 OBLIQUE: 0x200 //512 }; /** * @private */ Font.prototype.usWidthClasses = { ULTRA_CONDENSED: 1, EXTRA_CONDENSED: 2, CONDENSED: 3, SEMI_CONDENSED: 4, MEDIUM: 5, SEMI_EXPANDED: 6, EXPANDED: 7, EXTRA_EXPANDED: 8, ULTRA_EXPANDED: 9 }; /** * @private */ Font.prototype.usWeightClasses = { THIN: 100, EXTRA_LIGHT: 200, LIGHT: 300, NORMAL: 400, MEDIUM: 500, SEMI_BOLD: 600, BOLD: 700, EXTRA_BOLD: 800, BLACK: 900 }; exports.Font = Font; },{"./encoding":9,"./glyphset":12,"./hintingtt":13,"./path":17,"./substitution":18,"./tables/sfnt":37,"./util":39,"fs":2}],11:[function(_dereq_,module,exports){ // The Glyph object 'use strict'; var check = _dereq_('./check'); var draw = _dereq_('./draw'); var path = _dereq_('./path'); var glyf = _dereq_('./tables/glyf'); function getPathDefinition(glyph, path) { var _path = path || { commands: [] }; return { configurable: true, get: function() { if (typeof _path === 'function') { _path = _path(); } return _path; }, set: function(p) { _path = p; } }; } /** * @typedef GlyphOptions * @type Object * @property {string} [name] - The glyph name * @property {number} [unicode] * @property {Array} [unicodes] * @property {number} [xMin] * @property {number} [yMin] * @property {number} [xMax] * @property {number} [yMax] * @property {number} [advanceWidth] */ // A Glyph is an individual mark that often corresponds to a character. // Some glyphs, such as ligatures, are a combination of many characters. // Glyphs are the basic building blocks of a font. // // The `Glyph` class contains utility methods for drawing the path and its points. /** * @exports opentype.Glyph * @class * @param {GlyphOptions} * @constructor */ function Glyph(options) { // By putting all the code on a prototype function (which is only declared once) // we reduce the memory requirements for larger fonts by some 2% this.bindConstructorValues(options); } /** * @param {GlyphOptions} */ Glyph.prototype.bindConstructorValues = function(options) { this.index = options.index || 0; // These three values cannnot be deferred for memory optimization: this.name = options.name || null; this.unicode = options.unicode || undefined; this.unicodes = options.unicodes || options.unicode !== undefined ? [options.unicode] : []; // But by binding these values only when necessary, we reduce can // the memory requirements by almost 3% for larger fonts. if (options.xMin) { this.xMin = options.xMin; } if (options.yMin) { this.yMin = options.yMin; } if (options.xMax) { this.xMax = options.xMax; } if (options.yMax) { this.yMax = options.yMax; } if (options.advanceWidth) { this.advanceWidth = options.advanceWidth; } // The path for a glyph is the most memory intensive, and is bound as a value // with a getter/setter to ensure we actually do path parsing only once the // path is actually needed by anything. Object.defineProperty(this, 'path', getPathDefinition(this, options.path)); }; /** * @param {number} */ Glyph.prototype.addUnicode = function(unicode) { if (this.unicodes.length === 0) { this.unicode = unicode; } this.unicodes.push(unicode); }; /** * Calculate the minimum bounding box for this glyph. * @return {opentype.BoundingBox} */ Glyph.prototype.getBoundingBox = function() { return this.path.getBoundingBox(); }; /** * Convert the glyph to a Path we can draw on a drawing context. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {Object=} options - xScale, yScale to strech the glyph. * @param {opentype.Font} if hinting is to be used, the font * @return {opentype.Path} */ Glyph.prototype.getPath = function(x, y, fontSize, options, font) { x = x !== undefined ? x : 0; y = y !== undefined ? y : 0; fontSize = fontSize !== undefined ? fontSize : 72; var commands; var hPoints; if (!options) options = { }; var xScale = options.xScale; var yScale = options.yScale; if (options.hinting && font && font.hinting) { // in case of hinting, the hinting engine takes care // of scaling the points (not the path) before hinting. hPoints = this.path && font.hinting.exec(this, fontSize); // in case the hinting engine failed hPoints is undefined // and thus reverts to plain rending } if (hPoints) { commands = glyf.getPath(hPoints).commands; x = Math.round(x); y = Math.round(y); // TODO in case of hinting xyScaling is not yet supported xScale = yScale = 1; } else { commands = this.path.commands; var scale = 1 / this.path.unitsPerEm * fontSize; if (xScale === undefined) xScale = scale; if (yScale === undefined) yScale = scale; } var p = new path.Path(); for (var i = 0; i < commands.length; i += 1) { var cmd = commands[i]; if (cmd.type === 'M') { p.moveTo(x + (cmd.x * xScale), y + (-cmd.y * yScale)); } else if (cmd.type === 'L') { p.lineTo(x + (cmd.x * xScale), y + (-cmd.y * yScale)); } else if (cmd.type === 'Q') { p.quadraticCurveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale), x + (cmd.x * xScale), y + (-cmd.y * yScale)); } else if (cmd.type === 'C') { p.curveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale), x + (cmd.x2 * xScale), y + (-cmd.y2 * yScale), x + (cmd.x * xScale), y + (-cmd.y * yScale)); } else if (cmd.type === 'Z') { p.closePath(); } } return p; }; /** * Split the glyph into contours. * This function is here for backwards compatibility, and to * provide raw access to the TrueType glyph outlines. * @return {Array} */ Glyph.prototype.getContours = function() { if (this.points === undefined) { return []; } var contours = []; var currentContour = []; for (var i = 0; i < this.points.length; i += 1) { var pt = this.points[i]; currentContour.push(pt); if (pt.lastPointOfContour) { contours.push(currentContour); currentContour = []; } } check.argument(currentContour.length === 0, 'There are still points left in the current contour.'); return contours; }; /** * Calculate the xMin/yMin/xMax/yMax/lsb/rsb for a Glyph. * @return {Object} */ Glyph.prototype.getMetrics = function() { var commands = this.path.commands; var xCoords = []; var yCoords = []; for (var i = 0; i < commands.length; i += 1) { var cmd = commands[i]; if (cmd.type !== 'Z') { xCoords.push(cmd.x); yCoords.push(cmd.y); } if (cmd.type === 'Q' || cmd.type === 'C') { xCoords.push(cmd.x1); yCoords.push(cmd.y1); } if (cmd.type === 'C') { xCoords.push(cmd.x2); yCoords.push(cmd.y2); } } var metrics = { xMin: Math.min.apply(null, xCoords), yMin: Math.min.apply(null, yCoords), xMax: Math.max.apply(null, xCoords), yMax: Math.max.apply(null, yCoords), leftSideBearing: this.leftSideBearing }; if (!isFinite(metrics.xMin)) { metrics.xMin = 0; } if (!isFinite(metrics.xMax)) { metrics.xMax = this.advanceWidth; } if (!isFinite(metrics.yMin)) { metrics.yMin = 0; } if (!isFinite(metrics.yMax)) { metrics.yMax = 0; } metrics.rightSideBearing = this.advanceWidth - metrics.leftSideBearing - (metrics.xMax - metrics.xMin); return metrics; }; /** * Draw the glyph on the given context. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {Object=} options - xScale, yScale to strech the glyph. */ Glyph.prototype.draw = function(ctx, x, y, fontSize, options) { this.getPath(x, y, fontSize, options).draw(ctx); }; /** * Draw the points of the glyph. * On-curve points will be drawn in blue, off-curve points will be drawn in red. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. */ Glyph.prototype.drawPoints = function(ctx, x, y, fontSize) { function drawCircles(l, x, y, scale) { var PI_SQ = Math.PI * 2; ctx.beginPath(); for (var j = 0; j < l.length; j += 1) { ctx.moveTo(x + (l[j].x * scale), y + (l[j].y * scale)); ctx.arc(x + (l[j].x * scale), y + (l[j].y * scale), 2, 0, PI_SQ, false); } ctx.closePath(); ctx.fill(); } x = x !== undefined ? x : 0; y = y !== undefined ? y : 0; fontSize = fontSize !== undefined ? fontSize : 24; var scale = 1 / this.path.unitsPerEm * fontSize; var blueCircles = []; var redCircles = []; var path = this.path; for (var i = 0; i < path.commands.length; i += 1) { var cmd = path.commands[i]; if (cmd.x !== undefined) { blueCircles.push({x: cmd.x, y: -cmd.y}); } if (cmd.x1 !== undefined) { redCircles.push({x: cmd.x1, y: -cmd.y1}); } if (cmd.x2 !== undefined) { redCircles.push({x: cmd.x2, y: -cmd.y2}); } } ctx.fillStyle = 'blue'; drawCircles(blueCircles, x, y, scale); ctx.fillStyle = 'red'; drawCircles(redCircles, x, y, scale); }; /** * Draw lines indicating important font measurements. * Black lines indicate the origin of the coordinate system (point 0,0). * Blue lines indicate the glyph bounding box. * Green line indicates the advance width of the glyph. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. */ Glyph.prototype.drawMetrics = function(ctx, x, y, fontSize) { var scale; x = x !== undefined ? x : 0; y = y !== undefined ? y : 0; fontSize = fontSize !== undefined ? fontSize : 24; scale = 1 / this.path.unitsPerEm * fontSize; ctx.lineWidth = 1; // Draw the origin ctx.strokeStyle = 'black'; draw.line(ctx, x, -10000, x, 10000); draw.line(ctx, -10000, y, 10000, y); // This code is here due to memory optimization: by not using // defaults in the constructor, we save a notable amount of memory. var xMin = this.xMin || 0; var yMin = this.yMin || 0; var xMax = this.xMax || 0; var yMax = this.yMax || 0; var advanceWidth = this.advanceWidth || 0; // Draw the glyph box ctx.strokeStyle = 'blue'; draw.line(ctx, x + (xMin * scale), -10000, x + (xMin * scale), 10000); draw.line(ctx, x + (xMax * scale), -10000, x + (xMax * scale), 10000); draw.line(ctx, -10000, y + (-yMin * scale), 10000, y + (-yMin * scale)); draw.line(ctx, -10000, y + (-yMax * scale), 10000, y + (-yMax * scale)); // Draw the advance width ctx.strokeStyle = 'green'; draw.line(ctx, x + (advanceWidth * scale), -10000, x + (advanceWidth * scale), 10000); }; exports.Glyph = Glyph; },{"./check":7,"./draw":8,"./path":17,"./tables/glyf":23}],12:[function(_dereq_,module,exports){ // The GlyphSet object 'use strict'; var _glyph = _dereq_('./glyph'); // Define a property on the glyph that depends on the path being loaded. function defineDependentProperty(glyph, externalName, internalName) { Object.defineProperty(glyph, externalName, { get: function() { // Request the path property to make sure the path is loaded. glyph.path; // jshint ignore:line return glyph[internalName]; }, set: function(newValue) { glyph[internalName] = newValue; }, enumerable: true, configurable: true }); } /** * A GlyphSet represents all glyphs available in the font, but modelled using * a deferred glyph loader, for retrieving glyphs only once they are absolutely * necessary, to keep the memory footprint down. * @exports opentype.GlyphSet * @class * @param {opentype.Font} * @param {Array} */ function GlyphSet(font, glyphs) { this.font = font; this.glyphs = {}; if (Array.isArray(glyphs)) { for (var i = 0; i < glyphs.length; i++) { this.glyphs[i] = glyphs[i]; } } this.length = (glyphs && glyphs.length) || 0; } /** * @param {number} index * @return {opentype.Glyph} */ GlyphSet.prototype.get = function(index) { if (typeof this.glyphs[index] === 'function') { this.glyphs[index] = this.glyphs[index](); } return this.glyphs[index]; }; /** * @param {number} index * @param {Object} */ GlyphSet.prototype.push = function(index, loader) { this.glyphs[index] = loader; this.length++; }; /** * @alias opentype.glyphLoader * @param {opentype.Font} font * @param {number} index * @return {opentype.Glyph} */ function glyphLoader(font, index) { return new _glyph.Glyph({index: index, font: font}); } /** * Generate a stub glyph that can be filled with all metadata *except* * the "points" and "path" properties, which must be loaded only once * the glyph's path is actually requested for text shaping. * @alias opentype.ttfGlyphLoader * @param {opentype.Font} font * @param {number} index * @param {Function} parseGlyph * @param {Object} data * @param {number} position * @param {Function} buildPath * @return {opentype.Glyph} */ function ttfGlyphLoader(font, index, parseGlyph, data, position, buildPath) { return function() { var glyph = new _glyph.Glyph({index: index, font: font}); glyph.path = function() { parseGlyph(glyph, data, position); var path = buildPath(font.glyphs, glyph); path.unitsPerEm = font.unitsPerEm; return path; }; defineDependentProperty(glyph, 'xMin', '_xMin'); defineDependentProperty(glyph, 'xMax', '_xMax'); defineDependentProperty(glyph, 'yMin', '_yMin'); defineDependentProperty(glyph, 'yMax', '_yMax'); return glyph; }; } /** * @alias opentype.cffGlyphLoader * @param {opentype.Font} font * @param {number} index * @param {Function} parseCFFCharstring * @param {string} charstring * @return {opentype.Glyph} */ function cffGlyphLoader(font, index, parseCFFCharstring, charstring) { return function() { var glyph = new _glyph.Glyph({index: index, font: font}); glyph.path = function() { var path = parseCFFCharstring(font, glyph, charstring); path.unitsPerEm = font.unitsPerEm; return path; }; return glyph; }; } exports.GlyphSet = GlyphSet; exports.glyphLoader = glyphLoader; exports.ttfGlyphLoader = ttfGlyphLoader; exports.cffGlyphLoader = cffGlyphLoader; },{"./glyph":11}],13:[function(_dereq_,module,exports){ /* A TrueType font hinting interpreter. * * (c) 2017 Axel Kittenberger * * This interpreter has been implemented according to this documentation: * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM05/Chap5.html * * According to the documentation F24DOT6 values are used for pixels. * That means calculation is 1/64 pixel accurate and uses integer operations. * However, Javascript has floating point operations by default and only * those are available. One could make a case to simulate the 1/64 accuracy * exactly by truncating after every division operation * (for example with << 0) to get pixel exacty results as other TrueType * implementations. It may make sense since some fonts are pixel optimized * by hand using DELTAP instructions. The current implementation doesn't * and rather uses full floating point precission. * * xScale, yScale and rotation is currently ignored. * * A few non-trivial instructions are missing as I didn't encounter yet * a font that used them to test a possible implementation. * * Some fonts seem to use undocumented features regarding the twilight zone. * Only some of them are implemented as they were encountered. * * The DEBUG statements can be removed, manually or for example with "uglify" * fixing DEBUG to false. */ 'use strict'; var DEBUG = false; var instructionTable; var exec; var execComponent; var execGlyph; /* * Creates a hinting object. * * There ought to be exactly one * for each truetype font that is used for hinting. */ function Hinting(font) { // the font this hinting object is for this.font = font; // cached states this._fpgmState = this._prepState = undefined; // errorState // 0 ... all okay // 1 ... had an error in a glyf, // continue working but stop spamming // the console // 2 ... error at prep, stop hinting at this ppem // 3 ... error at fpeg, stop hinting for this font at all this._errorState = 0; } /* * Not rounding. */ function roundOff(v) { return v; } /* * Rounding to grid. */ function roundToGrid(v) { //Rounding in TT is supposed to "symmetrical around zero" return Math.sign(v) * Math.round(Math.abs(v)); } /* * Rounding to double grid. */ function roundToDoubleGrid(v) { return Math.sign(v) * Math.round(Math.abs(v * 2)) / 2; } /* * Rounding to half grid. */ function roundToHalfGrid(v) { return Math.sign(v) * (Math.round(Math.abs(v) + 0.5) - 0.5); } /* * Rounding to up to grid. */ function roundUpToGrid(v) { return Math.sign(v) * Math.ceil(Math.abs(v)); } /* * Rounding to down to grid. */ function roundDownToGrid(v) { return Math.sign(v) * Math.floor(Math.abs(v)); } /* * Super rounding. */ var roundSuper = function(v) { var period = this.srPeriod; var phase = this.srPhase; var threshold = this.srThreshold; var sign = 1; if (v < 0) { v = -v; sign = -1; } v += threshold - phase; v = Math.trunc(v / period) * period; v += phase; // according to http://xgridfit.sourceforge.net/round.html if (sign > 0 && v < 0) return phase; if (sign < 0 && v > 0) return -phase; return v * sign; }; /* * Unit vector of x-axis. */ var xUnitVector = { x: 1, y: 0, axis: 'x', // Gets the projected distance between two points. // o1/o2 ... if true, respective original position is used. distance: function(p1, p2, o1, o2) { return (o1 ? p1.xo : p1.x) - (o2 ? p2.xo : p2.x); }, // Moves point p so the moved position has the same relative // position to the moved positions of rp1 and rp2 than the // original positions had. // // See APPENDIX on INTERPOLATE at the bottom of this file. interpolate: function(p, rp1, rp2, pv) { var do1; var do2; var doa1; var doa2; var dm1; var dm2; var dt; if (!pv || pv === this) { do1 = p.xo - rp1.xo; do2 = p.xo - rp2.xo; dm1 = rp1.x - rp1.xo; dm2 = rp2.x - rp2.xo; doa1 = Math.abs(do1); doa2 = Math.abs(do2); dt = doa1 + doa2; if (dt === 0) { p.x = p.xo + (dm1 + dm2) / 2; return; } p.x = p.xo + (dm1 * doa2 + dm2 * doa1) / dt; return; } do1 = pv.distance(p, rp1, true, true); do2 = pv.distance(p, rp2, true, true); dm1 = pv.distance(rp1, rp1, false, true); dm2 = pv.distance(rp2, rp2, false, true); doa1 = Math.abs(do1); doa2 = Math.abs(do2); dt = doa1 + doa2; if (dt === 0) { xUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); return; } xUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); }, // Slope of line normal to this normalSlope: Number.NEGATIVE_INFINITY, // Sets the point 'p' relative to point 'rp' // by the distance 'd'. // // See APPENDIX on SETRELATIVE at the bottom of this file. // // p ... point to set // rp ... reference point // d ... distance on projection vector // pv ... projection vector (undefined = this) // org ... if true, uses the original position of rp as reference. setRelative: function(p, rp, d, pv, org) { if (!pv || pv === this) { p.x = (org ? rp.xo : rp.x) + d; return; } var rpx = org ? rp.xo : rp.x; var rpy = org ? rp.yo : rp.y; var rpdx = rpx + d * pv.x; var rpdy = rpy + d * pv.y; p.x = rpdx + (p.y - rpdy) / pv.normalSlope; }, // Slope of vector line. slope: 0, // Touches the point p. touch: function(p) { p.xTouched = true; }, // Tests if a point p is touched. touched: function(p) { return p.xTouched; }, // Untouches the point p. untouch: function(p) { p.xTouched = false; } }; /* * Unit vector of y-axis. */ var yUnitVector = { x: 0, y: 1, axis: 'y', // Gets the projected distance between two points. // o1/o2 ... if true, respective original position is used. distance: function(p1, p2, o1, o2) { return (o1 ? p1.yo : p1.y) - (o2 ? p2.yo : p2.y); }, // Moves point p so the moved position has the same relative // position to the moved positions of rp1 and rp2 than the // original positions had. // // See APPENDIX on INTERPOLATE at the bottom of this file. interpolate: function(p, rp1, rp2, pv) { var do1; var do2; var doa1; var doa2; var dm1; var dm2; var dt; if (!pv || pv === this) { do1 = p.yo - rp1.yo; do2 = p.yo - rp2.yo; dm1 = rp1.y - rp1.yo; dm2 = rp2.y - rp2.yo; doa1 = Math.abs(do1); doa2 = Math.abs(do2); dt = doa1 + doa2; if (dt === 0) { p.y = p.yo + (dm1 + dm2) / 2; return; } p.y = p.yo + (dm1 * doa2 + dm2 * doa1) / dt; return; } do1 = pv.distance(p, rp1, true, true); do2 = pv.distance(p, rp2, true, true); dm1 = pv.distance(rp1, rp1, false, true); dm2 = pv.distance(rp2, rp2, false, true); doa1 = Math.abs(do1); doa2 = Math.abs(do2); dt = doa1 + doa2; if (dt === 0) { yUnitVector.setRelative(p, p, (dm1 + dm2) / 2, pv, true); return; } yUnitVector.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); }, // Slope of line normal to this. normalSlope: 0, // Sets the point 'p' relative to point 'rp' // by the distance 'd' // // See APPENDIX on SETRELATIVE at the bottom of this file. // // p ... point to set // rp ... reference point // d ... distance on projection vector // pv ... projection vector (undefined = this) // org ... if true, uses the original position of rp as reference. setRelative: function(p, rp, d, pv, org) { if (!pv || pv === this) { p.y = (org ? rp.yo : rp.y) + d; return; } var rpx = org ? rp.xo : rp.x; var rpy = org ? rp.yo : rp.y; var rpdx = rpx + d * pv.x; var rpdy = rpy + d * pv.y; p.y = rpdy + pv.normalSlope * (p.x - rpdx); }, // Slope of vector line. slope: Number.POSITIVE_INFINITY, // Touches the point p. touch: function(p) { p.yTouched = true; }, // Tests if a point p is touched. touched: function(p) { return p.yTouched; }, // Untouches the point p. untouch: function(p) { p.yTouched = false; } }; Object.freeze(xUnitVector); Object.freeze(yUnitVector); /* * Creates a unit vector that is not x- or y-axis. */ function UnitVector(x, y) { this.x = x; this.y = y; this.axis = undefined; this.slope = y / x; this.normalSlope = -x / y; Object.freeze(this); } /* * Gets the projected distance between two points. * o1/o2 ... if true, respective original position is used. */ UnitVector.prototype.distance = function(p1, p2, o1, o2) { return ( this.x * xUnitVector.distance(p1, p2, o1, o2) + this.y * yUnitVector.distance(p1, p2, o1, o2) ); }; /* * Moves point p so the moved position has the same relative * position to the moved positions of rp1 and rp2 than the * original positions had. * * See APPENDIX on INTERPOLATE at the bottom of this file. */ UnitVector.prototype.interpolate = function(p, rp1, rp2, pv) { var dm1; var dm2; var do1; var do2; var doa1; var doa2; var dt; do1 = pv.distance(p, rp1, true, true); do2 = pv.distance(p, rp2, true, true); dm1 = pv.distance(rp1, rp1, false, true); dm2 = pv.distance(rp2, rp2, false, true); doa1 = Math.abs(do1); doa2 = Math.abs(do2); dt = doa1 + doa2; if (dt === 0) { this.setRelative(p, p, (dm1 + dm2) / 2, pv, true); return; } this.setRelative(p, p, (dm1 * doa2 + dm2 * doa1) / dt, pv, true); }; /* * Sets the point 'p' relative to point 'rp' * by the distance 'd' * * See APPENDIX on SETRELATIVE at the bottom of this file. * * p ... point to set * rp ... reference point * d ... distance on projection vector * pv ... projection vector (undefined = this) * org ... if true, uses the original position of rp as reference. */ UnitVector.prototype.setRelative = function(p, rp, d, pv, org) { pv = pv || this; var rpx = org ? rp.xo : rp.x; var rpy = org ? rp.yo : rp.y; var rpdx = rpx + d * pv.x; var rpdy = rpy + d * pv.y; var pvns = pv.normalSlope; var fvs = this.slope; var px = p.x; var py = p.y; p.x = (fvs * px - pvns * rpdx + rpdy - py) / (fvs - pvns); p.y = fvs * (p.x - px) + py; }; /* * Touches the point p. */ UnitVector.prototype.touch = function(p) { p.xTouched = true; p.yTouched = true; }; /* * Returns a unit vector with x/y coordinates. */ function getUnitVector(x, y) { var d = Math.sqrt(x * x + y * y); x /= d; y /= d; if (x === 1 && y === 0) return xUnitVector; else if (x === 0 && y === 1) return yUnitVector; else return new UnitVector(x, y); } /* * Creates a point in the hinting engine. */ function HPoint( x, y, lastPointOfContour, onCurve ) { this.x = this.xo = Math.round(x * 64) / 64; // hinted x value and original x-value this.y = this.yo = Math.round(y * 64) / 64; // hinted y value and original y-value this.lastPointOfContour = lastPointOfContour; this.onCurve = onCurve; this.prevPointOnContour = undefined; this.nextPointOnContour = undefined; this.xTouched = false; this.yTouched = false; Object.preventExtensions(this); } /* * Returns the next touched point on the contour. * * v ... unit vector to test touch axis. */ HPoint.prototype.nextTouched = function(v) { var p = this.nextPointOnContour; while (!v.touched(p) && p !== this) p = p.nextPointOnContour; return p; }; /* * Returns the previous touched point on the contour * * v ... unit vector to test touch axis. */ HPoint.prototype.prevTouched = function(v) { var p = this.prevPointOnContour; while (!v.touched(p) && p !== this) p = p.prevPointOnContour; return p; }; /* * The zero point. */ var HPZero = Object.freeze(new HPoint(0, 0)); /* * The default state of the interpreter. * * Note: Freezing the defaultState and then deriving from it * makes the V8 Javascript engine going akward, * so this is avoided, albeit the defaultState shouldn't * ever change. */ var defaultState = { cvCutIn: 17 / 16, // control value cut in deltaBase: 9, deltaShift: 0.125, loop: 1, // loops some instructions minDis: 1, // minimum distance autoFlip: true }; /* * The current state of the interpreter. * * env ... 'fpgm' or 'prep' or 'glyf' * prog ... the program */ function State(env, prog) { this.env = env; this.stack = []; this.prog = prog; switch (env) { case 'glyf' : this.zp0 = this.zp1 = this.zp2 = 1; this.rp0 = this.rp1 = this.rp2 = 0; /* fall through */ case 'prep' : this.fv = this.pv = this.dpv = xUnitVector; this.round = roundToGrid; } } /* * Executes a glyph program. * * This does the hinting for each glyph. * * Returns an array of moved points. * * glyph: the glyph to hint * ppem: the size the glyph is rendered for */ Hinting.prototype.exec = function(glyph, ppem) { if (typeof ppem !== 'number') { throw new Error('Point size is not a number!'); } // Received a fatal error, don't do any hinting anymore. if (this._errorState > 2) return; var font = this.font; var prepState = this._prepState; if (!prepState || prepState.ppem !== ppem) { var fpgmState = this._fpgmState; if (!fpgmState) { // Executes the fpgm state. // This is used by fonts to define functions. State.prototype = defaultState; fpgmState = this._fpgmState = new State('fpgm', font.tables.fpgm); fpgmState.funcs = [ ]; fpgmState.font = font; if (DEBUG) { console.log('---EXEC FPGM---'); fpgmState.step = -1; } try { exec(fpgmState); } catch (e) { console.log('Hinting error in FPGM:' + e); this._errorState = 3; return; } } // Executes the prep program for this ppem setting. // This is used by fonts to set cvt values // depending on to be rendered font size. State.prototype = fpgmState; prepState = this._prepState = new State('prep', font.tables.prep); prepState.ppem = ppem; // Creates a copy of the cvt table // and scales it to the current ppem setting. var oCvt = font.tables.cvt; if (oCvt) { var cvt = prepState.cvt = new Array(oCvt.length); var scale = ppem / font.unitsPerEm; for (var c = 0; c < oCvt.length; c++) { cvt[c] = oCvt[c] * scale; } } else { prepState.cvt = []; } if (DEBUG) { console.log('---EXEC PREP---'); prepState.step = -1; } try { exec(prepState); } catch (e) { if (this._errorState < 2) { console.log('Hinting error in PREP:' + e); } this._errorState = 2; } } if (this._errorState > 1) return; try { return execGlyph(glyph, prepState); } catch (e) { if (this._errorState < 1) { console.log('Hinting error:' + e); console.log('Note: further hinting errors are silenced'); } this._errorState = 1; return; } }; /* * Executes the hinting program for a glyph. */ function execGlyph(glyph, prepState) { // original point positions var xScale = prepState.ppem / prepState.font.unitsPerEm; var yScale = xScale; var components = glyph.components; var contours; var gZone; var state; State.prototype = prepState; if (!components) { state = new State('glyf', glyph.instructions); if (DEBUG) { console.log('---EXEC GLYPH---'); state.step = -1; } execComponent(glyph, state, xScale, yScale); gZone = state.gZone; } else { var font = prepState.font; gZone = []; contours = []; for (var i = 0; i < components.length; i++) { var c = components[i]; var cg = font.glyphs.get(c.glyphIndex); state = new State('glyf', cg.instructions); if (DEBUG) { console.log('---EXEC COMP ' + i + '---'); state.step = -1; } execComponent(cg, state, xScale, yScale); // appends the computed points to the result array // post processes the component points var dx = Math.round(c.dx * xScale); var dy = Math.round(c.dy * yScale); var gz = state.gZone; var cc = state.contours; for (var pi = 0; pi < gz.length; pi++) { var p = gz[pi]; p.xTouched = p.yTouched = false; p.xo = p.x = p.x + dx; p.yo = p.y = p.y + dy; } var gLen = gZone.length; gZone.push.apply(gZone, gz); for (var j = 0; j < cc.length; j++) { contours.push(cc[j] + gLen); } } if (glyph.instructions && !state.inhibitGridFit) { // the composite has instructions on its own state = new State('glyf', glyph.instructions); state.gZone = state.z0 = state.z1 = state.z2 = gZone; state.contours = contours; // note: HPZero cannot be used here, since // the point might be modified gZone.push( new HPoint(0, 0), new HPoint(Math.round(glyph.advanceWidth * xScale), 0) ); if (DEBUG) { console.log('---EXEC COMPOSITE---'); state.step = -1; } exec(state); gZone.length -= 2; } } return gZone; } /* * Executes the hinting program for a componenet of a multi-component glyph * or of the glyph itself by a non-component glyph. */ function execComponent(glyph, state, xScale, yScale) { var points = glyph.points || []; var pLen = points.length; var gZone = state.gZone = state.z0 = state.z1 = state.z2 = []; var contours = state.contours = []; var i; // Scales the original points and // makes copies for the hinted points. var cp; // current point for (i = 0; i < pLen; i++) { cp = points[i]; gZone[i] = new HPoint( cp.x * xScale, cp.y * yScale, cp.lastPointOfContour, cp.onCurve ); } // Chain links the contours. var sp; // start point var np; // next point for (i = 0; i < pLen; i++) { cp = gZone[i]; if (!sp) { sp = cp; contours.push(i); } if (cp.lastPointOfContour) { cp.nextPointOnContour = sp; sp.prevPointOnContour = cp; sp = undefined; } else { np = gZone[i + 1]; cp.nextPointOnContour = np; np.prevPointOnContour = cp; } } if (state.inhibitGridFit) return; gZone.push( new HPoint(0, 0), new HPoint(Math.round(glyph.advanceWidth * xScale), 0) ); exec(state); // Removes the extra points. gZone.length -= 2; if (DEBUG) { console.log('FINISHED GLYPH', state.stack); for (i = 0; i < pLen; i++) { console.log(i, gZone[i].x, gZone[i].y); } } } /* * Executes the program loaded in state. */ function exec(state) { var prog = state.prog; if (!prog) return; var pLen = prog.length; var ins; for (state.ip = 0; state.ip < pLen; state.ip++) { if (DEBUG) state.step++; ins = instructionTable[prog[state.ip]]; if (!ins) { throw new Error( 'unknown instruction: 0x' + Number(prog[state.ip]).toString(16) ); } ins(state); // very extensive debugging for each step /* if (DEBUG) { var da; var i; if (state.gZone) { da = []; for (i = 0; i < state.gZone.length; i++) { da.push(i + ' ' + state.gZone[i].x * 64 + ' ' + state.gZone[i].y * 64 + ' ' + (state.gZone[i].xTouched ? 'x' : '') + (state.gZone[i].yTouched ? 'y' : '') ); } console.log('GZ', da); } if (state.tZone) { da = []; for (i = 0; i < state.tZone.length; i++) { da.push(i + ' ' + state.tZone[i].x * 64 + ' ' + state.tZone[i].y * 64 + ' ' + (state.tZone[i].xTouched ? 'x' : '') + (state.tZone[i].yTouched ? 'y' : '') ); } console.log('TZ', da); } if (state.stack.length > 10) { console.log( state.stack.length, '...', state.stack.slice(state.stack.length - 10) ); } else { console.log(state.stack.length, state.stack); } } */ } } /* * Initializes the twilight zone. * * This is only done if a SZPx instruction * refers to the twilight zone. */ function initTZone(state) { var tZone = state.tZone = new Array(state.gZone.length); // no idea if this is actually correct... for (var i = 0; i < tZone.length; i++) { tZone[i] = new HPoint(0, 0); } } /* * Skips the instruction pointer ahead over an IF/ELSE block. * handleElse .. if true breaks on mathing ELSE */ function skip(state, handleElse) { var prog = state.prog; var ip = state.ip; var nesting = 1; var ins; do { ins = prog[++ip]; if (ins === 0x58) // IF nesting++; else if (ins === 0x59) // EIF nesting--; else if (ins === 0x40) // NPUSHB ip += prog[ip + 1] + 1; else if (ins === 0x41) // NPUSHW ip += 2 * prog[ip + 1] + 1; else if (ins >= 0xB0 && ins <= 0xB7) // PUSHB ip += ins - 0xB0 + 1; else if (ins >= 0xB8 && ins <= 0xBF) // PUSHW ip += (ins - 0xB8 + 1) * 2; else if (handleElse && nesting === 1 && ins === 0x1B) // ELSE break; } while (nesting > 0); state.ip = ip; } /*----------------------------------------------------------* * And then a lot of instructions... * *----------------------------------------------------------*/ // SVTCA[a] Set freedom and projection Vectors To Coordinate Axis // 0x00-0x01 function SVTCA(v, state) { if (DEBUG) console.log(state.step, 'SVTCA[' + v.axis + ']'); state.fv = state.pv = state.dpv = v; } // SPVTCA[a] Set Projection Vector to Coordinate Axis // 0x02-0x03 function SPVTCA(v, state) { if (DEBUG) console.log(state.step, 'SPVTCA[' + v.axis + ']'); state.pv = state.dpv = v; } // SFVTCA[a] Set Freedom Vector to Coordinate Axis // 0x04-0x05 function SFVTCA(v, state) { if (DEBUG) console.log(state.step, 'SFVTCA[' + v.axis + ']'); state.fv = v; } // SPVTL[a] Set Projection Vector To Line // 0x06-0x07 function SPVTL(a, state) { var stack = state.stack; var p2i = stack.pop(); var p1i = stack.pop(); var p2 = state.z2[p2i]; var p1 = state.z1[p1i]; if (DEBUG) console.log('SPVTL[' + a + ']', p2i, p1i); var dx; var dy; if (!a) { dx = p1.x - p2.x; dy = p1.y - p2.y; } else { dx = p2.y - p1.y; dy = p1.x - p2.x; } state.pv = state.dpv = getUnitVector(dx, dy); } // SFVTL[a] Set Freedom Vector To Line // 0x08-0x09 function SFVTL(a, state) { var stack = state.stack; var p2i = stack.pop(); var p1i = stack.pop(); var p2 = state.z2[p2i]; var p1 = state.z1[p1i]; if (DEBUG) console.log('SFVTL[' + a + ']', p2i, p1i); var dx; var dy; if (!a) { dx = p1.x - p2.x; dy = p1.y - p2.y; } else { dx = p2.y - p1.y; dy = p1.x - p2.x; } state.fv = getUnitVector(dx, dy); } // SPVFS[] Set Projection Vector From Stack // 0x0A function SPVFS(state) { var stack = state.stack; var y = stack.pop(); var x = stack.pop(); if (DEBUG) console.log(state.step, 'SPVFS[]', y, x); state.pv = state.dpv = getUnitVector(x, y); } // SFVFS[] Set Freedom Vector From Stack // 0x0B function SFVFS(state) { var stack = state.stack; var y = stack.pop(); var x = stack.pop(); if (DEBUG) console.log(state.step, 'SPVFS[]', y, x); state.fv = getUnitVector(x, y); } // GPV[] Get Projection Vector // 0x0C function GPV(state) { var stack = state.stack; var pv = state.pv; if (DEBUG) console.log(state.step, 'GPV[]'); stack.push(pv.x * 0x4000); stack.push(pv.y * 0x4000); } // GFV[] Get Freedom Vector // 0x0C function GFV(state) { var stack = state.stack; var fv = state.fv; if (DEBUG) console.log(state.step, 'GFV[]'); stack.push(fv.x * 0x4000); stack.push(fv.y * 0x4000); } // SFVTPV[] Set Freedom Vector To Projection Vector // 0x0E function SFVTPV(state) { state.fv = state.pv; if (DEBUG) console.log(state.step, 'SFVTPV[]'); } // ISECT[] moves point p to the InterSECTion of two lines // 0x0F function ISECT(state) { var stack = state.stack; var pa0i = stack.pop(); var pa1i = stack.pop(); var pb0i = stack.pop(); var pb1i = stack.pop(); var pi = stack.pop(); var z0 = state.z0; var z1 = state.z1; var pa0 = z0[pa0i]; var pa1 = z0[pa1i]; var pb0 = z1[pb0i]; var pb1 = z1[pb1i]; var p = state.z2[pi]; if (DEBUG) console.log('ISECT[], ', pa0i, pa1i, pb0i, pb1i, pi); // math from // en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line var x1 = pa0.x; var y1 = pa0.y; var x2 = pa1.x; var y2 = pa1.y; var x3 = pb0.x; var y3 = pb0.y; var x4 = pb1.x; var y4 = pb1.y; var div = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); var f1 = x1 * y2 - y1 * x2; var f2 = x3 * y4 - y3 * x4; p.x = (f1 * (x3 - x4) - f2 * (x1 - x2)) / div; p.y = (f1 * (y3 - y4) - f2 * (y1 - y2)) / div; } // SRP0[] Set Reference Point 0 // 0x10 function SRP0(state) { state.rp0 = state.stack.pop(); if (DEBUG) console.log(state.step, 'SRP0[]', state.rp0); } // SRP1[] Set Reference Point 1 // 0x11 function SRP1(state) { state.rp1 = state.stack.pop(); if (DEBUG) console.log(state.step, 'SRP1[]', state.rp1); } // SRP1[] Set Reference Point 2 // 0x12 function SRP2(state) { state.rp2 = state.stack.pop(); if (DEBUG) console.log(state.step, 'SRP2[]', state.rp2); } // SZP0[] Set Zone Pointer 0 // 0x13 function SZP0(state) { var n = state.stack.pop(); if (DEBUG) console.log(state.step, 'SZP0[]', n); state.zp0 = n; switch (n) { case 0: if (!state.tZone) initTZone(state); state.z0 = state.tZone; break; case 1 : state.z0 = state.gZone; break; default : throw new Error('Invalid zone pointer'); } } // SZP1[] Set Zone Pointer 1 // 0x14 function SZP1(state) { var n = state.stack.pop(); if (DEBUG) console.log(state.step, 'SZP1[]', n); state.zp1 = n; switch (n) { case 0: if (!state.tZone) initTZone(state); state.z1 = state.tZone; break; case 1 : state.z1 = state.gZone; break; default : throw new Error('Invalid zone pointer'); } } // SZP2[] Set Zone Pointer 2 // 0x15 function SZP2(state) { var n = state.stack.pop(); if (DEBUG) console.log(state.step, 'SZP2[]', n); state.zp2 = n; switch (n) { case 0: if (!state.tZone) initTZone(state); state.z2 = state.tZone; break; case 1 : state.z2 = state.gZone; break; default : throw new Error('Invalid zone pointer'); } } // SZPS[] Set Zone PointerS // 0x16 function SZPS(state) { var n = state.stack.pop(); if (DEBUG) console.log(state.step, 'SZPS[]', n); state.zp0 = state.zp1 = state.zp2 = n; switch (n) { case 0: if (!state.tZone) initTZone(state); state.z0 = state.z1 = state.z2 = state.tZone; break; case 1 : state.z0 = state.z1 = state.z2 = state.gZone; break; default : throw new Error('Invalid zone pointer'); } } // SLOOP[] Set LOOP variable // 0x17 function SLOOP(state) { state.loop = state.stack.pop(); if (DEBUG) console.log(state.step, 'SLOOP[]', state.loop); } // RTG[] Round To Grid // 0x18 function RTG(state) { if (DEBUG) console.log(state.step, 'RTG[]'); state.round = roundToGrid; } // RTHG[] Round To Half Grid // 0x19 function RTHG(state) { if (DEBUG) console.log(state.step, 'RTHG[]'); state.round = roundToHalfGrid; } // SMD[] Set Minimum Distance // 0x1A function SMD(state) { var d = state.stack.pop(); if (DEBUG) console.log(state.step, 'SMD[]', d); state.minDis = d / 0x40; } // ELSE[] ELSE clause // 0x1B function ELSE(state) { // This instruction has been reached by executing a then branch // so it just skips ahead until mathing EIF. // // In case the IF was negative the IF[] instruction already // skipped forward over the ELSE[] if (DEBUG) console.log(state.step, 'ELSE[]'); skip(state, false); } // JMPR[] JuMP Relative // 0x1C function JMPR(state) { var o = state.stack.pop(); if (DEBUG) console.log(state.step, 'JMPR[]', o); // A jump by 1 would do nothing. state.ip += o - 1; } // SCVTCI[] Set Control Value Table Cut-In // 0x1D function SCVTCI(state) { var n = state.stack.pop(); if (DEBUG) console.log(state.step, 'SCVTCI[]', n); state.cvCutIn = n / 0x40; } // DUP[] DUPlicate top stack element // 0x20 function DUP(state) { var stack = state.stack; if (DEBUG) console.log(state.step, 'DUP[]'); stack.push(stack[stack.length - 1]); } // POP[] POP top stack element // 0x21 function POP(state) { if (DEBUG) console.log(state.step, 'POP[]'); state.stack.pop(); } // CLEAR[] CLEAR the stack // 0x22 function CLEAR(state) { if (DEBUG) console.log(state.step, 'CLEAR[]'); state.stack.length = 0; } // SWAP[] SWAP the top two elements on the stack // 0x23 function SWAP(state) { var stack = state.stack; var a = stack.pop(); var b = stack.pop(); if (DEBUG) console.log(state.step, 'SWAP[]'); stack.push(a); stack.push(b); } // DEPTH[] DEPTH of the stack // 0x24 function DEPTH(state) { var stack = state.stack; if (DEBUG) console.log(state.step, 'DEPTH[]'); stack.push(stack.length); } // LOOPCALL[] LOOPCALL function // 0x2A function LOOPCALL(state) { var stack = state.stack; var fn = stack.pop(); var c = stack.pop(); if (DEBUG) console.log(state.step, 'LOOPCALL[]', fn, c); // saves callers program var cip = state.ip; var cprog = state.prog; state.prog = state.funcs[fn]; // executes the function for (var i = 0; i < c; i++) { exec(state); if (DEBUG) console.log( ++state.step, i + 1 < c ? 'next loopcall' : 'done loopcall', i ); } // restores the callers program state.ip = cip; state.prog = cprog; } // CALL[] CALL function // 0x2B function CALL(state) { var fn = state.stack.pop(); if (DEBUG) console.log(state.step, 'CALL[]', fn); // saves callers program var cip = state.ip; var cprog = state.prog; state.prog = state.funcs[fn]; // executes the function exec(state); // restores the callers program state.ip = cip; state.prog = cprog; if (DEBUG) console.log(++state.step, 'returning from', fn); } // CINDEX[] Copy the INDEXed element to the top of the stack // 0x25 function CINDEX(state) { var stack = state.stack; var k = stack.pop(); if (DEBUG) console.log(state.step, 'CINDEX[]', k); // In case of k == 1, it copies the last element after poping // thus stack.length - k. stack.push(stack[stack.length - k]); } // MINDEX[] Move the INDEXed element to the top of the stack // 0x26 function MINDEX(state) { var stack = state.stack; var k = stack.pop(); if (DEBUG) console.log(state.step, 'MINDEX[]', k); stack.push(stack.splice(stack.length - k, 1)[0]); } // FDEF[] Function DEFinition // 0x2C function FDEF(state) { if (state.env !== 'fpgm') throw new Error('FDEF not allowed here'); var stack = state.stack; var prog = state.prog; var ip = state.ip; var fn = stack.pop(); var ipBegin = ip; if (DEBUG) console.log(state.step, 'FDEF[]', fn); while (prog[++ip] !== 0x2D); state.ip = ip; state.funcs[fn] = prog.slice(ipBegin + 1, ip); } // MDAP[a] Move Direct Absolute Point // 0x2E-0x2F function MDAP(round, state) { var pi = state.stack.pop(); var p = state.z0[pi]; var fv = state.fv; var pv = state.pv; if (DEBUG) console.log(state.step, 'MDAP[' + round + ']', pi); var d = pv.distance(p, HPZero); if (round) d = state.round(d); fv.setRelative(p, HPZero, d, pv); fv.touch(p); state.rp0 = state.rp1 = pi; } // IUP[a] Interpolate Untouched Points through the outline // 0x30 function IUP(v, state) { var z2 = state.z2; var pLen = z2.length - 2; var cp; var pp; var np; if (DEBUG) console.log(state.step, 'IUP[' + v.axis + ']'); for (var i = 0; i < pLen; i++) { cp = z2[i]; // current point // if this point has been touched go on if (v.touched(cp)) continue; pp = cp.prevTouched(v); // no point on the contour has been touched? if (pp === cp) continue; np = cp.nextTouched(v); if (pp === np) { // only one point on the contour has been touched // so simply moves the point like that v.setRelative(cp, cp, v.distance(pp, pp, false, true), v, true); } v.interpolate(cp, pp, np, v); } } // SHP[] SHift Point using reference point // 0x32-0x33 function SHP(a, state) { var stack = state.stack; var rpi = a ? state.rp1 : state.rp2; var rp = (a ? state.z0 : state.z1)[rpi]; var fv = state.fv; var pv = state.pv; var loop = state.loop; var z2 = state.z2; while (loop--) { var pi = stack.pop(); var p = z2[pi]; var d = pv.distance(rp, rp, false, true); fv.setRelative(p, p, d, pv); fv.touch(p); if (DEBUG) { console.log( state.step, (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '' ) + 'SHP[' + (a ? 'rp1' : 'rp2') + ']', pi ); } } state.loop = 1; } // SHC[] SHift Contour using reference point // 0x36-0x37 function SHC(a, state) { var stack = state.stack; var rpi = a ? state.rp1 : state.rp2; var rp = (a ? state.z0 : state.z1)[rpi]; var fv = state.fv; var pv = state.pv; var ci = stack.pop(); var sp = state.z2[state.contours[ci]]; var p = sp; if (DEBUG) console.log(state.step, 'SHC[' + a + ']', ci); var d = pv.distance(rp, rp, false, true); do { if (p !== rp) fv.setRelative(p, p, d, pv); p = p.nextPointOnContour; } while (p !== sp); } // SHZ[] SHift Zone using reference point // 0x36-0x37 function SHZ(a, state) { var stack = state.stack; var rpi = a ? state.rp1 : state.rp2; var rp = (a ? state.z0 : state.z1)[rpi]; var fv = state.fv; var pv = state.pv; var e = stack.pop(); if (DEBUG) console.log(state.step, 'SHZ[' + a + ']', e); var z; switch (e) { case 0 : z = state.tZone; break; case 1 : z = state.gZone; break; default : throw new Error('Invalid zone'); } var p; var d = pv.distance(rp, rp, false, true); var pLen = z.length - 2; for (var i = 0; i < pLen; i++) { p = z[i]; if (p !== rp) fv.setRelative(p, p, d, pv); } } // SHPIX[] SHift point by a PIXel amount // 0x38 function SHPIX(state) { var stack = state.stack; var loop = state.loop; var fv = state.fv; var d = stack.pop() / 0x40; var z2 = state.z2; while (loop--) { var pi = stack.pop(); var p = z2[pi]; if (DEBUG) console.log( state.step, (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') + 'SHPIX[]', pi, d ); fv.setRelative(p, p, d); fv.touch(p); } state.loop = 1; } // IP[] Interpolate Point // 0x39 function IP(state) { var stack = state.stack; var rp1i = state.rp1; var rp2i = state.rp2; var loop = state.loop; var rp1 = state.z0[rp1i]; var rp2 = state.z1[rp2i]; var fv = state.fv; var pv = state.dpv; var z2 = state.z2; while (loop--) { var pi = stack.pop(); var p = z2[pi]; if (DEBUG) console.log( state.step, (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') + 'IP[]', pi, rp1i, '<->', rp2i ); fv.interpolate(p, rp1, rp2, pv); fv.touch(p); } state.loop = 1; } // MSIRP[a] Move Stack Indirect Relative Point // 0x3A-0x3B function MSIRP(a, state) { var stack = state.stack; var d = stack.pop() / 64; var pi = stack.pop(); var p = state.z1[pi]; var rp0 = state.z0[state.rp0]; var fv = state.fv; var pv = state.pv; fv.setRelative(p, rp0, d, pv); fv.touch(p); if (DEBUG) console.log(state.step, 'MSIRP[' + a + ']', d, pi); state.rp1 = state.rp0; state.rp2 = pi; if (a) state.rp0 = pi; } // ALIGNRP[] Align to reference point. // 0x3C function ALIGNRP(state) { var stack = state.stack; var rp0i = state.rp0; var rp0 = state.z0[rp0i]; var loop = state.loop; var fv = state.fv; var pv = state.pv; var z1 = state.z1; while (loop--) { var pi = stack.pop(); var p = z1[pi]; if (DEBUG) console.log( state.step, (state.loop > 1 ? 'loop ' + (state.loop - loop) + ': ' : '') + 'ALIGNRP[]', pi ); fv.setRelative(p, rp0, 0, pv); fv.touch(p); } state.loop = 1; } // RTG[] Round To Double Grid // 0x3D function RTDG(state) { if (DEBUG) console.log(state.step, 'RTDG[]'); state.round = roundToDoubleGrid; } // MIAP[a] Move Indirect Absolute Point // 0x3E-0x3F function MIAP(round, state) { var stack = state.stack; var n = stack.pop(); var pi = stack.pop(); var p = state.z0[pi]; var fv = state.fv; var pv = state.pv; var cv = state.cvt[n]; // TODO cvtcutin should be considered here if (round) cv = state.round(cv); if (DEBUG) { console.log( state.step, 'MIAP[' + round + ']', n, '(', cv, ')', pi ); } fv.setRelative(p, HPZero, cv, pv); if (state.zp0 === 0) { p.xo = p.x; p.yo = p.y; } fv.touch(p); state.rp0 = state.rp1 = pi; } // NPUSB[] PUSH N Bytes // 0x40 function NPUSHB(state) { var prog = state.prog; var ip = state.ip; var stack = state.stack; var n = prog[++ip]; if (DEBUG) console.log(state.step, 'NPUSHB[]', n); for (var i = 0; i < n; i++) stack.push(prog[++ip]); state.ip = ip; } // NPUSHW[] PUSH N Words // 0x41 function NPUSHW(state) { var ip = state.ip; var prog = state.prog; var stack = state.stack; var n = prog[++ip]; if (DEBUG) console.log(state.step, 'NPUSHW[]', n); for (var i = 0; i < n; i++) { var w = (prog[++ip] << 8) | prog[++ip]; if (w & 0x8000) w = -((w ^ 0xffff) + 1); stack.push(w); } state.ip = ip; } // WS[] Write Store // 0x42 function WS(state) { var stack = state.stack; var store = state.store; if (!store) store = state.store = []; var v = stack.pop(); var l = stack.pop(); if (DEBUG) console.log(state.step, 'WS', v, l); store[l] = v; } // RS[] Read Store // 0x43 function RS(state) { var stack = state.stack; var store = state.store; var l = stack.pop(); if (DEBUG) console.log(state.step, 'RS', l); var v = (store && store[l]) || 0; stack.push(v); } // WCVTP[] Write Control Value Table in Pixel units // 0x44 function WCVTP(state) { var stack = state.stack; var v = stack.pop(); var l = stack.pop(); if (DEBUG) console.log(state.step, 'WCVTP', v, l); state.cvt[l] = v / 0x40; } // RCVT[] Read Control Value Table entry // 0x45 function RCVT(state) { var stack = state.stack; var cvte = stack.pop(); if (DEBUG) console.log(state.step, 'RCVT', cvte); stack.push(state.cvt[cvte] * 0x40); } // GC[] Get Coordinate projected onto the projection vector // 0x46-0x47 function GC(a, state) { var stack = state.stack; var pi = stack.pop(); var p = state.z2[pi]; if (DEBUG) console.log(state.step, 'GC[' + a + ']', pi); stack.push(state.dpv.distance(p, HPZero, a, false) * 0x40); } // MD[a] Measure Distance // 0x49-0x4A function MD(a, state) { var stack = state.stack; var pi2 = stack.pop(); var pi1 = stack.pop(); var p2 = state.z1[pi2]; var p1 = state.z0[pi1]; var d = state.dpv.distance(p1, p2, a, a); if (DEBUG) console.log(state.step, 'MD[' + a + ']', pi2, pi1, '->', d); state.stack.push(Math.round(d * 64)); } // MPPEM[] Measure Pixels Per EM // 0x4B function MPPEM(state) { if (DEBUG) console.log(state.step, 'MPPEM[]'); state.stack.push(state.ppem); } // FLIPON[] set the auto FLIP Boolean to ON // 0x4D function FLIPON(state) { if (DEBUG) console.log(state.step, 'FLIPON[]'); state.autoFlip = true; } // LT[] Less Than // 0x50 function LT(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (DEBUG) console.log(state.step, 'LT[]', e2, e1); stack.push(e1 < e2 ? 1 : 0); } // LTEQ[] Less Than or EQual // 0x53 function LTEQ(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (DEBUG) console.log(state.step, 'LTEQ[]', e2, e1); stack.push(e1 <= e2 ? 1 : 0); } // GTEQ[] Greater Than // 0x52 function GT(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (DEBUG) console.log(state.step, 'GT[]', e2, e1); stack.push(e1 > e2 ? 1 : 0); } // GTEQ[] Greater Than or EQual // 0x53 function GTEQ(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (DEBUG) console.log(state.step, 'GTEQ[]', e2, e1); stack.push(e1 >= e2 ? 1 : 0); } // EQ[] EQual // 0x54 function EQ(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (DEBUG) console.log(state.step, 'EQ[]', e2, e1); stack.push(e2 === e1 ? 1 : 0); } // NEQ[] Not EQual // 0x55 function NEQ(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (DEBUG) console.log(state.step, 'NEQ[]', e2, e1); stack.push(e2 !== e1 ? 1 : 0); } // ODD[] ODD // 0x56 function ODD(state) { var stack = state.stack; var n = stack.pop(); if (DEBUG) console.log(state.step, 'ODD[]', n); stack.push(Math.trunc(n) % 2 ? 1 : 0); } // EVEN[] EVEN // 0x57 function EVEN(state) { var stack = state.stack; var n = stack.pop(); if (DEBUG) console.log(state.step, 'EVEN[]', n); stack.push(Math.trunc(n) % 2 ? 0 : 1); } // IF[] IF test // 0x58 function IF(state) { var test = state.stack.pop(); var ins; if (DEBUG) console.log(state.step, 'IF[]', test); // if test is true it just continues // if not the ip is skipped until matching ELSE or EIF if (!test) { skip(state, true); if (DEBUG) console.log(state.step, ins === 0x1B ? 'ELSE[]' : 'EIF[]'); } } // EIF[] End IF // 0x59 function EIF(state) { // this can be reached normally when // executing an else branch. // -> just ignore it if (DEBUG) console.log(state.step, 'EIF[]'); } // AND[] logical AND // 0x5A function AND(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (DEBUG) console.log(state.step, 'AND[]', e2, e1); stack.push(e2 && e1 ? 1 : 0); } // OR[] logical OR // 0x5B function OR(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (DEBUG) console.log(state.step, 'OR[]', e2, e1); stack.push(e2 || e1 ? 1 : 0); } // NOT[] logical NOT // 0x5C function NOT(state) { var stack = state.stack; var e = stack.pop(); if (DEBUG) console.log(state.step, 'NOT[]', e); stack.push(e ? 0 : 1); } // DELTAP1[] DELTA exception P1 // DELTAP2[] DELTA exception P2 // DELTAP3[] DELTA exception P3 // 0x5D, 0x71, 0x72 function DELTAP123(b, state) { var stack = state.stack; var n = stack.pop(); var fv = state.fv; var pv = state.pv; var ppem = state.ppem; var base = state.deltaBase + (b - 1) * 16; var ds = state.deltaShift; var z0 = state.z0; if (DEBUG) console.log(state.step, 'DELTAP[' + b + ']', n, stack); for (var i = 0; i < n; i++) { var pi = stack.pop(); var arg = stack.pop(); var appem = base + ((arg & 0xF0) >> 4); if (appem !== ppem) continue; var mag = (arg & 0x0F) - 8; if (mag >= 0) mag++; if (DEBUG) console.log(state.step, 'DELTAPFIX', pi, 'by', mag * ds); var p = z0[pi]; fv.setRelative(p, p, mag * ds, pv); } } // SDB[] Set Delta Base in the graphics state // 0x5E function SDB(state) { var stack = state.stack; var n = stack.pop(); if (DEBUG) console.log(state.step, 'SDB[]', n); state.deltaBase = n; } // SDS[] Set Delta Shift in the graphics state // 0x5F function SDS(state) { var stack = state.stack; var n = stack.pop(); if (DEBUG) console.log(state.step, 'SDS[]', n); state.deltaShift = Math.pow(0.5, n); } // ADD[] ADD // 0x60 function ADD(state) { var stack = state.stack; var n2 = stack.pop(); var n1 = stack.pop(); if (DEBUG) console.log(state.step, 'ADD[]', n2, n1); stack.push(n1 + n2); } // SUB[] SUB // 0x61 function SUB(state) { var stack = state.stack; var n2 = stack.pop(); var n1 = stack.pop(); if (DEBUG) console.log(state.step, 'SUB[]', n2, n1); stack.push(n1 - n2); } // DIV[] DIV // 0x62 function DIV(state) { var stack = state.stack; var n2 = stack.pop(); var n1 = stack.pop(); if (DEBUG) console.log(state.step, 'DIV[]', n2, n1); stack.push(n1 * 64 / n2); } // MUL[] MUL // 0x63 function MUL(state) { var stack = state.stack; var n2 = stack.pop(); var n1 = stack.pop(); if (DEBUG) console.log(state.step, 'MUL[]', n2, n1); stack.push(n1 * n2 / 64); } // ABS[] ABSolute value // 0x64 function ABS(state) { var stack = state.stack; var n = stack.pop(); if (DEBUG) console.log(state.step, 'ABS[]', n); stack.push(Math.abs(n)); } // NEG[] NEGate // 0x65 function NEG(state) { var stack = state.stack; var n = stack.pop(); if (DEBUG) console.log(state.step, 'NEG[]', n); stack.push(-n); } // FLOOR[] FLOOR // 0x66 function FLOOR(state) { var stack = state.stack; var n = stack.pop(); if (DEBUG) console.log(state.step, 'FLOOR[]', n); stack.push(Math.floor(n / 0x40) * 0x40); } // CEILING[] CEILING // 0x67 function CEILING(state) { var stack = state.stack; var n = stack.pop(); if (DEBUG) console.log(state.step, 'CEILING[]', n); stack.push(Math.ceil(n / 0x40) * 0x40); } // ROUND[ab] ROUND value // 0x68-0x6B function ROUND(dt, state) { var stack = state.stack; var n = stack.pop(); if (DEBUG) console.log(state.step, 'ROUND[]'); stack.push(state.round(n / 0x40) * 0x40); } // WCVTF[] Write Control Value Table in Funits // 0x70 function WCVTF(state) { var stack = state.stack; var v = stack.pop(); var l = stack.pop(); if (DEBUG) console.log(state.step, 'WCVTF[]', v, l); state.cvt[l] = v * state.ppem / state.font.unitsPerEm; } // DELTAC1[] DELTA exception C1 // DELTAC2[] DELTA exception C2 // DELTAC3[] DELTA exception C3 // 0x73, 0x74, 0x75 function DELTAC123(b, state) { var stack = state.stack; var n = stack.pop(); var ppem = state.ppem; var base = state.deltaBase + (b - 1) * 16; var ds = state.deltaShift; if (DEBUG) console.log(state.step, 'DELTAC[' + b + ']', n, stack); for (var i = 0; i < n; i++) { var c = stack.pop(); var arg = stack.pop(); var appem = base + ((arg & 0xF0) >> 4); if (appem !== ppem) continue; var mag = (arg & 0x0F) - 8; if (mag >= 0) mag++; var delta = mag * ds; if (DEBUG) console.log(state.step, 'DELTACFIX', c, 'by', delta); state.cvt[c] += delta; } } // SROUND[] Super ROUND // 0x76 function SROUND(state) { var n = state.stack.pop(); if (DEBUG) console.log(state.step, 'SROUND[]', n); state.round = roundSuper; var period; switch (n & 0xC0) { case 0x00: period = 0.5; break; case 0x40: period = 1; break; case 0x80: period = 2; break; default: throw new Error('invalid SROUND value'); } state.srPeriod = period; switch (n & 0x30) { case 0x00: state.srPhase = 0; break; case 0x10: state.srPhase = 0.25 * period; break; case 0x20: state.srPhase = 0.5 * period; break; case 0x30: state.srPhase = 0.75 * period; break; default: throw new Error('invalid SROUND value'); } n &= 0x0F; if (n === 0) state.srThreshold = 0; else state.srThreshold = (n / 8 - 0.5) * period; } // S45ROUND[] Super ROUND 45 degrees // 0x77 function S45ROUND(state) { var n = state.stack.pop(); if (DEBUG) console.log(state.step, 'S45ROUND[]', n); state.round = roundSuper; var period; switch (n & 0xC0) { case 0x00: period = Math.sqrt(2) / 2; break; case 0x40: period = Math.sqrt(2); break; case 0x80: period = 2 * Math.sqrt(2); break; default: throw new Error('invalid S45ROUND value'); } state.srPeriod = period; switch (n & 0x30) { case 0x00: state.srPhase = 0; break; case 0x10: state.srPhase = 0.25 * period; break; case 0x20: state.srPhase = 0.5 * period; break; case 0x30: state.srPhase = 0.75 * period; break; default: throw new Error('invalid S45ROUND value'); } n &= 0x0F; if (n === 0) state.srThreshold = 0; else state.srThreshold = (n / 8 - 0.5) * period; } // ROFF[] Round Off // 0x7A function ROFF(state) { if (DEBUG) console.log(state.step, 'ROFF[]'); state.round = roundOff; } // RUTG[] Round Up To Grid // 0x7C function RUTG(state) { if (DEBUG) console.log(state.step, 'RUTG[]'); state.round = roundUpToGrid; } // RDTG[] Round Down To Grid // 0x7D function RDTG(state) { if (DEBUG) console.log(state.step, 'RDTG[]'); state.round = roundDownToGrid; } // SCANCTRL[] SCAN conversion ConTRoL // 0x85 function SCANCTRL(state) { var n = state.stack.pop(); // ignored by opentype.js if (DEBUG) console.log(state.step, 'SCANCTRL[]', n); } // SDPVTL[a] Set Dual Projection Vector To Line // 0x86-0x87 function SDPVTL(a, state) { var stack = state.stack; var p2i = stack.pop(); var p1i = stack.pop(); var p2 = state.z2[p2i]; var p1 = state.z1[p1i]; if (DEBUG) console.log('SDPVTL[' + a + ']', p2i, p1i); var dx; var dy; if (!a) { dx = p1.x - p2.x; dy = p1.y - p2.y; } else { dx = p2.y - p1.y; dy = p1.x - p2.x; } state.dpv = getUnitVector(dx, dy); } // GETINFO[] GET INFOrmation // 0x88 function GETINFO(state) { var stack = state.stack; var sel = stack.pop(); var r = 0; if (DEBUG) console.log(state.step, 'GETINFO[]', sel); // v35 as in no subpixel hinting if (sel & 0x01) r = 35; // TODO rotation and stretch currently not supported // and thus those GETINFO are always 0. // opentype.js is always gray scaling if (sel & 0x20) r |= 0x1000; stack.push(r); } // ROLL[] ROLL the top three stack elements // 0x8A function ROLL(state) { var stack = state.stack; var a = stack.pop(); var b = stack.pop(); var c = stack.pop(); if (DEBUG) console.log(state.step, 'ROLL[]'); stack.push(b); stack.push(a); stack.push(c); } // MAX[] MAXimum of top two stack elements // 0x8B function MAX(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (DEBUG) console.log(state.step, 'MAX[]', e2, e1); stack.push(Math.max(e1, e2)); } // MIN[] MINimum of top two stack elements // 0x8C function MIN(state) { var stack = state.stack; var e2 = stack.pop(); var e1 = stack.pop(); if (DEBUG) console.log(state.step, 'MIN[]', e2, e1); stack.push(Math.min(e1, e2)); } // SCANTYPE[] SCANTYPE // 0x8D function SCANTYPE(state) { var n = state.stack.pop(); // ignored by opentype.js if (DEBUG) console.log(state.step, 'SCANTYPE[]', n); } // INSTCTRL[] INSTCTRL // 0x8D function INSTCTRL(state) { var s = state.stack.pop(); var v = state.stack.pop(); if (DEBUG) console.log(state.step, 'INSTCTRL[]', s, v); switch (s) { case 1 : state.inhibitGridFit = !!v; return; case 2 : state.ignoreCvt = !!v; return; default: throw new Error('invalid INSTCTRL[] selector'); } } // PUSHB[abc] PUSH Bytes // 0xB0-0xB7 function PUSHB(n, state) { var stack = state.stack; var prog = state.prog; var ip = state.ip; if (DEBUG) console.log(state.step, 'PUSHB[' + n + ']'); for (var i = 0; i < n; i++) stack.push(prog[++ip]); state.ip = ip; } // PUSHW[abc] PUSH Words // 0xB8-0xBF function PUSHW(n, state) { var ip = state.ip; var prog = state.prog; var stack = state.stack; if (DEBUG) console.log(state.ip, 'PUSHW[' + n + ']'); for (var i = 0; i < n; i++) { var w = (prog[++ip] << 8) | prog[++ip]; if (w & 0x8000) w = -((w ^ 0xffff) + 1); stack.push(w); } state.ip = ip; } // MDRP[abcde] Move Direct Relative Point // 0xD0-0xEF // (if indirect is 0) // // and // // MIRP[abcde] Move Indirect Relative Point // 0xE0-0xFF // (if indirect is 1) function MDRP_MIRP(indirect, setRp0, keepD, ro, dt, state) { var stack = state.stack; var cvte = indirect && stack.pop(); var pi = stack.pop(); var rp0i = state.rp0; var rp = state.z0[rp0i]; var p = state.z1[pi]; var md = state.minDis; var fv = state.fv; var pv = state.dpv; var od; // original distance var d; // moving distance var sign; // sign of distance var cv; d = od = pv.distance(p, rp, true, true); sign = d >= 0 ? 1 : -1; // Math.sign would be 0 in case of 0 // TODO consider autoFlip d = Math.abs(d); if (indirect) { cv = state.cvt[cvte]; if (ro && Math.abs(d - cv) < state.cvCutIn) d = cv; } if (keepD && d < md) d = md; if (ro) d = state.round(d); fv.setRelative(p, rp, sign * d, pv); fv.touch(p); if (DEBUG) { console.log( state.step, (indirect ? 'MIRP[' : 'MDRP[') + (setRp0 ? 'M' : 'm') + (keepD ? '>' : '_') + (ro ? 'R' : '_') + (dt === 0 ? 'Gr' : (dt === 1 ? 'Bl' : (dt === 2 ? 'Wh' : ''))) + ']', indirect ? cvte + '(' + state.cvt[cvte] + ',' + cv + ')' : '', pi, '(d =', od, '->', sign * d, ')' ); } state.rp1 = state.rp0; state.rp2 = pi; if (setRp0) state.rp0 = pi; } /* * The instruction table. */ instructionTable = [ /* 0x00 */ SVTCA.bind(undefined, yUnitVector), /* 0x01 */ SVTCA.bind(undefined, xUnitVector), /* 0x02 */ SPVTCA.bind(undefined, yUnitVector), /* 0x03 */ SPVTCA.bind(undefined, xUnitVector), /* 0x04 */ SFVTCA.bind(undefined, yUnitVector), /* 0x05 */ SFVTCA.bind(undefined, xUnitVector), /* 0x06 */ SPVTL.bind(undefined, 0), /* 0x07 */ SPVTL.bind(undefined, 1), /* 0x08 */ SFVTL.bind(undefined, 0), /* 0x09 */ SFVTL.bind(undefined, 1), /* 0x0A */ SPVFS, /* 0x0B */ SFVFS, /* 0x0C */ GPV, /* 0x0D */ GFV, /* 0x0E */ SFVTPV, /* 0x0F */ ISECT, /* 0x10 */ SRP0, /* 0x11 */ SRP1, /* 0x12 */ SRP2, /* 0x13 */ SZP0, /* 0x14 */ SZP1, /* 0x15 */ SZP2, /* 0x16 */ SZPS, /* 0x17 */ SLOOP, /* 0x18 */ RTG, /* 0x19 */ RTHG, /* 0x1A */ SMD, /* 0x1B */ ELSE, /* 0x1C */ JMPR, /* 0x1D */ SCVTCI, /* 0x1E */ undefined, // TODO SSWCI /* 0x1F */ undefined, // TODO SSW /* 0x20 */ DUP, /* 0x21 */ POP, /* 0x22 */ CLEAR, /* 0x23 */ SWAP, /* 0x24 */ DEPTH, /* 0x25 */ CINDEX, /* 0x26 */ MINDEX, /* 0x27 */ undefined, // TODO ALIGNPTS /* 0x28 */ undefined, /* 0x29 */ undefined, // TODO UTP /* 0x2A */ LOOPCALL, /* 0x2B */ CALL, /* 0x2C */ FDEF, /* 0x2D */ undefined, // ENDF (eaten by FDEF) /* 0x2E */ MDAP.bind(undefined, 0), /* 0x2F */ MDAP.bind(undefined, 1), /* 0x30 */ IUP.bind(undefined, yUnitVector), /* 0x31 */ IUP.bind(undefined, xUnitVector), /* 0x32 */ SHP.bind(undefined, 0), /* 0x33 */ SHP.bind(undefined, 1), /* 0x34 */ SHC.bind(undefined, 0), /* 0x35 */ SHC.bind(undefined, 1), /* 0x36 */ SHZ.bind(undefined, 0), /* 0x37 */ SHZ.bind(undefined, 1), /* 0x38 */ SHPIX, /* 0x39 */ IP, /* 0x3A */ MSIRP.bind(undefined, 0), /* 0x3B */ MSIRP.bind(undefined, 1), /* 0x3C */ ALIGNRP, /* 0x3D */ RTDG, /* 0x3E */ MIAP.bind(undefined, 0), /* 0x3F */ MIAP.bind(undefined, 1), /* 0x40 */ NPUSHB, /* 0x41 */ NPUSHW, /* 0x42 */ WS, /* 0x43 */ RS, /* 0x44 */ WCVTP, /* 0x45 */ RCVT, /* 0x46 */ GC.bind(undefined, 0), /* 0x47 */ GC.bind(undefined, 1), /* 0x48 */ undefined, // TODO SCFS /* 0x49 */ MD.bind(undefined, 0), /* 0x4A */ MD.bind(undefined, 1), /* 0x4B */ MPPEM, /* 0x4C */ undefined, // TODO MPS /* 0x4D */ FLIPON, /* 0x4E */ undefined, // TODO FLIPOFF /* 0x4F */ undefined, // TODO DEBUG /* 0x50 */ LT, /* 0x51 */ LTEQ, /* 0x52 */ GT, /* 0x53 */ GTEQ, /* 0x54 */ EQ, /* 0x55 */ NEQ, /* 0x56 */ ODD, /* 0x57 */ EVEN, /* 0x58 */ IF, /* 0x59 */ EIF, /* 0x5A */ AND, /* 0x5B */ OR, /* 0x5C */ NOT, /* 0x5D */ DELTAP123.bind(undefined, 1), /* 0x5E */ SDB, /* 0x5F */ SDS, /* 0x60 */ ADD, /* 0x61 */ SUB, /* 0x62 */ DIV, /* 0x63 */ MUL, /* 0x64 */ ABS, /* 0x65 */ NEG, /* 0x66 */ FLOOR, /* 0x67 */ CEILING, /* 0x68 */ ROUND.bind(undefined, 0), /* 0x69 */ ROUND.bind(undefined, 1), /* 0x6A */ ROUND.bind(undefined, 2), /* 0x6B */ ROUND.bind(undefined, 3), /* 0x6C */ undefined, // TODO NROUND[ab] /* 0x6D */ undefined, // TODO NROUND[ab] /* 0x6E */ undefined, // TODO NROUND[ab] /* 0x6F */ undefined, // TODO NROUND[ab] /* 0x70 */ WCVTF, /* 0x71 */ DELTAP123.bind(undefined, 2), /* 0x72 */ DELTAP123.bind(undefined, 3), /* 0x73 */ DELTAC123.bind(undefined, 1), /* 0x74 */ DELTAC123.bind(undefined, 2), /* 0x75 */ DELTAC123.bind(undefined, 3), /* 0x76 */ SROUND, /* 0x77 */ S45ROUND, /* 0x78 */ undefined, // TODO JROT[] /* 0x79 */ undefined, // TODO JROF[] /* 0x7A */ ROFF, /* 0x7B */ undefined, /* 0x7C */ RUTG, /* 0x7D */ RDTG, /* 0x7E */ POP, // actually SANGW, supposed to do only a pop though /* 0x7F */ POP, // actually AA, upposed to do only a pop though /* 0x80 */ undefined, // TODO FLIPPT /* 0x81 */ undefined, // TODO FLIPRGON /* 0x82 */ undefined, // TODO FLIPRGOFF /* 0x83 */ undefined, /* 0x84 */ undefined, /* 0x85 */ SCANCTRL, /* 0x86 */ SDPVTL.bind(undefined, 0), /* 0x87 */ SDPVTL.bind(undefined, 1), /* 0x88 */ GETINFO, /* 0x89 */ undefined, // TODO IDEF /* 0x8A */ ROLL, /* 0x8B */ MAX, /* 0x8C */ MIN, /* 0x8D */ SCANTYPE, /* 0x8E */ INSTCTRL, /* 0x8F */ undefined, /* 0x90 */ undefined, /* 0x91 */ undefined, /* 0x92 */ undefined, /* 0x93 */ undefined, /* 0x94 */ undefined, /* 0x95 */ undefined, /* 0x96 */ undefined, /* 0x97 */ undefined, /* 0x98 */ undefined, /* 0x99 */ undefined, /* 0x9A */ undefined, /* 0x9B */ undefined, /* 0x9C */ undefined, /* 0x9D */ undefined, /* 0x9E */ undefined, /* 0x9F */ undefined, /* 0xA0 */ undefined, /* 0xA1 */ undefined, /* 0xA2 */ undefined, /* 0xA3 */ undefined, /* 0xA4 */ undefined, /* 0xA5 */ undefined, /* 0xA6 */ undefined, /* 0xA7 */ undefined, /* 0xA8 */ undefined, /* 0xA9 */ undefined, /* 0xAA */ undefined, /* 0xAB */ undefined, /* 0xAC */ undefined, /* 0xAD */ undefined, /* 0xAE */ undefined, /* 0xAF */ undefined, /* 0xB0 */ PUSHB.bind(undefined, 1), /* 0xB1 */ PUSHB.bind(undefined, 2), /* 0xB2 */ PUSHB.bind(undefined, 3), /* 0xB3 */ PUSHB.bind(undefined, 4), /* 0xB4 */ PUSHB.bind(undefined, 5), /* 0xB5 */ PUSHB.bind(undefined, 6), /* 0xB6 */ PUSHB.bind(undefined, 7), /* 0xB7 */ PUSHB.bind(undefined, 8), /* 0xB8 */ PUSHW.bind(undefined, 1), /* 0xB9 */ PUSHW.bind(undefined, 2), /* 0xBA */ PUSHW.bind(undefined, 3), /* 0xBB */ PUSHW.bind(undefined, 4), /* 0xBC */ PUSHW.bind(undefined, 5), /* 0xBD */ PUSHW.bind(undefined, 6), /* 0xBE */ PUSHW.bind(undefined, 7), /* 0xBF */ PUSHW.bind(undefined, 8), /* 0xC0 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 0), /* 0xC1 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 1), /* 0xC2 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 2), /* 0xC3 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 0, 3), /* 0xC4 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 0), /* 0xC5 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 1), /* 0xC6 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 2), /* 0xC7 */ MDRP_MIRP.bind(undefined, 0, 0, 0, 1, 3), /* 0xC8 */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 0), /* 0xC9 */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 1), /* 0xCA */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 2), /* 0xCB */ MDRP_MIRP.bind(undefined, 0, 0, 1, 0, 3), /* 0xCC */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 0), /* 0xCD */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 1), /* 0xCE */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 2), /* 0xCF */ MDRP_MIRP.bind(undefined, 0, 0, 1, 1, 3), /* 0xD0 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 0), /* 0xD1 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 1), /* 0xD2 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 2), /* 0xD3 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 0, 3), /* 0xD4 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 0), /* 0xD5 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 1), /* 0xD6 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 2), /* 0xD7 */ MDRP_MIRP.bind(undefined, 0, 1, 0, 1, 3), /* 0xD8 */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 0), /* 0xD9 */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 1), /* 0xDA */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 2), /* 0xDB */ MDRP_MIRP.bind(undefined, 0, 1, 1, 0, 3), /* 0xDC */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 0), /* 0xDD */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 1), /* 0xDE */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 2), /* 0xDF */ MDRP_MIRP.bind(undefined, 0, 1, 1, 1, 3), /* 0xE0 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 0), /* 0xE1 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 1), /* 0xE2 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 2), /* 0xE3 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 0, 3), /* 0xE4 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 0), /* 0xE5 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 1), /* 0xE6 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 2), /* 0xE7 */ MDRP_MIRP.bind(undefined, 1, 0, 0, 1, 3), /* 0xE8 */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 0), /* 0xE9 */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 1), /* 0xEA */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 2), /* 0xEB */ MDRP_MIRP.bind(undefined, 1, 0, 1, 0, 3), /* 0xEC */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 0), /* 0xED */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 1), /* 0xEE */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 2), /* 0xEF */ MDRP_MIRP.bind(undefined, 1, 0, 1, 1, 3), /* 0xF0 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 0), /* 0xF1 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 1), /* 0xF2 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 2), /* 0xF3 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 0, 3), /* 0xF4 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 0), /* 0xF5 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 1), /* 0xF6 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 2), /* 0xF7 */ MDRP_MIRP.bind(undefined, 1, 1, 0, 1, 3), /* 0xF8 */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 0), /* 0xF9 */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 1), /* 0xFA */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 2), /* 0xFB */ MDRP_MIRP.bind(undefined, 1, 1, 1, 0, 3), /* 0xFC */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 0), /* 0xFD */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 1), /* 0xFE */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 2), /* 0xFF */ MDRP_MIRP.bind(undefined, 1, 1, 1, 1, 3) ]; module.exports = Hinting; /***************************** Mathematical Considertions ****************************** fv ... refers to freedom vector pv ... refers to projection vector rp ... refers to reference point p ... refers to to point being operated on d ... refers to distance SETRELATIVE: ============ case freedom vector == x-axis: ------------------------------ (pv) .-' rpd .-' .-* d .-'90°' .-' ' .-' ' *-' ' b rp ' ' ' p *----------*-------------- (fv) pm rpdx = rpx + d * pv.x rpdy = rpy + d * pv.y equation of line b y - rpdy = pvns * (x- rpdx) y = p.y x = rpdx + ( p.y - rpdy ) / pvns case freedom vector == y-axis: ------------------------------ * pm |\ | \ | \ | \ | \ | \ | \ | \ | \ | \ b | \ | \ | \ .-' (pv) | 90° \.-' | .-'* rpd | .-' * *-' d p rp rpdx = rpx + d * pv.x rpdy = rpy + d * pv.y equation of line b: pvns ... normal slope to pv y - rpdy = pvns * (x - rpdx) x = p.x y = rpdy + pvns * (p.x - rpdx) generic case: ------------- .'(fv) .' .* pm .' ! .' . .' ! .' . b .' ! * . p ! 90° . ... (pv) ...-*-''' ...---''' rpd ...---''' d *--''' rp rpdx = rpx + d * pv.x rpdy = rpy + d * pv.y equation of line b: pvns... normal slope to pv y - rpdy = pvns * (x - rpdx) equation of freedom vector line: fvs ... slope of freedom vector (=fy/fx) y - py = fvs * (x - px) on pm both equations are true for same x/y y - rpdy = pvns * (x - rpdx) y - py = fvs * (x - px) form to y and set equal: pvns * (x - rpdx) + rpdy = fvs * (x - px) + py expand: pvns * x - pvns * rpdx + rpdy = fvs * x - fvs * px + py switch: fvs * x - fvs * px + py = pvns * x - pvns * rpdx + rpdy solve for x: fvs * x - pvns * x = fvs * px - pvns * rpdx - py + rpdy fvs * px - pvns * rpdx + rpdy - py x = ----------------------------------- fvs - pvns and: y = fvs * (x - px) + py INTERPOLATE: ============ Examples of point interpolation. The weight of the movement of the reference point gets bigger the further the other reference point is away, thus the safest option (that is avoiding 0/0 divisions) is to weight the original distance of the other point by the sum of both distances. If the sum of both distances is 0, then move the point by the arithmetic average of the movement of both refererence points. (+6) rp1o *---->*rp1 . . (+12) . . rp2o *---------->* rp2 . . . . . . . . . 10 20 . . |.........|...................| . . . . . . (+8) . po *------>*p . . . . . 12 . 24 . |...........|.......................| 36 ------- (+10) rp1o *-------->*rp1 . . (-10) . . rp2 *<---------* rpo2 . . . . . . . . . 10 . 30 . . |.........|.............................| . . . (+5) . po *--->* p . . . . . . 20 . |....|..............| 5 15 ------- (+10) rp1o *-------->*rp1 . . . . rp2o *-------->*rp2 (+10) po *-------->* p ------- (+10) rp1o *-------->*rp1 . . . .(+30) rp2o *---------------------------->*rp2 (+25) po *----------------------->* p vim: set ts=4 sw=4 expandtab: *****/ },{}],14:[function(_dereq_,module,exports){ // The Layout object is the prototype of Substition objects, and provides utility methods to manipulate // common layout tables (GPOS, GSUB, GDEF...) 'use strict'; var check = _dereq_('./check'); function searchTag(arr, tag) { /* jshint bitwise: false */ var imin = 0; var imax = arr.length - 1; while (imin <= imax) { var imid = (imin + imax) >>> 1; var val = arr[imid].tag; if (val === tag) { return imid; } else if (val < tag) { imin = imid + 1; } else { imax = imid - 1; } } // Not found: return -1-insertion point return -imin - 1; } function binSearch(arr, value) { /* jshint bitwise: false */ var imin = 0; var imax = arr.length - 1; while (imin <= imax) { var imid = (imin + imax) >>> 1; var val = arr[imid]; if (val === value) { return imid; } else if (val < value) { imin = imid + 1; } else { imax = imid - 1; } } // Not found: return -1-insertion point return -imin - 1; } /** * @exports opentype.Layout * @class */ function Layout(font, tableName) { this.font = font; this.tableName = tableName; } Layout.prototype = { /** * Binary search an object by "tag" property * @instance * @function searchTag * @memberof opentype.Layout * @param {Array} arr * @param {string} tag * @return {number} */ searchTag: searchTag, /** * Binary search in a list of numbers * @instance * @function binSearch * @memberof opentype.Layout * @param {Array} arr * @param {number} value * @return {number} */ binSearch: binSearch, /** * Get or create the Layout table (GSUB, GPOS etc). * @param {boolean} create - Whether to create a new one. * @return {Object} The GSUB or GPOS table. */ getTable: function(create) { var layout = this.font.tables[this.tableName]; if (!layout && create) { layout = this.font.tables[this.tableName] = this.createDefaultTable(); } return layout; }, /** * Returns all scripts in the substitution table. * @instance * @return {Array} */ getScriptNames: function() { var layout = this.getTable(); if (!layout) { return []; } return layout.scripts.map(function(script) { return script.tag; }); }, /** * Returns the best bet for a script name. * Returns 'DFLT' if it exists. * If not, returns 'latn' if it exists. * If neither exist, returns undefined. */ getDefaultScriptName: function() { var layout = this.getTable(); if (!layout) { return; } var hasLatn = false; for (var i = 0; i < layout.scripts.length; i++) { var name = layout.scripts[i].tag; if (name === 'DFLT') return name; if (name === 'latn') hasLatn = true; } if (hasLatn) return 'latn'; }, /** * Returns all LangSysRecords in the given script. * @instance * @param {string} [script='DFLT'] * @param {boolean} create - forces the creation of this script table if it doesn't exist. * @return {Object} An object with tag and script properties. */ getScriptTable: function(script, create) { var layout = this.getTable(create); if (layout) { script = script || 'DFLT'; var scripts = layout.scripts; var pos = searchTag(layout.scripts, script); if (pos >= 0) { return scripts[pos].script; } else if (create) { var scr = { tag: script, script: { defaultLangSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [] }, langSysRecords: [] } }; scripts.splice(-1 - pos, 0, scr); return scr.script; } } }, /** * Returns a language system table * @instance * @param {string} [script='DFLT'] * @param {string} [language='dlft'] * @param {boolean} create - forces the creation of this langSysTable if it doesn't exist. * @return {Object} */ getLangSysTable: function(script, language, create) { var scriptTable = this.getScriptTable(script, create); if (scriptTable) { if (!language || language === 'dflt' || language === 'DFLT') { return scriptTable.defaultLangSys; } var pos = searchTag(scriptTable.langSysRecords, language); if (pos >= 0) { return scriptTable.langSysRecords[pos].langSys; } else if (create) { var langSysRecord = { tag: language, langSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [] } }; scriptTable.langSysRecords.splice(-1 - pos, 0, langSysRecord); return langSysRecord.langSys; } } }, /** * Get a specific feature table. * @instance * @param {string} [script='DFLT'] * @param {string} [language='dlft'] * @param {string} feature - One of the codes listed at https://www.microsoft.com/typography/OTSPEC/featurelist.htm * @param {boolean} create - forces the creation of the feature table if it doesn't exist. * @return {Object} */ getFeatureTable: function(script, language, feature, create) { var langSysTable = this.getLangSysTable(script, language, create); if (langSysTable) { var featureRecord; var featIndexes = langSysTable.featureIndexes; var allFeatures = this.font.tables[this.tableName].features; // The FeatureIndex array of indices is in arbitrary order, // even if allFeatures is sorted alphabetically by feature tag. for (var i = 0; i < featIndexes.length; i++) { featureRecord = allFeatures[featIndexes[i]]; if (featureRecord.tag === feature) { return featureRecord.feature; } } if (create) { var index = allFeatures.length; // Automatic ordering of features would require to shift feature indexes in the script list. check.assert(index === 0 || feature >= allFeatures[index - 1].tag, 'Features must be added in alphabetical order.'); featureRecord = { tag: feature, feature: { params: 0, lookupListIndexes: [] } }; allFeatures.push(featureRecord); featIndexes.push(index); return featureRecord.feature; } } }, /** * Get the lookup tables of a given type for a script/language/feature. * @instance * @param {string} [script='DFLT'] * @param {string} [language='dlft'] * @param {string} feature - 4-letter feature code * @param {number} lookupType - 1 to 8 * @param {boolean} create - forces the creation of the lookup table if it doesn't exist, with no subtables. * @return {Object[]} */ getLookupTables: function(script, language, feature, lookupType, create) { var featureTable = this.getFeatureTable(script, language, feature, create); var tables = []; if (featureTable) { var lookupTable; var lookupListIndexes = featureTable.lookupListIndexes; var allLookups = this.font.tables[this.tableName].lookups; // lookupListIndexes are in no particular order, so use naïve search. for (var i = 0; i < lookupListIndexes.length; i++) { lookupTable = allLookups[lookupListIndexes[i]]; if (lookupTable.lookupType === lookupType) { tables.push(lookupTable); } } if (tables.length === 0 && create) { lookupTable = { lookupType: lookupType, lookupFlag: 0, subtables: [], markFilteringSet: undefined }; var index = allLookups.length; allLookups.push(lookupTable); lookupListIndexes.push(index); return [lookupTable]; } } return tables; }, /** * Returns the list of glyph indexes of a coverage table. * Format 1: the list is stored raw * Format 2: compact list as range records. * @instance * @param {Object} coverageTable * @return {Array} */ expandCoverage: function(coverageTable) { if (coverageTable.format === 1) { return coverageTable.glyphs; } else { var glyphs = []; var ranges = coverageTable.ranges; for (var i = 0; i < ranges.length; i++) { var range = ranges[i]; var start = range.start; var end = range.end; for (var j = start; j <= end; j++) { glyphs.push(j); } } return glyphs; } } }; module.exports = Layout; },{"./check":7}],15:[function(_dereq_,module,exports){ // opentype.js // https://github.com/nodebox/opentype.js // (c) 2015 Frederik De Bleser // opentype.js may be freely distributed under the MIT license. /* global DataView, Uint8Array, XMLHttpRequest */ 'use strict'; var inflate = _dereq_('tiny-inflate'); var encoding = _dereq_('./encoding'); var _font = _dereq_('./font'); var glyph = _dereq_('./glyph'); var parse = _dereq_('./parse'); var bbox = _dereq_('./bbox'); var path = _dereq_('./path'); var util = _dereq_('./util'); var cmap = _dereq_('./tables/cmap'); var cff = _dereq_('./tables/cff'); var fvar = _dereq_('./tables/fvar'); var glyf = _dereq_('./tables/glyf'); var gpos = _dereq_('./tables/gpos'); var gsub = _dereq_('./tables/gsub'); var head = _dereq_('./tables/head'); var hhea = _dereq_('./tables/hhea'); var hmtx = _dereq_('./tables/hmtx'); var kern = _dereq_('./tables/kern'); var ltag = _dereq_('./tables/ltag'); var loca = _dereq_('./tables/loca'); var maxp = _dereq_('./tables/maxp'); var _name = _dereq_('./tables/name'); var os2 = _dereq_('./tables/os2'); var post = _dereq_('./tables/post'); var meta = _dereq_('./tables/meta'); /** * The opentype library. * @namespace opentype */ // File loaders ///////////////////////////////////////////////////////// /** * Loads a font from a file. The callback throws an error message as the first parameter if it fails * and the font as an ArrayBuffer in the second parameter if it succeeds. * @param {string} path - The path of the file * @param {Function} callback - The function to call when the font load completes */ function loadFromFile(path, callback) { var fs = _dereq_('fs'); fs.readFile(path, function(err, buffer) { if (err) { return callback(err.message); } callback(null, util.nodeBufferToArrayBuffer(buffer)); }); } /** * Loads a font from a URL. The callback throws an error message as the first parameter if it fails * and the font as an ArrayBuffer in the second parameter if it succeeds. * @param {string} url - The URL of the font file. * @param {Function} callback - The function to call when the font load completes */ function loadFromUrl(url, callback) { var request = new XMLHttpRequest(); request.open('get', url, true); request.responseType = 'arraybuffer'; request.onload = function() { if (request.status !== 200) { return callback('Font could not be loaded: ' + request.statusText); } return callback(null, request.response); }; request.onerror = function () { callback('Font could not be loaded'); }; request.send(); } // Table Directory Entries ////////////////////////////////////////////// /** * Parses OpenType table entries. * @param {DataView} * @param {Number} * @return {Object[]} */ function parseOpenTypeTableEntries(data, numTables) { var tableEntries = []; var p = 12; for (var i = 0; i < numTables; i += 1) { var tag = parse.getTag(data, p); var checksum = parse.getULong(data, p + 4); var offset = parse.getULong(data, p + 8); var length = parse.getULong(data, p + 12); tableEntries.push({tag: tag, checksum: checksum, offset: offset, length: length, compression: false}); p += 16; } return tableEntries; } /** * Parses WOFF table entries. * @param {DataView} * @param {Number} * @return {Object[]} */ function parseWOFFTableEntries(data, numTables) { var tableEntries = []; var p = 44; // offset to the first table directory entry. for (var i = 0; i < numTables; i += 1) { var tag = parse.getTag(data, p); var offset = parse.getULong(data, p + 4); var compLength = parse.getULong(data, p + 8); var origLength = parse.getULong(data, p + 12); var compression; if (compLength < origLength) { compression = 'WOFF'; } else { compression = false; } tableEntries.push({tag: tag, offset: offset, compression: compression, compressedLength: compLength, originalLength: origLength}); p += 20; } return tableEntries; } /** * @typedef TableData * @type Object * @property {DataView} data - The DataView * @property {number} offset - The data offset. */ /** * @param {DataView} * @param {Object} * @return {TableData} */ function uncompressTable(data, tableEntry) { if (tableEntry.compression === 'WOFF') { var inBuffer = new Uint8Array(data.buffer, tableEntry.offset + 2, tableEntry.compressedLength - 2); var outBuffer = new Uint8Array(tableEntry.originalLength); inflate(inBuffer, outBuffer); if (outBuffer.byteLength !== tableEntry.originalLength) { throw new Error('Decompression error: ' + tableEntry.tag + ' decompressed length doesn\'t match recorded length'); } var view = new DataView(outBuffer.buffer, 0); return {data: view, offset: 0}; } else { return {data: data, offset: tableEntry.offset}; } } // Public API /////////////////////////////////////////////////////////// /** * Parse the OpenType file data (as an ArrayBuffer) and return a Font object. * Throws an error if the font could not be parsed. * @param {ArrayBuffer} * @return {opentype.Font} */ function parseBuffer(buffer) { var indexToLocFormat; var ltagTable; // Since the constructor can also be called to create new fonts from scratch, we indicate this // should be an empty font that we'll fill with our own data. var font = new _font.Font({empty: true}); // OpenType fonts use big endian byte ordering. // We can't rely on typed array view types, because they operate with the endianness of the host computer. // Instead we use DataViews where we can specify endianness. var data = new DataView(buffer, 0); var numTables; var tableEntries = []; var signature = parse.getTag(data, 0); if (signature === String.fromCharCode(0, 1, 0, 0) || signature === 'true' || signature === 'typ1') { font.outlinesFormat = 'truetype'; numTables = parse.getUShort(data, 4); tableEntries = parseOpenTypeTableEntries(data, numTables); } else if (signature === 'OTTO') { font.outlinesFormat = 'cff'; numTables = parse.getUShort(data, 4); tableEntries = parseOpenTypeTableEntries(data, numTables); } else if (signature === 'wOFF') { var flavor = parse.getTag(data, 4); if (flavor === String.fromCharCode(0, 1, 0, 0)) { font.outlinesFormat = 'truetype'; } else if (flavor === 'OTTO') { font.outlinesFormat = 'cff'; } else { throw new Error('Unsupported OpenType flavor ' + signature); } numTables = parse.getUShort(data, 12); tableEntries = parseWOFFTableEntries(data, numTables); } else { throw new Error('Unsupported OpenType signature ' + signature); } var cffTableEntry; var fvarTableEntry; var glyfTableEntry; var gposTableEntry; var gsubTableEntry; var hmtxTableEntry; var kernTableEntry; var locaTableEntry; var nameTableEntry; var metaTableEntry; var p; for (var i = 0; i < numTables; i += 1) { var tableEntry = tableEntries[i]; var table; switch (tableEntry.tag) { case 'cmap': table = uncompressTable(data, tableEntry); font.tables.cmap = cmap.parse(table.data, table.offset); font.encoding = new encoding.CmapEncoding(font.tables.cmap); break; case 'cvt ' : table = uncompressTable(data, tableEntry); p = new parse.Parser(table.data, table.offset); font.tables.cvt = p.parseShortList(tableEntry.length / 2); break; case 'fvar': fvarTableEntry = tableEntry; break; case 'fpgm' : table = uncompressTable(data, tableEntry); p = new parse.Parser(table.data, table.offset); font.tables.fpgm = p.parseByteList(tableEntry.length); break; case 'head': table = uncompressTable(data, tableEntry); font.tables.head = head.parse(table.data, table.offset); font.unitsPerEm = font.tables.head.unitsPerEm; indexToLocFormat = font.tables.head.indexToLocFormat; break; case 'hhea': table = uncompressTable(data, tableEntry); font.tables.hhea = hhea.parse(table.data, table.offset); font.ascender = font.tables.hhea.ascender; font.descender = font.tables.hhea.descender; font.numberOfHMetrics = font.tables.hhea.numberOfHMetrics; break; case 'hmtx': hmtxTableEntry = tableEntry; break; case 'ltag': table = uncompressTable(data, tableEntry); ltagTable = ltag.parse(table.data, table.offset); break; case 'maxp': table = uncompressTable(data, tableEntry); font.tables.maxp = maxp.parse(table.data, table.offset); font.numGlyphs = font.tables.maxp.numGlyphs; break; case 'name': nameTableEntry = tableEntry; break; case 'OS/2': table = uncompressTable(data, tableEntry); font.tables.os2 = os2.parse(table.data, table.offset); break; case 'post': table = uncompressTable(data, tableEntry); font.tables.post = post.parse(table.data, table.offset); font.glyphNames = new encoding.GlyphNames(font.tables.post); break; case 'prep' : table = uncompressTable(data, tableEntry); p = new parse.Parser(table.data, table.offset); font.tables.prep = p.parseByteList(tableEntry.length); break; case 'glyf': glyfTableEntry = tableEntry; break; case 'loca': locaTableEntry = tableEntry; break; case 'CFF ': cffTableEntry = tableEntry; break; case 'kern': kernTableEntry = tableEntry; break; case 'GPOS': gposTableEntry = tableEntry; break; case 'GSUB': gsubTableEntry = tableEntry; break; case 'meta': metaTableEntry = tableEntry; break; } } var nameTable = uncompressTable(data, nameTableEntry); font.tables.name = _name.parse(nameTable.data, nameTable.offset, ltagTable); font.names = font.tables.name; if (glyfTableEntry && locaTableEntry) { var shortVersion = indexToLocFormat === 0; var locaTable = uncompressTable(data, locaTableEntry); var locaOffsets = loca.parse(locaTable.data, locaTable.offset, font.numGlyphs, shortVersion); var glyfTable = uncompressTable(data, glyfTableEntry); font.glyphs = glyf.parse(glyfTable.data, glyfTable.offset, locaOffsets, font); } else if (cffTableEntry) { var cffTable = uncompressTable(data, cffTableEntry); cff.parse(cffTable.data, cffTable.offset, font); } else { throw new Error('Font doesn\'t contain TrueType or CFF outlines.'); } var hmtxTable = uncompressTable(data, hmtxTableEntry); hmtx.parse(hmtxTable.data, hmtxTable.offset, font.numberOfHMetrics, font.numGlyphs, font.glyphs); encoding.addGlyphNames(font); if (kernTableEntry) { var kernTable = uncompressTable(data, kernTableEntry); font.kerningPairs = kern.parse(kernTable.data, kernTable.offset); } else { font.kerningPairs = {}; } if (gposTableEntry) { var gposTable = uncompressTable(data, gposTableEntry); gpos.parse(gposTable.data, gposTable.offset, font); } if (gsubTableEntry) { var gsubTable = uncompressTable(data, gsubTableEntry); font.tables.gsub = gsub.parse(gsubTable.data, gsubTable.offset); } if (fvarTableEntry) { var fvarTable = uncompressTable(data, fvarTableEntry); font.tables.fvar = fvar.parse(fvarTable.data, fvarTable.offset, font.names); } if (metaTableEntry) { var metaTable = uncompressTable(data, metaTableEntry); font.tables.meta = meta.parse(metaTable.data, metaTable.offset); font.metas = font.tables.meta; } return font; } /** * Asynchronously load the font from a URL or a filesystem. When done, call the callback * with two arguments `(err, font)`. The `err` will be null on success, * the `font` is a Font object. * We use the node.js callback convention so that * opentype.js can integrate with frameworks like async.js. * @alias opentype.load * @param {string} url - The URL of the font to load. * @param {Function} callback - The callback. */ function load(url, callback) { var isNode = typeof window === 'undefined'; var loadFn = isNode ? loadFromFile : loadFromUrl; loadFn(url, function(err, arrayBuffer) { if (err) { return callback(err); } var font; try { font = parseBuffer(arrayBuffer); } catch (e) { return callback(e, null); } return callback(null, font); }); } /** * Synchronously load the font from a URL or file. * When done, returns the font object or throws an error. * @alias opentype.loadSync * @param {string} url - The URL of the font to load. * @return {opentype.Font} */ function loadSync(url) { var fs = _dereq_('fs'); var buffer = fs.readFileSync(url); return parseBuffer(util.nodeBufferToArrayBuffer(buffer)); } exports._parse = parse; exports.Font = _font.Font; exports.Glyph = glyph.Glyph; exports.Path = path.Path; exports.BoundingBox = bbox.BoundingBox; exports.parse = parseBuffer; exports.load = load; exports.loadSync = loadSync; },{"./bbox":6,"./encoding":9,"./font":10,"./glyph":11,"./parse":16,"./path":17,"./tables/cff":20,"./tables/cmap":21,"./tables/fvar":22,"./tables/glyf":23,"./tables/gpos":24,"./tables/gsub":25,"./tables/head":26,"./tables/hhea":27,"./tables/hmtx":28,"./tables/kern":29,"./tables/loca":30,"./tables/ltag":31,"./tables/maxp":32,"./tables/meta":33,"./tables/name":34,"./tables/os2":35,"./tables/post":36,"./util":39,"fs":2,"tiny-inflate":40}],16:[function(_dereq_,module,exports){ // Parsing utility functions 'use strict'; var check = _dereq_('./check'); // Retrieve an unsigned byte from the DataView. exports.getByte = function getByte(dataView, offset) { return dataView.getUint8(offset); }; exports.getCard8 = exports.getByte; // Retrieve an unsigned 16-bit short from the DataView. // The value is stored in big endian. function getUShort(dataView, offset) { return dataView.getUint16(offset, false); } exports.getUShort = exports.getCard16 = getUShort; // Retrieve a signed 16-bit short from the DataView. // The value is stored in big endian. exports.getShort = function(dataView, offset) { return dataView.getInt16(offset, false); }; // Retrieve an unsigned 32-bit long from the DataView. // The value is stored in big endian. exports.getULong = function(dataView, offset) { return dataView.getUint32(offset, false); }; // Retrieve a 32-bit signed fixed-point number (16.16) from the DataView. // The value is stored in big endian. exports.getFixed = function(dataView, offset) { var decimal = dataView.getInt16(offset, false); var fraction = dataView.getUint16(offset + 2, false); return decimal + fraction / 65535; }; // Retrieve a 4-character tag from the DataView. // Tags are used to identify tables. exports.getTag = function(dataView, offset) { var tag = ''; for (var i = offset; i < offset + 4; i += 1) { tag += String.fromCharCode(dataView.getInt8(i)); } return tag; }; // Retrieve an offset from the DataView. // Offsets are 1 to 4 bytes in length, depending on the offSize argument. exports.getOffset = function(dataView, offset, offSize) { var v = 0; for (var i = 0; i < offSize; i += 1) { v <<= 8; v += dataView.getUint8(offset + i); } return v; }; // Retrieve a number of bytes from start offset to the end offset from the DataView. exports.getBytes = function(dataView, startOffset, endOffset) { var bytes = []; for (var i = startOffset; i < endOffset; i += 1) { bytes.push(dataView.getUint8(i)); } return bytes; }; // Convert the list of bytes to a string. exports.bytesToString = function(bytes) { var s = ''; for (var i = 0; i < bytes.length; i += 1) { s += String.fromCharCode(bytes[i]); } return s; }; var typeOffsets = { byte: 1, uShort: 2, short: 2, uLong: 4, fixed: 4, longDateTime: 8, tag: 4 }; // A stateful parser that changes the offset whenever a value is retrieved. // The data is a DataView. function Parser(data, offset) { this.data = data; this.offset = offset; this.relativeOffset = 0; } Parser.prototype.parseByte = function() { var v = this.data.getUint8(this.offset + this.relativeOffset); this.relativeOffset += 1; return v; }; Parser.prototype.parseChar = function() { var v = this.data.getInt8(this.offset + this.relativeOffset); this.relativeOffset += 1; return v; }; Parser.prototype.parseCard8 = Parser.prototype.parseByte; Parser.prototype.parseUShort = function() { var v = this.data.getUint16(this.offset + this.relativeOffset); this.relativeOffset += 2; return v; }; Parser.prototype.parseCard16 = Parser.prototype.parseUShort; Parser.prototype.parseSID = Parser.prototype.parseUShort; Parser.prototype.parseOffset16 = Parser.prototype.parseUShort; Parser.prototype.parseShort = function() { var v = this.data.getInt16(this.offset + this.relativeOffset); this.relativeOffset += 2; return v; }; Parser.prototype.parseF2Dot14 = function() { var v = this.data.getInt16(this.offset + this.relativeOffset) / 16384; this.relativeOffset += 2; return v; }; Parser.prototype.parseULong = function() { var v = exports.getULong(this.data, this.offset + this.relativeOffset); this.relativeOffset += 4; return v; }; Parser.prototype.parseFixed = function() { var v = exports.getFixed(this.data, this.offset + this.relativeOffset); this.relativeOffset += 4; return v; }; Parser.prototype.parseString = function(length) { var dataView = this.data; var offset = this.offset + this.relativeOffset; var string = ''; this.relativeOffset += length; for (var i = 0; i < length; i++) { string += String.fromCharCode(dataView.getUint8(offset + i)); } return string; }; Parser.prototype.parseTag = function() { return this.parseString(4); }; // LONGDATETIME is a 64-bit integer. // JavaScript and unix timestamps traditionally use 32 bits, so we // only take the last 32 bits. // + Since until 2038 those bits will be filled by zeros we can ignore them. Parser.prototype.parseLongDateTime = function() { var v = exports.getULong(this.data, this.offset + this.relativeOffset + 4); // Subtract seconds between 01/01/1904 and 01/01/1970 // to convert Apple Mac timstamp to Standard Unix timestamp v -= 2082844800; this.relativeOffset += 8; return v; }; Parser.prototype.parseVersion = function() { var major = getUShort(this.data, this.offset + this.relativeOffset); // How to interpret the minor version is very vague in the spec. 0x5000 is 5, 0x1000 is 1 // This returns the correct number if minor = 0xN000 where N is 0-9 var minor = getUShort(this.data, this.offset + this.relativeOffset + 2); this.relativeOffset += 4; return major + minor / 0x1000 / 10; }; Parser.prototype.skip = function(type, amount) { if (amount === undefined) { amount = 1; } this.relativeOffset += typeOffsets[type] * amount; }; ///// Parsing lists and records /////////////////////////////// // Parse a list of 16 bit unsigned integers. The length of the list can be read on the stream // or provided as an argument. Parser.prototype.parseOffset16List = Parser.prototype.parseUShortList = function(count) { if (count === undefined) { count = this.parseUShort(); } var offsets = new Array(count); var dataView = this.data; var offset = this.offset + this.relativeOffset; for (var i = 0; i < count; i++) { offsets[i] = dataView.getUint16(offset); offset += 2; } this.relativeOffset += count * 2; return offsets; }; // Parses a list of 16 bit signed integers. Parser.prototype.parseShortList = function(count) { var list = new Array(count); var dataView = this.data; var offset = this.offset + this.relativeOffset; for (var i = 0; i < count; i++) { list[i] = dataView.getInt16(offset); offset += 2; } this.relativeOffset += count * 2; return list; }; // Parses a list of bytes. Parser.prototype.parseByteList = function(count) { var list = new Array(count); var dataView = this.data; var offset = this.offset + this.relativeOffset; for (var i = 0; i < count; i++) { list[i] = dataView.getUint8(offset++); } this.relativeOffset += count; return list; }; /** * Parse a list of items. * Record count is optional, if omitted it is read from the stream. * itemCallback is one of the Parser methods. */ Parser.prototype.parseList = function(count, itemCallback) { if (!itemCallback) { itemCallback = count; count = this.parseUShort(); } var list = new Array(count); for (var i = 0; i < count; i++) { list[i] = itemCallback.call(this); } return list; }; /** * Parse a list of records. * Record count is optional, if omitted it is read from the stream. * Example of recordDescription: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort } */ Parser.prototype.parseRecordList = function(count, recordDescription) { // If the count argument is absent, read it in the stream. if (!recordDescription) { recordDescription = count; count = this.parseUShort(); } var records = new Array(count); var fields = Object.keys(recordDescription); for (var i = 0; i < count; i++) { var rec = {}; for (var j = 0; j < fields.length; j++) { var fieldName = fields[j]; var fieldType = recordDescription[fieldName]; rec[fieldName] = fieldType.call(this); } records[i] = rec; } return records; }; // Parse a data structure into an object // Example of description: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort } Parser.prototype.parseStruct = function(description) { if (typeof description === 'function') { return description.call(this); } else { var fields = Object.keys(description); var struct = {}; for (var j = 0; j < fields.length; j++) { var fieldName = fields[j]; var fieldType = description[fieldName]; struct[fieldName] = fieldType.call(this); } return struct; } }; Parser.prototype.parsePointer = function(description) { var structOffset = this.parseOffset16(); if (structOffset > 0) { // NULL offset => return indefined return new Parser(this.data, this.offset + structOffset).parseStruct(description); } }; /** * Parse a list of offsets to lists of 16-bit integers, * or a list of offsets to lists of offsets to any kind of items. * If itemCallback is not provided, a list of list of UShort is assumed. * If provided, itemCallback is called on each item and must parse the item. * See examples in tables/gsub.js */ Parser.prototype.parseListOfLists = function(itemCallback) { var offsets = this.parseOffset16List(); var count = offsets.length; var relativeOffset = this.relativeOffset; var list = new Array(count); for (var i = 0; i < count; i++) { var start = offsets[i]; if (start === 0) { // NULL offset list[i] = undefined; // Add i as owned property to list. Convenient with assert. continue; } this.relativeOffset = start; if (itemCallback) { var subOffsets = this.parseOffset16List(); var subList = new Array(subOffsets.length); for (var j = 0; j < subOffsets.length; j++) { this.relativeOffset = start + subOffsets[j]; subList[j] = itemCallback.call(this); } list[i] = subList; } else { list[i] = this.parseUShortList(); } } this.relativeOffset = relativeOffset; return list; }; ///// Complex tables parsing ////////////////////////////////// // Parse a coverage table in a GSUB, GPOS or GDEF table. // https://www.microsoft.com/typography/OTSPEC/chapter2.htm // parser.offset must point to the start of the table containing the coverage. Parser.prototype.parseCoverage = function() { var startOffset = this.offset + this.relativeOffset; var format = this.parseUShort(); var count = this.parseUShort(); if (format === 1) { return { format: 1, glyphs: this.parseUShortList(count) }; } else if (format === 2) { var ranges = new Array(count); for (var i = 0; i < count; i++) { ranges[i] = { start: this.parseUShort(), end: this.parseUShort(), index: this.parseUShort() }; } return { format: 2, ranges: ranges }; } check.assert(false, '0x' + startOffset.toString(16) + ': Coverage format must be 1 or 2.'); }; // Parse a Class Definition Table in a GSUB, GPOS or GDEF table. // https://www.microsoft.com/typography/OTSPEC/chapter2.htm Parser.prototype.parseClassDef = function() { var startOffset = this.offset + this.relativeOffset; var format = this.parseUShort(); if (format === 1) { return { format: 1, startGlyph: this.parseUShort(), classes: this.parseUShortList() }; } else if (format === 2) { return { format: 2, ranges: this.parseRecordList({ start: Parser.uShort, end: Parser.uShort, classId: Parser.uShort }) }; } check.assert(false, '0x' + startOffset.toString(16) + ': ClassDef format must be 1 or 2.'); }; ///// Static methods /////////////////////////////////// // These convenience methods can be used as callbacks and should be called with "this" context set to a Parser instance. Parser.list = function(count, itemCallback) { return function() { return this.parseList(count, itemCallback); }; }; Parser.recordList = function(count, recordDescription) { return function() { return this.parseRecordList(count, recordDescription); }; }; Parser.pointer = function(description) { return function() { return this.parsePointer(description); }; }; Parser.tag = Parser.prototype.parseTag; Parser.byte = Parser.prototype.parseByte; Parser.uShort = Parser.offset16 = Parser.prototype.parseUShort; Parser.uShortList = Parser.prototype.parseUShortList; Parser.struct = Parser.prototype.parseStruct; Parser.coverage = Parser.prototype.parseCoverage; Parser.classDef = Parser.prototype.parseClassDef; ///// Script, Feature, Lookup lists /////////////////////////////////////////////// // https://www.microsoft.com/typography/OTSPEC/chapter2.htm var langSysTable = { reserved: Parser.uShort, reqFeatureIndex: Parser.uShort, featureIndexes: Parser.uShortList }; Parser.prototype.parseScriptList = function() { return this.parsePointer(Parser.recordList({ tag: Parser.tag, script: Parser.pointer({ defaultLangSys: Parser.pointer(langSysTable), langSysRecords: Parser.recordList({ tag: Parser.tag, langSys: Parser.pointer(langSysTable) }) }) })); }; Parser.prototype.parseFeatureList = function() { return this.parsePointer(Parser.recordList({ tag: Parser.tag, feature: Parser.pointer({ featureParams: Parser.offset16, lookupListIndexes: Parser.uShortList }) })); }; Parser.prototype.parseLookupList = function(lookupTableParsers) { return this.parsePointer(Parser.list(Parser.pointer(function() { var lookupType = this.parseUShort(); check.argument(1 <= lookupType && lookupType <= 8, 'GSUB lookup type ' + lookupType + ' unknown.'); var lookupFlag = this.parseUShort(); var useMarkFilteringSet = lookupFlag & 0x10; return { lookupType: lookupType, lookupFlag: lookupFlag, subtables: this.parseList(Parser.pointer(lookupTableParsers[lookupType])), markFilteringSet: useMarkFilteringSet ? this.parseUShort() : undefined }; }))); }; exports.Parser = Parser; },{"./check":7}],17:[function(_dereq_,module,exports){ // Geometric objects 'use strict'; var bbox = _dereq_('./bbox'); /** * A bézier path containing a set of path commands similar to a SVG path. * Paths can be drawn on a context using `draw`. * @exports opentype.Path * @class * @constructor */ function Path() { this.commands = []; this.fill = 'black'; this.stroke = null; this.strokeWidth = 1; } /** * @param {number} x * @param {number} y */ Path.prototype.moveTo = function(x, y) { this.commands.push({ type: 'M', x: x, y: y }); }; /** * @param {number} x * @param {number} y */ Path.prototype.lineTo = function(x, y) { this.commands.push({ type: 'L', x: x, y: y }); }; /** * Draws cubic curve * @function * curveTo * @memberof opentype.Path.prototype * @param {number} x1 - x of control 1 * @param {number} y1 - y of control 1 * @param {number} x2 - x of control 2 * @param {number} y2 - y of control 2 * @param {number} x - x of path point * @param {number} y - y of path point */ /** * Draws cubic curve * @function * bezierCurveTo * @memberof opentype.Path.prototype * @param {number} x1 - x of control 1 * @param {number} y1 - y of control 1 * @param {number} x2 - x of control 2 * @param {number} y2 - y of control 2 * @param {number} x - x of path point * @param {number} y - y of path point * @see curveTo */ Path.prototype.curveTo = Path.prototype.bezierCurveTo = function(x1, y1, x2, y2, x, y) { this.commands.push({ type: 'C', x1: x1, y1: y1, x2: x2, y2: y2, x: x, y: y }); }; /** * Draws quadratic curve * @function * quadraticCurveTo * @memberof opentype.Path.prototype * @param {number} x1 - x of control * @param {number} y1 - y of control * @param {number} x - x of path point * @param {number} y - y of path point */ /** * Draws quadratic curve * @function * quadTo * @memberof opentype.Path.prototype * @param {number} x1 - x of control * @param {number} y1 - y of control * @param {number} x - x of path point * @param {number} y - y of path point */ Path.prototype.quadTo = Path.prototype.quadraticCurveTo = function(x1, y1, x, y) { this.commands.push({ type: 'Q', x1: x1, y1: y1, x: x, y: y }); }; /** * Closes the path * @function closePath * @memberof opentype.Path.prototype */ /** * Close the path * @function close * @memberof opentype.Path.prototype */ Path.prototype.close = Path.prototype.closePath = function() { this.commands.push({ type: 'Z' }); }; /** * Add the given path or list of commands to the commands of this path. * @param {Array} pathOrCommands - another opentype.Path, an opentype.BoundingBox, or an array of commands. */ Path.prototype.extend = function(pathOrCommands) { if (pathOrCommands.commands) { pathOrCommands = pathOrCommands.commands; } else if (pathOrCommands instanceof bbox.BoundingBox) { var box = pathOrCommands; this.moveTo(box.x1, box.y1); this.lineTo(box.x2, box.y1); this.lineTo(box.x2, box.y2); this.lineTo(box.x1, box.y2); this.close(); return; } Array.prototype.push.apply(this.commands, pathOrCommands); }; /** * Calculate the bounding box of the path. * @returns {opentype.BoundingBox} */ Path.prototype.getBoundingBox = function() { var box = new bbox.BoundingBox(); var startX = 0; var startY = 0; var prevX = 0; var prevY = 0; for (var i = 0; i < this.commands.length; i++) { var cmd = this.commands[i]; switch (cmd.type) { case 'M': box.addPoint(cmd.x, cmd.y); startX = prevX = cmd.x; startY = prevY = cmd.y; break; case 'L': box.addPoint(cmd.x, cmd.y); prevX = cmd.x; prevY = cmd.y; break; case 'Q': box.addQuad(prevX, prevY, cmd.x1, cmd.y1, cmd.x, cmd.y); prevX = cmd.x; prevY = cmd.y; break; case 'C': box.addBezier(prevX, prevY, cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); prevX = cmd.x; prevY = cmd.y; break; case 'Z': prevX = startX; prevY = startY; break; default: throw new Error('Unexpected path commmand ' + cmd.type); } } if (box.isEmpty()) { box.addPoint(0, 0); } return box; }; /** * Draw the path to a 2D context. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context. */ Path.prototype.draw = function(ctx) { ctx.beginPath(); for (var i = 0; i < this.commands.length; i += 1) { var cmd = this.commands[i]; if (cmd.type === 'M') { ctx.moveTo(cmd.x, cmd.y); } else if (cmd.type === 'L') { ctx.lineTo(cmd.x, cmd.y); } else if (cmd.type === 'C') { ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); } else if (cmd.type === 'Q') { ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y); } else if (cmd.type === 'Z') { ctx.closePath(); } } if (this.fill) { ctx.fillStyle = this.fill; ctx.fill(); } if (this.stroke) { ctx.strokeStyle = this.stroke; ctx.lineWidth = this.strokeWidth; ctx.stroke(); } }; /** * Convert the Path to a string of path data instructions * See http://www.w3.org/TR/SVG/paths.html#PathData * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values * @return {string} */ Path.prototype.toPathData = function(decimalPlaces) { decimalPlaces = decimalPlaces !== undefined ? decimalPlaces : 2; function floatToString(v) { if (Math.round(v) === v) { return '' + Math.round(v); } else { return v.toFixed(decimalPlaces); } } function packValues() { var s = ''; for (var i = 0; i < arguments.length; i += 1) { var v = arguments[i]; if (v >= 0 && i > 0) { s += ' '; } s += floatToString(v); } return s; } var d = ''; for (var i = 0; i < this.commands.length; i += 1) { var cmd = this.commands[i]; if (cmd.type === 'M') { d += 'M' + packValues(cmd.x, cmd.y); } else if (cmd.type === 'L') { d += 'L' + packValues(cmd.x, cmd.y); } else if (cmd.type === 'C') { d += 'C' + packValues(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); } else if (cmd.type === 'Q') { d += 'Q' + packValues(cmd.x1, cmd.y1, cmd.x, cmd.y); } else if (cmd.type === 'Z') { d += 'Z'; } } return d; }; /** * Convert the path to an SVG element, as a string. * @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values * @return {string} */ Path.prototype.toSVG = function(decimalPlaces) { var svg = '= 0) { // ligatureSet already exists var ligatureSet = subtable.ligatureSets[pos]; for (var i = 0; i < ligatureSet.length; i++) { // If ligature already exists, return. if (arraysEqual(ligatureSet[i].components, ligComponents)) { return; } } // ligature does not exist: add it. ligatureSet.push(ligatureTable); } else { // Create a new ligatureSet and add coverage for the first glyph. pos = -1 - pos; subtable.coverage.glyphs.splice(pos, 0, coverageGlyph); subtable.ligatureSets.splice(pos, 0, [ligatureTable]); } }; /** * List all feature data for a given script and language. * @param {string} feature - 4-letter feature name * @param {string} [script='DFLT'] * @param {string} [language='dflt'] * @return {Array} substitutions - The list of substitutions. */ Substitution.prototype.getFeature = function(feature, script, language) { if (/ss\d\d/.test(feature)) { // ss01 - ss20 return this.getSingle(feature, script, language); } switch (feature) { case 'aalt': case 'salt': return this.getSingle(feature, script, language) .concat(this.getAlternates(feature, script, language)); case 'dlig': case 'liga': case 'rlig': return this.getLigatures(feature, script, language); } }; /** * Add a substitution to a feature for a given script and language. * @param {string} feature - 4-letter feature name * @param {Object} sub - the substitution to add (an object like { sub: id or [ids], by: id or [ids] }) * @param {string} [script='DFLT'] * @param {string} [language='dflt'] */ Substitution.prototype.add = function(feature, sub, script, language) { if (/ss\d\d/.test(feature)) { // ss01 - ss20 return this.addSingle(feature, sub, script, language); } switch (feature) { case 'aalt': case 'salt': if (typeof sub.by === 'number') { return this.addSingle(feature, sub, script, language); } return this.addAlternate(feature, sub, script, language); case 'dlig': case 'liga': case 'rlig': return this.addLigature(feature, sub, script, language); } }; module.exports = Substitution; },{"./check":7,"./layout":14}],19:[function(_dereq_,module,exports){ // Table metadata 'use strict'; var check = _dereq_('./check'); var encode = _dereq_('./types').encode; var sizeOf = _dereq_('./types').sizeOf; /** * @exports opentype.Table * @class * @param {string} tableName * @param {Array} fields * @param {Object} options * @constructor */ function Table(tableName, fields, options) { var i; for (i = 0; i < fields.length; i += 1) { var field = fields[i]; this[field.name] = field.value; } this.tableName = tableName; this.fields = fields; if (options) { var optionKeys = Object.keys(options); for (i = 0; i < optionKeys.length; i += 1) { var k = optionKeys[i]; var v = options[k]; if (this[k] !== undefined) { this[k] = v; } } } } /** * Encodes the table and returns an array of bytes * @return {Array} */ Table.prototype.encode = function() { return encode.TABLE(this); }; /** * Get the size of the table. * @return {number} */ Table.prototype.sizeOf = function() { return sizeOf.TABLE(this); }; /** * @private */ function ushortList(itemName, list, count) { if (count === undefined) { count = list.length; } var fields = new Array(list.length + 1); fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; for (var i = 0; i < list.length; i++) { fields[i + 1] = {name: itemName + i, type: 'USHORT', value: list[i]}; } return fields; } /** * @private */ function tableList(itemName, records, itemCallback) { var count = records.length; var fields = new Array(count + 1); fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; for (var i = 0; i < count; i++) { fields[i + 1] = {name: itemName + i, type: 'TABLE', value: itemCallback(records[i], i)}; } return fields; } /** * @private */ function recordList(itemName, records, itemCallback) { var count = records.length; var fields = []; fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count}; for (var i = 0; i < count; i++) { fields = fields.concat(itemCallback(records[i], i)); } return fields; } // Common Layout Tables /** * @exports opentype.Coverage * @class * @param {opentype.Table} * @constructor * @extends opentype.Table */ function Coverage(coverageTable) { if (coverageTable.format === 1) { Table.call(this, 'coverageTable', [{name: 'coverageFormat', type: 'USHORT', value: 1}] .concat(ushortList('glyph', coverageTable.glyphs)) ); } else { check.assert(false, 'Can\'t create coverage table format 2 yet.'); } } Coverage.prototype = Object.create(Table.prototype); Coverage.prototype.constructor = Coverage; function ScriptList(scriptListTable) { Table.call(this, 'scriptListTable', recordList('scriptRecord', scriptListTable, function(scriptRecord, i) { var script = scriptRecord.script; var defaultLangSys = script.defaultLangSys; check.assert(!!defaultLangSys, 'Unable to write GSUB: script ' + scriptRecord.tag + ' has no default language system.'); return [ {name: 'scriptTag' + i, type: 'TAG', value: scriptRecord.tag}, {name: 'script' + i, type: 'TABLE', value: new Table('scriptTable', [ {name: 'defaultLangSys', type: 'TABLE', value: new Table('defaultLangSys', [ {name: 'lookupOrder', type: 'USHORT', value: 0}, {name: 'reqFeatureIndex', type: 'USHORT', value: defaultLangSys.reqFeatureIndex}] .concat(ushortList('featureIndex', defaultLangSys.featureIndexes)))} ].concat(recordList('langSys', script.langSysRecords, function(langSysRecord, i) { var langSys = langSysRecord.langSys; return [ {name: 'langSysTag' + i, type: 'TAG', value: langSysRecord.tag}, {name: 'langSys' + i, type: 'TABLE', value: new Table('langSys', [ {name: 'lookupOrder', type: 'USHORT', value: 0}, {name: 'reqFeatureIndex', type: 'USHORT', value: langSys.reqFeatureIndex} ].concat(ushortList('featureIndex', langSys.featureIndexes)))} ]; })))} ]; }) ); } ScriptList.prototype = Object.create(Table.prototype); ScriptList.prototype.constructor = ScriptList; /** * @exports opentype.FeatureList * @class * @param {opentype.Table} * @constructor * @extends opentype.Table */ function FeatureList(featureListTable) { Table.call(this, 'featureListTable', recordList('featureRecord', featureListTable, function(featureRecord, i) { var feature = featureRecord.feature; return [ {name: 'featureTag' + i, type: 'TAG', value: featureRecord.tag}, {name: 'feature' + i, type: 'TABLE', value: new Table('featureTable', [ {name: 'featureParams', type: 'USHORT', value: feature.featureParams}, ].concat(ushortList('lookupListIndex', feature.lookupListIndexes)))} ]; }) ); } FeatureList.prototype = Object.create(Table.prototype); FeatureList.prototype.constructor = FeatureList; /** * @exports opentype.LookupList * @class * @param {opentype.Table} * @param {Object} * @constructor * @extends opentype.Table */ function LookupList(lookupListTable, subtableMakers) { Table.call(this, 'lookupListTable', tableList('lookup', lookupListTable, function(lookupTable) { var subtableCallback = subtableMakers[lookupTable.lookupType]; check.assert(!!subtableCallback, 'Unable to write GSUB lookup type ' + lookupTable.lookupType + ' tables.'); return new Table('lookupTable', [ {name: 'lookupType', type: 'USHORT', value: lookupTable.lookupType}, {name: 'lookupFlag', type: 'USHORT', value: lookupTable.lookupFlag} ].concat(tableList('subtable', lookupTable.subtables, subtableCallback))); })); } LookupList.prototype = Object.create(Table.prototype); LookupList.prototype.constructor = LookupList; // Record = same as Table, but inlined (a Table has an offset and its data is further in the stream) // Don't use offsets inside Records (probable bug), only in Tables. exports.Record = exports.Table = Table; exports.Coverage = Coverage; exports.ScriptList = ScriptList; exports.FeatureList = FeatureList; exports.LookupList = LookupList; exports.ushortList = ushortList; exports.tableList = tableList; exports.recordList = recordList; },{"./check":7,"./types":38}],20:[function(_dereq_,module,exports){ // The `CFF` table contains the glyph outlines in PostScript format. // https://www.microsoft.com/typography/OTSPEC/cff.htm // http://download.microsoft.com/download/8/0/1/801a191c-029d-4af3-9642-555f6fe514ee/cff.pdf // http://download.microsoft.com/download/8/0/1/801a191c-029d-4af3-9642-555f6fe514ee/type2.pdf 'use strict'; var encoding = _dereq_('../encoding'); var glyphset = _dereq_('../glyphset'); var parse = _dereq_('../parse'); var path = _dereq_('../path'); var table = _dereq_('../table'); // Custom equals function that can also check lists. function equals(a, b) { if (a === b) { return true; } else if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) { return false; } for (var i = 0; i < a.length; i += 1) { if (!equals(a[i], b[i])) { return false; } } return true; } else { return false; } } // Subroutines are encoded using the negative half of the number space. // See type 2 chapter 4.7 "Subroutine operators". function calcCFFSubroutineBias(subrs) { var bias; if (subrs.length < 1240) { bias = 107; } else if (subrs.length < 33900) { bias = 1131; } else { bias = 32768; } return bias; } // Parse a `CFF` INDEX array. // An index array consists of a list of offsets, then a list of objects at those offsets. function parseCFFIndex(data, start, conversionFn) { //var i, objectOffset, endOffset; var offsets = []; var objects = []; var count = parse.getCard16(data, start); var i; var objectOffset; var endOffset; if (count !== 0) { var offsetSize = parse.getByte(data, start + 2); objectOffset = start + ((count + 1) * offsetSize) + 2; var pos = start + 3; for (i = 0; i < count + 1; i += 1) { offsets.push(parse.getOffset(data, pos, offsetSize)); pos += offsetSize; } // The total size of the index array is 4 header bytes + the value of the last offset. endOffset = objectOffset + offsets[count]; } else { endOffset = start + 2; } for (i = 0; i < offsets.length - 1; i += 1) { var value = parse.getBytes(data, objectOffset + offsets[i], objectOffset + offsets[i + 1]); if (conversionFn) { value = conversionFn(value); } objects.push(value); } return {objects: objects, startOffset: start, endOffset: endOffset}; } // Parse a `CFF` DICT real value. function parseFloatOperand(parser) { var s = ''; var eof = 15; var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', 'E', 'E-', null, '-']; while (true) { var b = parser.parseByte(); var n1 = b >> 4; var n2 = b & 15; if (n1 === eof) { break; } s += lookup[n1]; if (n2 === eof) { break; } s += lookup[n2]; } return parseFloat(s); } // Parse a `CFF` DICT operand. function parseOperand(parser, b0) { var b1; var b2; var b3; var b4; if (b0 === 28) { b1 = parser.parseByte(); b2 = parser.parseByte(); return b1 << 8 | b2; } if (b0 === 29) { b1 = parser.parseByte(); b2 = parser.parseByte(); b3 = parser.parseByte(); b4 = parser.parseByte(); return b1 << 24 | b2 << 16 | b3 << 8 | b4; } if (b0 === 30) { return parseFloatOperand(parser); } if (b0 >= 32 && b0 <= 246) { return b0 - 139; } if (b0 >= 247 && b0 <= 250) { b1 = parser.parseByte(); return (b0 - 247) * 256 + b1 + 108; } if (b0 >= 251 && b0 <= 254) { b1 = parser.parseByte(); return -(b0 - 251) * 256 - b1 - 108; } throw new Error('Invalid b0 ' + b0); } // Convert the entries returned by `parseDict` to a proper dictionary. // If a value is a list of one, it is unpacked. function entriesToObject(entries) { var o = {}; for (var i = 0; i < entries.length; i += 1) { var key = entries[i][0]; var values = entries[i][1]; var value; if (values.length === 1) { value = values[0]; } else { value = values; } if (o.hasOwnProperty(key)) { throw new Error('Object ' + o + ' already has key ' + key); } o[key] = value; } return o; } // Parse a `CFF` DICT object. // A dictionary contains key-value pairs in a compact tokenized format. function parseCFFDict(data, start, size) { start = start !== undefined ? start : 0; var parser = new parse.Parser(data, start); var entries = []; var operands = []; size = size !== undefined ? size : data.length; while (parser.relativeOffset < size) { var op = parser.parseByte(); // The first byte for each dict item distinguishes between operator (key) and operand (value). // Values <= 21 are operators. if (op <= 21) { // Two-byte operators have an initial escape byte of 12. if (op === 12) { op = 1200 + parser.parseByte(); } entries.push([op, operands]); operands = []; } else { // Since the operands (values) come before the operators (keys), we store all operands in a list // until we encounter an operator. operands.push(parseOperand(parser, op)); } } return entriesToObject(entries); } // Given a String Index (SID), return the value of the string. // Strings below index 392 are standard CFF strings and are not encoded in the font. function getCFFString(strings, index) { if (index <= 390) { index = encoding.cffStandardStrings[index]; } else { index = strings[index - 391]; } return index; } // Interpret a dictionary and return a new dictionary with readable keys and values for missing entries. // This function takes `meta` which is a list of objects containing `operand`, `name` and `default`. function interpretDict(dict, meta, strings) { var newDict = {}; var value; // Because we also want to include missing values, we start out from the meta list // and lookup values in the dict. for (var i = 0; i < meta.length; i += 1) { var m = meta[i]; if (Array.isArray(m.type)) { var values = []; values.length = m.type.length; for (var j = 0; j < m.type.length; j++) { value = dict[m.op] !== undefined ? dict[m.op][j] : undefined; if (value === undefined) { value = m.value !== undefined && m.value[j] !== undefined ? m.value[j] : null; } if (m.type[j] === 'SID') { value = getCFFString(strings, value); } values[j] = value; } newDict[m.name] = values; } else { value = dict[m.op]; if (value === undefined) { value = m.value !== undefined ? m.value : null; } if (m.type === 'SID') { value = getCFFString(strings, value); } newDict[m.name] = value; } } return newDict; } // Parse the CFF header. function parseCFFHeader(data, start) { var header = {}; header.formatMajor = parse.getCard8(data, start); header.formatMinor = parse.getCard8(data, start + 1); header.size = parse.getCard8(data, start + 2); header.offsetSize = parse.getCard8(data, start + 3); header.startOffset = start; header.endOffset = start + 4; return header; } var TOP_DICT_META = [ {name: 'version', op: 0, type: 'SID'}, {name: 'notice', op: 1, type: 'SID'}, {name: 'copyright', op: 1200, type: 'SID'}, {name: 'fullName', op: 2, type: 'SID'}, {name: 'familyName', op: 3, type: 'SID'}, {name: 'weight', op: 4, type: 'SID'}, {name: 'isFixedPitch', op: 1201, type: 'number', value: 0}, {name: 'italicAngle', op: 1202, type: 'number', value: 0}, {name: 'underlinePosition', op: 1203, type: 'number', value: -100}, {name: 'underlineThickness', op: 1204, type: 'number', value: 50}, {name: 'paintType', op: 1205, type: 'number', value: 0}, {name: 'charstringType', op: 1206, type: 'number', value: 2}, {name: 'fontMatrix', op: 1207, type: ['real', 'real', 'real', 'real', 'real', 'real'], value: [0.001, 0, 0, 0.001, 0, 0]}, {name: 'uniqueId', op: 13, type: 'number'}, {name: 'fontBBox', op: 5, type: ['number', 'number', 'number', 'number'], value: [0, 0, 0, 0]}, {name: 'strokeWidth', op: 1208, type: 'number', value: 0}, {name: 'xuid', op: 14, type: [], value: null}, {name: 'charset', op: 15, type: 'offset', value: 0}, {name: 'encoding', op: 16, type: 'offset', value: 0}, {name: 'charStrings', op: 17, type: 'offset', value: 0}, {name: 'private', op: 18, type: ['number', 'offset'], value: [0, 0]}, {name: 'ros', op: 1230, type: ['SID', 'SID', 'number']}, {name: 'cidFontVersion', op: 1231, type: 'number', value: 0}, {name: 'cidFontRevision', op: 1232, type: 'number', value: 0}, {name: 'cidFontType', op: 1233, type: 'number', value: 0}, {name: 'cidCount', op: 1234, type: 'number', value: 8720}, {name: 'uidBase', op: 1235, type: 'number'}, {name: 'fdArray', op: 1236, type: 'offset'}, {name: 'fdSelect', op: 1237, type: 'offset'}, {name: 'fontName', op: 1238, type: 'SID'} ]; var PRIVATE_DICT_META = [ {name: 'subrs', op: 19, type: 'offset', value: 0}, {name: 'defaultWidthX', op: 20, type: 'number', value: 0}, {name: 'nominalWidthX', op: 21, type: 'number', value: 0} ]; // Parse the CFF top dictionary. A CFF table can contain multiple fonts, each with their own top dictionary. // The top dictionary contains the essential metadata for the font, together with the private dictionary. function parseCFFTopDict(data, strings) { var dict = parseCFFDict(data, 0, data.byteLength); return interpretDict(dict, TOP_DICT_META, strings); } // Parse the CFF private dictionary. We don't fully parse out all the values, only the ones we need. function parseCFFPrivateDict(data, start, size, strings) { var dict = parseCFFDict(data, start, size); return interpretDict(dict, PRIVATE_DICT_META, strings); } // Returns a list of "Top DICT"s found using an INDEX list. // Used to read both the usual high-level Top DICTs and also the FDArray // discovered inside CID-keyed fonts. When a Top DICT has a reference to // a Private DICT that is read and saved into the Top DICT. // // In addition to the expected/optional values as outlined in TOP_DICT_META // the following values might be saved into the Top DICT. // // _subrs [] array of local CFF subroutines from Private DICT // _subrsBias bias value computed from number of subroutines // (see calcCFFSubroutineBias() and parseCFFCharstring()) // _defaultWidthX default widths for CFF characters // _nominalWidthX bias added to width embedded within glyph description // // _privateDict saved copy of parsed Private DICT from Top DICT function gatherCFFTopDicts(data, start, cffIndex, strings) { var topDictArray = []; for (var iTopDict = 0; iTopDict < cffIndex.length; iTopDict += 1) { var topDictData = new DataView(new Uint8Array(cffIndex[iTopDict]).buffer); var topDict = parseCFFTopDict(topDictData, strings); topDict._subrs = []; topDict._subrsBias = 0; var privateSize = topDict.private[0]; var privateOffset = topDict.private[1]; if (privateSize !== 0 && privateOffset !== 0) { var privateDict = parseCFFPrivateDict(data, privateOffset + start, privateSize, strings); topDict._defaultWidthX = privateDict.defaultWidthX; topDict._nominalWidthX = privateDict.nominalWidthX; if (privateDict.subrs !== 0) { var subrOffset = privateOffset + privateDict.subrs; var subrIndex = parseCFFIndex(data, subrOffset + start); topDict._subrs = subrIndex.objects; topDict._subrsBias = calcCFFSubroutineBias(topDict._subrs); } topDict._privateDict = privateDict; } topDictArray.push(topDict); } return topDictArray; } // Parse the CFF charset table, which contains internal names for all the glyphs. // This function will return a list of glyph names. // See Adobe TN #5176 chapter 13, "Charsets". function parseCFFCharset(data, start, nGlyphs, strings) { var i; var sid; var count; var parser = new parse.Parser(data, start); // The .notdef glyph is not included, so subtract 1. nGlyphs -= 1; var charset = ['.notdef']; var format = parser.parseCard8(); if (format === 0) { for (i = 0; i < nGlyphs; i += 1) { sid = parser.parseSID(); charset.push(getCFFString(strings, sid)); } } else if (format === 1) { while (charset.length <= nGlyphs) { sid = parser.parseSID(); count = parser.parseCard8(); for (i = 0; i <= count; i += 1) { charset.push(getCFFString(strings, sid)); sid += 1; } } } else if (format === 2) { while (charset.length <= nGlyphs) { sid = parser.parseSID(); count = parser.parseCard16(); for (i = 0; i <= count; i += 1) { charset.push(getCFFString(strings, sid)); sid += 1; } } } else { throw new Error('Unknown charset format ' + format); } return charset; } // Parse the CFF encoding data. Only one encoding can be specified per font. // See Adobe TN #5176 chapter 12, "Encodings". function parseCFFEncoding(data, start, charset) { var i; var code; var enc = {}; var parser = new parse.Parser(data, start); var format = parser.parseCard8(); if (format === 0) { var nCodes = parser.parseCard8(); for (i = 0; i < nCodes; i += 1) { code = parser.parseCard8(); enc[code] = i; } } else if (format === 1) { var nRanges = parser.parseCard8(); code = 1; for (i = 0; i < nRanges; i += 1) { var first = parser.parseCard8(); var nLeft = parser.parseCard8(); for (var j = first; j <= first + nLeft; j += 1) { enc[j] = code; code += 1; } } } else { throw new Error('Unknown encoding format ' + format); } return new encoding.CffEncoding(enc, charset); } // Take in charstring code and return a Glyph object. // The encoding is described in the Type 2 Charstring Format // https://www.microsoft.com/typography/OTSPEC/charstr2.htm function parseCFFCharstring(font, glyph, code) { var c1x; var c1y; var c2x; var c2y; var p = new path.Path(); var stack = []; var nStems = 0; var haveWidth = false; var open = false; var x = 0; var y = 0; var subrs; var subrsBias; var defaultWidthX; var nominalWidthX; if (font.isCIDFont) { var fdIndex = font.tables.cff.topDict._fdSelect[glyph.index]; var fdDict = font.tables.cff.topDict._fdArray[fdIndex]; subrs = fdDict._subrs; subrsBias = fdDict._subrsBias; defaultWidthX = fdDict._defaultWidthX; nominalWidthX = fdDict._nominalWidthX; } else { subrs = font.tables.cff.topDict._subrs; subrsBias = font.tables.cff.topDict._subrsBias; defaultWidthX = font.tables.cff.topDict._defaultWidthX; nominalWidthX = font.tables.cff.topDict._nominalWidthX; } var width = defaultWidthX; function newContour(x, y) { if (open) { p.closePath(); } p.moveTo(x, y); open = true; } function parseStems() { var hasWidthArg; // The number of stem operators on the stack is always even. // If the value is uneven, that means a width is specified. hasWidthArg = stack.length % 2 !== 0; if (hasWidthArg && !haveWidth) { width = stack.shift() + nominalWidthX; } nStems += stack.length >> 1; stack.length = 0; haveWidth = true; } function parse(code) { var b1; var b2; var b3; var b4; var codeIndex; var subrCode; var jpx; var jpy; var c3x; var c3y; var c4x; var c4y; var i = 0; while (i < code.length) { var v = code[i]; i += 1; switch (v) { case 1: // hstem parseStems(); break; case 3: // vstem parseStems(); break; case 4: // vmoveto if (stack.length > 1 && !haveWidth) { width = stack.shift() + nominalWidthX; haveWidth = true; } y += stack.pop(); newContour(x, y); break; case 5: // rlineto while (stack.length > 0) { x += stack.shift(); y += stack.shift(); p.lineTo(x, y); } break; case 6: // hlineto while (stack.length > 0) { x += stack.shift(); p.lineTo(x, y); if (stack.length === 0) { break; } y += stack.shift(); p.lineTo(x, y); } break; case 7: // vlineto while (stack.length > 0) { y += stack.shift(); p.lineTo(x, y); if (stack.length === 0) { break; } x += stack.shift(); p.lineTo(x, y); } break; case 8: // rrcurveto while (stack.length > 0) { c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + stack.shift(); p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 10: // callsubr codeIndex = stack.pop() + subrsBias; subrCode = subrs[codeIndex]; if (subrCode) { parse(subrCode); } break; case 11: // return return; case 12: // flex operators v = code[i]; i += 1; switch (v) { case 35: // flex // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 dx6 dy6 fd flex (12 35) |- c1x = x + stack.shift(); // dx1 c1y = y + stack.shift(); // dy1 c2x = c1x + stack.shift(); // dx2 c2y = c1y + stack.shift(); // dy2 jpx = c2x + stack.shift(); // dx3 jpy = c2y + stack.shift(); // dy3 c3x = jpx + stack.shift(); // dx4 c3y = jpy + stack.shift(); // dy4 c4x = c3x + stack.shift(); // dx5 c4y = c3y + stack.shift(); // dy5 x = c4x + stack.shift(); // dx6 y = c4y + stack.shift(); // dy6 stack.shift(); // flex depth p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p.curveTo(c3x, c3y, c4x, c4y, x, y); break; case 34: // hflex // |- dx1 dx2 dy2 dx3 dx4 dx5 dx6 hflex (12 34) |- c1x = x + stack.shift(); // dx1 c1y = y; // dy1 c2x = c1x + stack.shift(); // dx2 c2y = c1y + stack.shift(); // dy2 jpx = c2x + stack.shift(); // dx3 jpy = c2y; // dy3 c3x = jpx + stack.shift(); // dx4 c3y = c2y; // dy4 c4x = c3x + stack.shift(); // dx5 c4y = y; // dy5 x = c4x + stack.shift(); // dx6 p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p.curveTo(c3x, c3y, c4x, c4y, x, y); break; case 36: // hflex1 // |- dx1 dy1 dx2 dy2 dx3 dx4 dx5 dy5 dx6 hflex1 (12 36) |- c1x = x + stack.shift(); // dx1 c1y = y + stack.shift(); // dy1 c2x = c1x + stack.shift(); // dx2 c2y = c1y + stack.shift(); // dy2 jpx = c2x + stack.shift(); // dx3 jpy = c2y; // dy3 c3x = jpx + stack.shift(); // dx4 c3y = c2y; // dy4 c4x = c3x + stack.shift(); // dx5 c4y = c3y + stack.shift(); // dy5 x = c4x + stack.shift(); // dx6 p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p.curveTo(c3x, c3y, c4x, c4y, x, y); break; case 37: // flex1 // |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 d6 flex1 (12 37) |- c1x = x + stack.shift(); // dx1 c1y = y + stack.shift(); // dy1 c2x = c1x + stack.shift(); // dx2 c2y = c1y + stack.shift(); // dy2 jpx = c2x + stack.shift(); // dx3 jpy = c2y + stack.shift(); // dy3 c3x = jpx + stack.shift(); // dx4 c3y = jpy + stack.shift(); // dy4 c4x = c3x + stack.shift(); // dx5 c4y = c3y + stack.shift(); // dy5 if (Math.abs(c4x - x) > Math.abs(c4y - y)) { x = c4x + stack.shift(); } else { y = c4y + stack.shift(); } p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy); p.curveTo(c3x, c3y, c4x, c4y, x, y); break; default: console.log('Glyph ' + glyph.index + ': unknown operator ' + 1200 + v); stack.length = 0; } break; case 14: // endchar if (stack.length > 0 && !haveWidth) { width = stack.shift() + nominalWidthX; haveWidth = true; } if (open) { p.closePath(); open = false; } break; case 18: // hstemhm parseStems(); break; case 19: // hintmask case 20: // cntrmask parseStems(); i += (nStems + 7) >> 3; break; case 21: // rmoveto if (stack.length > 2 && !haveWidth) { width = stack.shift() + nominalWidthX; haveWidth = true; } y += stack.pop(); x += stack.pop(); newContour(x, y); break; case 22: // hmoveto if (stack.length > 1 && !haveWidth) { width = stack.shift() + nominalWidthX; haveWidth = true; } x += stack.pop(); newContour(x, y); break; case 23: // vstemhm parseStems(); break; case 24: // rcurveline while (stack.length > 2) { c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + stack.shift(); p.curveTo(c1x, c1y, c2x, c2y, x, y); } x += stack.shift(); y += stack.shift(); p.lineTo(x, y); break; case 25: // rlinecurve while (stack.length > 6) { x += stack.shift(); y += stack.shift(); p.lineTo(x, y); } c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + stack.shift(); p.curveTo(c1x, c1y, c2x, c2y, x, y); break; case 26: // vvcurveto if (stack.length % 2) { x += stack.shift(); } while (stack.length > 0) { c1x = x; c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x; y = c2y + stack.shift(); p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 27: // hhcurveto if (stack.length % 2) { y += stack.shift(); } while (stack.length > 0) { c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y; p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 28: // shortint b1 = code[i]; b2 = code[i + 1]; stack.push(((b1 << 24) | (b2 << 16)) >> 16); i += 2; break; case 29: // callgsubr codeIndex = stack.pop() + font.gsubrsBias; subrCode = font.gsubrs[codeIndex]; if (subrCode) { parse(subrCode); } break; case 30: // vhcurveto while (stack.length > 0) { c1x = x; c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + (stack.length === 1 ? stack.shift() : 0); p.curveTo(c1x, c1y, c2x, c2y, x, y); if (stack.length === 0) { break; } c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); y = c2y + stack.shift(); x = c2x + (stack.length === 1 ? stack.shift() : 0); p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; case 31: // hvcurveto while (stack.length > 0) { c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); y = c2y + stack.shift(); x = c2x + (stack.length === 1 ? stack.shift() : 0); p.curveTo(c1x, c1y, c2x, c2y, x, y); if (stack.length === 0) { break; } c1x = x; c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + (stack.length === 1 ? stack.shift() : 0); p.curveTo(c1x, c1y, c2x, c2y, x, y); } break; default: if (v < 32) { console.log('Glyph ' + glyph.index + ': unknown operator ' + v); } else if (v < 247) { stack.push(v - 139); } else if (v < 251) { b1 = code[i]; i += 1; stack.push((v - 247) * 256 + b1 + 108); } else if (v < 255) { b1 = code[i]; i += 1; stack.push(-(v - 251) * 256 - b1 - 108); } else { b1 = code[i]; b2 = code[i + 1]; b3 = code[i + 2]; b4 = code[i + 3]; i += 4; stack.push(((b1 << 24) | (b2 << 16) | (b3 << 8) | b4) / 65536); } } } } parse(code); glyph.advanceWidth = width; return p; } function parseCFFFDSelect(data, start, nGlyphs, fdArrayCount) { var fdSelect = []; var fdIndex; var parser = new parse.Parser(data, start); var format = parser.parseCard8(); if (format === 0) { // Simple list of nGlyphs elements for (var iGid = 0; iGid < nGlyphs; iGid++) { fdIndex = parser.parseCard8(); if (fdIndex >= fdArrayCount) { throw new Error('CFF table CID Font FDSelect has bad FD index value ' + fdIndex + ' (FD count ' + fdArrayCount + ')'); } fdSelect.push(fdIndex); } } else if (format === 3) { // Ranges var nRanges = parser.parseCard16(); var first = parser.parseCard16(); if (first !== 0) { throw new Error('CFF Table CID Font FDSelect format 3 range has bad initial GID ' + first); } var next; for (var iRange = 0; iRange < nRanges; iRange++) { fdIndex = parser.parseCard8(); next = parser.parseCard16(); if (fdIndex >= fdArrayCount) { throw new Error('CFF table CID Font FDSelect has bad FD index value ' + fdIndex + ' (FD count ' + fdArrayCount + ')'); } if (next > nGlyphs) { throw new Error('CFF Table CID Font FDSelect format 3 range has bad GID ' + next); } for (; first < next; first++) { fdSelect.push(fdIndex); } first = next; } if (next !== nGlyphs) { throw new Error('CFF Table CID Font FDSelect format 3 range has bad final GID ' + next); } } else { throw new Error('CFF Table CID Font FDSelect table has unsupported format ' + format); } return fdSelect; } // Parse the `CFF` table, which contains the glyph outlines in PostScript format. function parseCFFTable(data, start, font) { font.tables.cff = {}; var header = parseCFFHeader(data, start); var nameIndex = parseCFFIndex(data, header.endOffset, parse.bytesToString); var topDictIndex = parseCFFIndex(data, nameIndex.endOffset); var stringIndex = parseCFFIndex(data, topDictIndex.endOffset, parse.bytesToString); var globalSubrIndex = parseCFFIndex(data, stringIndex.endOffset); font.gsubrs = globalSubrIndex.objects; font.gsubrsBias = calcCFFSubroutineBias(font.gsubrs); var topDictArray = gatherCFFTopDicts(data, start, topDictIndex.objects, stringIndex.objects); if (topDictArray.length !== 1) { throw new Error('CFF table has too many fonts in \'FontSet\' - ' + 'count of fonts NameIndex.length = ' + topDictArray.length); } var topDict = topDictArray[0]; font.tables.cff.topDict = topDict; if (topDict._privateDict) { font.defaultWidthX = topDict._privateDict.defaultWidthX; font.nominalWidthX = topDict._privateDict.nominalWidthX; } if (topDict.ros[0] !== undefined && topDict.ros[1] !== undefined) { font.isCIDFont = true; } if (font.isCIDFont) { var fdArrayOffset = topDict.fdArray; var fdSelectOffset = topDict.fdSelect; if (fdArrayOffset === 0 || fdSelectOffset === 0) { throw new Error('Font is marked as a CID font, but FDArray and/or FDSelect information is missing'); } fdArrayOffset += start; var fdArrayIndex = parseCFFIndex(data, fdArrayOffset); var fdArray = gatherCFFTopDicts(data, start, fdArrayIndex.objects, stringIndex.objects); topDict._fdArray = fdArray; fdSelectOffset += start; topDict._fdSelect = parseCFFFDSelect(data, fdSelectOffset, font.numGlyphs, fdArray.length); } var privateDictOffset = start + topDict['private'][1]; var privateDict = parseCFFPrivateDict(data, privateDictOffset, topDict['private'][0], stringIndex.objects); font.defaultWidthX = privateDict.defaultWidthX; font.nominalWidthX = privateDict.nominalWidthX; if (privateDict.subrs !== 0) { var subrOffset = privateDictOffset + privateDict.subrs; var subrIndex = parseCFFIndex(data, subrOffset); font.subrs = subrIndex.objects; font.subrsBias = calcCFFSubroutineBias(font.subrs); } else { font.subrs = []; font.subrsBias = 0; } // Offsets in the top dict are relative to the beginning of the CFF data, so add the CFF start offset. var charStringsIndex = parseCFFIndex(data, start + topDict.charStrings); font.nGlyphs = charStringsIndex.objects.length; var charset = parseCFFCharset(data, start + topDict.charset, font.nGlyphs, stringIndex.objects); if (topDict.encoding === 0) { // Standard encoding font.cffEncoding = new encoding.CffEncoding(encoding.cffStandardEncoding, charset); } else if (topDict.encoding === 1) { // Expert encoding font.cffEncoding = new encoding.CffEncoding(encoding.cffExpertEncoding, charset); } else { font.cffEncoding = parseCFFEncoding(data, start + topDict.encoding, charset); } // Prefer the CMAP encoding to the CFF encoding. font.encoding = font.encoding || font.cffEncoding; font.glyphs = new glyphset.GlyphSet(font); for (var i = 0; i < font.nGlyphs; i += 1) { var charString = charStringsIndex.objects[i]; font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString)); } } // Convert a string to a String ID (SID). // The list of strings is modified in place. function encodeString(s, strings) { var sid; // Is the string in the CFF standard strings? var i = encoding.cffStandardStrings.indexOf(s); if (i >= 0) { sid = i; } // Is the string already in the string index? i = strings.indexOf(s); if (i >= 0) { sid = i + encoding.cffStandardStrings.length; } else { sid = encoding.cffStandardStrings.length + strings.length; strings.push(s); } return sid; } function makeHeader() { return new table.Record('Header', [ {name: 'major', type: 'Card8', value: 1}, {name: 'minor', type: 'Card8', value: 0}, {name: 'hdrSize', type: 'Card8', value: 4}, {name: 'major', type: 'Card8', value: 1} ]); } function makeNameIndex(fontNames) { var t = new table.Record('Name INDEX', [ {name: 'names', type: 'INDEX', value: []} ]); t.names = []; for (var i = 0; i < fontNames.length; i += 1) { t.names.push({name: 'name_' + i, type: 'NAME', value: fontNames[i]}); } return t; } // Given a dictionary's metadata, create a DICT structure. function makeDict(meta, attrs, strings) { var m = {}; for (var i = 0; i < meta.length; i += 1) { var entry = meta[i]; var value = attrs[entry.name]; if (value !== undefined && !equals(value, entry.value)) { if (entry.type === 'SID') { value = encodeString(value, strings); } m[entry.op] = {name: entry.name, type: entry.type, value: value}; } } return m; } // The Top DICT houses the global font attributes. function makeTopDict(attrs, strings) { var t = new table.Record('Top DICT', [ {name: 'dict', type: 'DICT', value: {}} ]); t.dict = makeDict(TOP_DICT_META, attrs, strings); return t; } function makeTopDictIndex(topDict) { var t = new table.Record('Top DICT INDEX', [ {name: 'topDicts', type: 'INDEX', value: []} ]); t.topDicts = [{name: 'topDict_0', type: 'TABLE', value: topDict}]; return t; } function makeStringIndex(strings) { var t = new table.Record('String INDEX', [ {name: 'strings', type: 'INDEX', value: []} ]); t.strings = []; for (var i = 0; i < strings.length; i += 1) { t.strings.push({name: 'string_' + i, type: 'STRING', value: strings[i]}); } return t; } function makeGlobalSubrIndex() { // Currently we don't use subroutines. return new table.Record('Global Subr INDEX', [ {name: 'subrs', type: 'INDEX', value: []} ]); } function makeCharsets(glyphNames, strings) { var t = new table.Record('Charsets', [ {name: 'format', type: 'Card8', value: 0} ]); for (var i = 0; i < glyphNames.length; i += 1) { var glyphName = glyphNames[i]; var glyphSID = encodeString(glyphName, strings); t.fields.push({name: 'glyph_' + i, type: 'SID', value: glyphSID}); } return t; } function glyphToOps(glyph) { var ops = []; var path = glyph.path; ops.push({name: 'width', type: 'NUMBER', value: glyph.advanceWidth}); var x = 0; var y = 0; for (var i = 0; i < path.commands.length; i += 1) { var dx; var dy; var cmd = path.commands[i]; if (cmd.type === 'Q') { // CFF only supports bézier curves, so convert the quad to a bézier. var _13 = 1 / 3; var _23 = 2 / 3; // We're going to create a new command so we don't change the original path. cmd = { type: 'C', x: cmd.x, y: cmd.y, x1: _13 * x + _23 * cmd.x1, y1: _13 * y + _23 * cmd.y1, x2: _13 * cmd.x + _23 * cmd.x1, y2: _13 * cmd.y + _23 * cmd.y1 }; } if (cmd.type === 'M') { dx = Math.round(cmd.x - x); dy = Math.round(cmd.y - y); ops.push({name: 'dx', type: 'NUMBER', value: dx}); ops.push({name: 'dy', type: 'NUMBER', value: dy}); ops.push({name: 'rmoveto', type: 'OP', value: 21}); x = Math.round(cmd.x); y = Math.round(cmd.y); } else if (cmd.type === 'L') { dx = Math.round(cmd.x - x); dy = Math.round(cmd.y - y); ops.push({name: 'dx', type: 'NUMBER', value: dx}); ops.push({name: 'dy', type: 'NUMBER', value: dy}); ops.push({name: 'rlineto', type: 'OP', value: 5}); x = Math.round(cmd.x); y = Math.round(cmd.y); } else if (cmd.type === 'C') { var dx1 = Math.round(cmd.x1 - x); var dy1 = Math.round(cmd.y1 - y); var dx2 = Math.round(cmd.x2 - cmd.x1); var dy2 = Math.round(cmd.y2 - cmd.y1); dx = Math.round(cmd.x - cmd.x2); dy = Math.round(cmd.y - cmd.y2); ops.push({name: 'dx1', type: 'NUMBER', value: dx1}); ops.push({name: 'dy1', type: 'NUMBER', value: dy1}); ops.push({name: 'dx2', type: 'NUMBER', value: dx2}); ops.push({name: 'dy2', type: 'NUMBER', value: dy2}); ops.push({name: 'dx', type: 'NUMBER', value: dx}); ops.push({name: 'dy', type: 'NUMBER', value: dy}); ops.push({name: 'rrcurveto', type: 'OP', value: 8}); x = Math.round(cmd.x); y = Math.round(cmd.y); } // Contours are closed automatically. } ops.push({name: 'endchar', type: 'OP', value: 14}); return ops; } function makeCharStringsIndex(glyphs) { var t = new table.Record('CharStrings INDEX', [ {name: 'charStrings', type: 'INDEX', value: []} ]); for (var i = 0; i < glyphs.length; i += 1) { var glyph = glyphs.get(i); var ops = glyphToOps(glyph); t.charStrings.push({name: glyph.name, type: 'CHARSTRING', value: ops}); } return t; } function makePrivateDict(attrs, strings) { var t = new table.Record('Private DICT', [ {name: 'dict', type: 'DICT', value: {}} ]); t.dict = makeDict(PRIVATE_DICT_META, attrs, strings); return t; } function makeCFFTable(glyphs, options) { var t = new table.Table('CFF ', [ {name: 'header', type: 'RECORD'}, {name: 'nameIndex', type: 'RECORD'}, {name: 'topDictIndex', type: 'RECORD'}, {name: 'stringIndex', type: 'RECORD'}, {name: 'globalSubrIndex', type: 'RECORD'}, {name: 'charsets', type: 'RECORD'}, {name: 'charStringsIndex', type: 'RECORD'}, {name: 'privateDict', type: 'RECORD'} ]); var fontScale = 1 / options.unitsPerEm; // We use non-zero values for the offsets so that the DICT encodes them. // This is important because the size of the Top DICT plays a role in offset calculation, // and the size shouldn't change after we've written correct offsets. var attrs = { version: options.version, fullName: options.fullName, familyName: options.familyName, weight: options.weightName, fontBBox: options.fontBBox || [0, 0, 0, 0], fontMatrix: [fontScale, 0, 0, fontScale, 0, 0], charset: 999, encoding: 0, charStrings: 999, private: [0, 999] }; var privateAttrs = {}; var glyphNames = []; var glyph; // Skip first glyph (.notdef) for (var i = 1; i < glyphs.length; i += 1) { glyph = glyphs.get(i); glyphNames.push(glyph.name); } var strings = []; t.header = makeHeader(); t.nameIndex = makeNameIndex([options.postScriptName]); var topDict = makeTopDict(attrs, strings); t.topDictIndex = makeTopDictIndex(topDict); t.globalSubrIndex = makeGlobalSubrIndex(); t.charsets = makeCharsets(glyphNames, strings); t.charStringsIndex = makeCharStringsIndex(glyphs); t.privateDict = makePrivateDict(privateAttrs, strings); // Needs to come at the end, to encode all custom strings used in the font. t.stringIndex = makeStringIndex(strings); var startOffset = t.header.sizeOf() + t.nameIndex.sizeOf() + t.topDictIndex.sizeOf() + t.stringIndex.sizeOf() + t.globalSubrIndex.sizeOf(); attrs.charset = startOffset; // We use the CFF standard encoding; proper encoding will be handled in cmap. attrs.encoding = 0; attrs.charStrings = attrs.charset + t.charsets.sizeOf(); attrs.private[1] = attrs.charStrings + t.charStringsIndex.sizeOf(); // Recreate the Top DICT INDEX with the correct offsets. topDict = makeTopDict(attrs, strings); t.topDictIndex = makeTopDictIndex(topDict); return t; } exports.parse = parseCFFTable; exports.make = makeCFFTable; },{"../encoding":9,"../glyphset":12,"../parse":16,"../path":17,"../table":19}],21:[function(_dereq_,module,exports){ // The `cmap` table stores the mappings from characters to glyphs. // https://www.microsoft.com/typography/OTSPEC/cmap.htm 'use strict'; var check = _dereq_('../check'); var parse = _dereq_('../parse'); var table = _dereq_('../table'); function parseCmapTableFormat12(cmap, p) { var i; //Skip reserved. p.parseUShort(); // Length in bytes of the sub-tables. cmap.length = p.parseULong(); cmap.language = p.parseULong(); var groupCount; cmap.groupCount = groupCount = p.parseULong(); cmap.glyphIndexMap = {}; for (i = 0; i < groupCount; i += 1) { var startCharCode = p.parseULong(); var endCharCode = p.parseULong(); var startGlyphId = p.parseULong(); for (var c = startCharCode; c <= endCharCode; c += 1) { cmap.glyphIndexMap[c] = startGlyphId; startGlyphId++; } } } function parseCmapTableFormat4(cmap, p, data, start, offset) { var i; // Length in bytes of the sub-tables. cmap.length = p.parseUShort(); cmap.language = p.parseUShort(); // segCount is stored x 2. var segCount; cmap.segCount = segCount = p.parseUShort() >> 1; // Skip searchRange, entrySelector, rangeShift. p.skip('uShort', 3); // The "unrolled" mapping from character codes to glyph indices. cmap.glyphIndexMap = {}; var endCountParser = new parse.Parser(data, start + offset + 14); var startCountParser = new parse.Parser(data, start + offset + 16 + segCount * 2); var idDeltaParser = new parse.Parser(data, start + offset + 16 + segCount * 4); var idRangeOffsetParser = new parse.Parser(data, start + offset + 16 + segCount * 6); var glyphIndexOffset = start + offset + 16 + segCount * 8; for (i = 0; i < segCount - 1; i += 1) { var glyphIndex; var endCount = endCountParser.parseUShort(); var startCount = startCountParser.parseUShort(); var idDelta = idDeltaParser.parseShort(); var idRangeOffset = idRangeOffsetParser.parseUShort(); for (var c = startCount; c <= endCount; c += 1) { if (idRangeOffset !== 0) { // The idRangeOffset is relative to the current position in the idRangeOffset array. // Take the current offset in the idRangeOffset array. glyphIndexOffset = (idRangeOffsetParser.offset + idRangeOffsetParser.relativeOffset - 2); // Add the value of the idRangeOffset, which will move us into the glyphIndex array. glyphIndexOffset += idRangeOffset; // Then add the character index of the current segment, multiplied by 2 for USHORTs. glyphIndexOffset += (c - startCount) * 2; glyphIndex = parse.getUShort(data, glyphIndexOffset); if (glyphIndex !== 0) { glyphIndex = (glyphIndex + idDelta) & 0xFFFF; } } else { glyphIndex = (c + idDelta) & 0xFFFF; } cmap.glyphIndexMap[c] = glyphIndex; } } } // Parse the `cmap` table. This table stores the mappings from characters to glyphs. // There are many available formats, but we only support the Windows format 4 and 12. // This function returns a `CmapEncoding` object or null if no supported format could be found. function parseCmapTable(data, start) { var i; var cmap = {}; cmap.version = parse.getUShort(data, start); check.argument(cmap.version === 0, 'cmap table version should be 0.'); // The cmap table can contain many sub-tables, each with their own format. // We're only interested in a "platform 3" table. This is a Windows format. cmap.numTables = parse.getUShort(data, start + 2); var offset = -1; for (i = cmap.numTables - 1; i >= 0; i -= 1) { var platformId = parse.getUShort(data, start + 4 + (i * 8)); var encodingId = parse.getUShort(data, start + 4 + (i * 8) + 2); if (platformId === 3 && (encodingId === 0 || encodingId === 1 || encodingId === 10)) { offset = parse.getULong(data, start + 4 + (i * 8) + 4); break; } } if (offset === -1) { // There is no cmap table in the font that we support. throw new Error('No valid cmap sub-tables found.'); } var p = new parse.Parser(data, start + offset); cmap.format = p.parseUShort(); if (cmap.format === 12) { parseCmapTableFormat12(cmap, p); } else if (cmap.format === 4) { parseCmapTableFormat4(cmap, p, data, start, offset); } else { throw new Error('Only format 4 and 12 cmap tables are supported (found format ' + cmap.format + ').'); } return cmap; } function addSegment(t, code, glyphIndex) { t.segments.push({ end: code, start: code, delta: -(code - glyphIndex), offset: 0 }); } function addTerminatorSegment(t) { t.segments.push({ end: 0xFFFF, start: 0xFFFF, delta: 1, offset: 0 }); } function makeCmapTable(glyphs) { var i; var t = new table.Table('cmap', [ {name: 'version', type: 'USHORT', value: 0}, {name: 'numTables', type: 'USHORT', value: 1}, {name: 'platformID', type: 'USHORT', value: 3}, {name: 'encodingID', type: 'USHORT', value: 1}, {name: 'offset', type: 'ULONG', value: 12}, {name: 'format', type: 'USHORT', value: 4}, {name: 'length', type: 'USHORT', value: 0}, {name: 'language', type: 'USHORT', value: 0}, {name: 'segCountX2', type: 'USHORT', value: 0}, {name: 'searchRange', type: 'USHORT', value: 0}, {name: 'entrySelector', type: 'USHORT', value: 0}, {name: 'rangeShift', type: 'USHORT', value: 0} ]); t.segments = []; for (i = 0; i < glyphs.length; i += 1) { var glyph = glyphs.get(i); for (var j = 0; j < glyph.unicodes.length; j += 1) { addSegment(t, glyph.unicodes[j], i); } t.segments = t.segments.sort(function(a, b) { return a.start - b.start; }); } addTerminatorSegment(t); var segCount; segCount = t.segments.length; t.segCountX2 = segCount * 2; t.searchRange = Math.pow(2, Math.floor(Math.log(segCount) / Math.log(2))) * 2; t.entrySelector = Math.log(t.searchRange / 2) / Math.log(2); t.rangeShift = t.segCountX2 - t.searchRange; // Set up parallel segment arrays. var endCounts = []; var startCounts = []; var idDeltas = []; var idRangeOffsets = []; var glyphIds = []; for (i = 0; i < segCount; i += 1) { var segment = t.segments[i]; endCounts = endCounts.concat({name: 'end_' + i, type: 'USHORT', value: segment.end}); startCounts = startCounts.concat({name: 'start_' + i, type: 'USHORT', value: segment.start}); idDeltas = idDeltas.concat({name: 'idDelta_' + i, type: 'SHORT', value: segment.delta}); idRangeOffsets = idRangeOffsets.concat({name: 'idRangeOffset_' + i, type: 'USHORT', value: segment.offset}); if (segment.glyphId !== undefined) { glyphIds = glyphIds.concat({name: 'glyph_' + i, type: 'USHORT', value: segment.glyphId}); } } t.fields = t.fields.concat(endCounts); t.fields.push({name: 'reservedPad', type: 'USHORT', value: 0}); t.fields = t.fields.concat(startCounts); t.fields = t.fields.concat(idDeltas); t.fields = t.fields.concat(idRangeOffsets); t.fields = t.fields.concat(glyphIds); t.length = 14 + // Subtable header endCounts.length * 2 + 2 + // reservedPad startCounts.length * 2 + idDeltas.length * 2 + idRangeOffsets.length * 2 + glyphIds.length * 2; return t; } exports.parse = parseCmapTable; exports.make = makeCmapTable; },{"../check":7,"../parse":16,"../table":19}],22:[function(_dereq_,module,exports){ // The `fvar` table stores font variation axes and instances. // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6fvar.html 'use strict'; var check = _dereq_('../check'); var parse = _dereq_('../parse'); var table = _dereq_('../table'); function addName(name, names) { var nameString = JSON.stringify(name); var nameID = 256; for (var nameKey in names) { var n = parseInt(nameKey); if (!n || n < 256) { continue; } if (JSON.stringify(names[nameKey]) === nameString) { return n; } if (nameID <= n) { nameID = n + 1; } } names[nameID] = name; return nameID; } function makeFvarAxis(n, axis, names) { var nameID = addName(axis.name, names); return [ {name: 'tag_' + n, type: 'TAG', value: axis.tag}, {name: 'minValue_' + n, type: 'FIXED', value: axis.minValue << 16}, {name: 'defaultValue_' + n, type: 'FIXED', value: axis.defaultValue << 16}, {name: 'maxValue_' + n, type: 'FIXED', value: axis.maxValue << 16}, {name: 'flags_' + n, type: 'USHORT', value: 0}, {name: 'nameID_' + n, type: 'USHORT', value: nameID} ]; } function parseFvarAxis(data, start, names) { var axis = {}; var p = new parse.Parser(data, start); axis.tag = p.parseTag(); axis.minValue = p.parseFixed(); axis.defaultValue = p.parseFixed(); axis.maxValue = p.parseFixed(); p.skip('uShort', 1); // reserved for flags; no values defined axis.name = names[p.parseUShort()] || {}; return axis; } function makeFvarInstance(n, inst, axes, names) { var nameID = addName(inst.name, names); var fields = [ {name: 'nameID_' + n, type: 'USHORT', value: nameID}, {name: 'flags_' + n, type: 'USHORT', value: 0} ]; for (var i = 0; i < axes.length; ++i) { var axisTag = axes[i].tag; fields.push({ name: 'axis_' + n + ' ' + axisTag, type: 'FIXED', value: inst.coordinates[axisTag] << 16 }); } return fields; } function parseFvarInstance(data, start, axes, names) { var inst = {}; var p = new parse.Parser(data, start); inst.name = names[p.parseUShort()] || {}; p.skip('uShort', 1); // reserved for flags; no values defined inst.coordinates = {}; for (var i = 0; i < axes.length; ++i) { inst.coordinates[axes[i].tag] = p.parseFixed(); } return inst; } function makeFvarTable(fvar, names) { var result = new table.Table('fvar', [ {name: 'version', type: 'ULONG', value: 0x10000}, {name: 'offsetToData', type: 'USHORT', value: 0}, {name: 'countSizePairs', type: 'USHORT', value: 2}, {name: 'axisCount', type: 'USHORT', value: fvar.axes.length}, {name: 'axisSize', type: 'USHORT', value: 20}, {name: 'instanceCount', type: 'USHORT', value: fvar.instances.length}, {name: 'instanceSize', type: 'USHORT', value: 4 + fvar.axes.length * 4} ]); result.offsetToData = result.sizeOf(); for (var i = 0; i < fvar.axes.length; i++) { result.fields = result.fields.concat(makeFvarAxis(i, fvar.axes[i], names)); } for (var j = 0; j < fvar.instances.length; j++) { result.fields = result.fields.concat(makeFvarInstance(j, fvar.instances[j], fvar.axes, names)); } return result; } function parseFvarTable(data, start, names) { var p = new parse.Parser(data, start); var tableVersion = p.parseULong(); check.argument(tableVersion === 0x00010000, 'Unsupported fvar table version.'); var offsetToData = p.parseOffset16(); // Skip countSizePairs. p.skip('uShort', 1); var axisCount = p.parseUShort(); var axisSize = p.parseUShort(); var instanceCount = p.parseUShort(); var instanceSize = p.parseUShort(); var axes = []; for (var i = 0; i < axisCount; i++) { axes.push(parseFvarAxis(data, start + offsetToData + i * axisSize, names)); } var instances = []; var instanceStart = start + offsetToData + axisCount * axisSize; for (var j = 0; j < instanceCount; j++) { instances.push(parseFvarInstance(data, instanceStart + j * instanceSize, axes, names)); } return {axes: axes, instances: instances}; } exports.make = makeFvarTable; exports.parse = parseFvarTable; },{"../check":7,"../parse":16,"../table":19}],23:[function(_dereq_,module,exports){ // The `glyf` table describes the glyphs in TrueType outline format. // http://www.microsoft.com/typography/otspec/glyf.htm 'use strict'; var check = _dereq_('../check'); var glyphset = _dereq_('../glyphset'); var parse = _dereq_('../parse'); var path = _dereq_('../path'); // Parse the coordinate data for a glyph. function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) { var v; if ((flag & shortVectorBitMask) > 0) { // The coordinate is 1 byte long. v = p.parseByte(); // The `same` bit is re-used for short values to signify the sign of the value. if ((flag & sameBitMask) === 0) { v = -v; } v = previousValue + v; } else { // The coordinate is 2 bytes long. // If the `same` bit is set, the coordinate is the same as the previous coordinate. if ((flag & sameBitMask) > 0) { v = previousValue; } else { // Parse the coordinate as a signed 16-bit delta value. v = previousValue + p.parseShort(); } } return v; } // Parse a TrueType glyph. function parseGlyph(glyph, data, start) { var p = new parse.Parser(data, start); glyph.numberOfContours = p.parseShort(); glyph._xMin = p.parseShort(); glyph._yMin = p.parseShort(); glyph._xMax = p.parseShort(); glyph._yMax = p.parseShort(); var flags; var flag; var i; if (glyph.numberOfContours > 0) { // This glyph is not a composite. var endPointIndices = glyph.endPointIndices = []; for (i = 0; i < glyph.numberOfContours; i += 1) { endPointIndices.push(p.parseUShort()); } glyph.instructionLength = p.parseUShort(); glyph.instructions = []; for (i = 0; i < glyph.instructionLength; i += 1) { glyph.instructions.push(p.parseByte()); } var numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1; flags = []; for (i = 0; i < numberOfCoordinates; i += 1) { flag = p.parseByte(); flags.push(flag); // If bit 3 is set, we repeat this flag n times, where n is the next byte. if ((flag & 8) > 0) { var repeatCount = p.parseByte(); for (var j = 0; j < repeatCount; j += 1) { flags.push(flag); i += 1; } } } check.argument(flags.length === numberOfCoordinates, 'Bad flags.'); if (endPointIndices.length > 0) { var points = []; var point; // X/Y coordinates are relative to the previous point, except for the first point which is relative to 0,0. if (numberOfCoordinates > 0) { for (i = 0; i < numberOfCoordinates; i += 1) { flag = flags[i]; point = {}; point.onCurve = !!(flag & 1); point.lastPointOfContour = endPointIndices.indexOf(i) >= 0; points.push(point); } var px = 0; for (i = 0; i < numberOfCoordinates; i += 1) { flag = flags[i]; point = points[i]; point.x = parseGlyphCoordinate(p, flag, px, 2, 16); px = point.x; } var py = 0; for (i = 0; i < numberOfCoordinates; i += 1) { flag = flags[i]; point = points[i]; point.y = parseGlyphCoordinate(p, flag, py, 4, 32); py = point.y; } } glyph.points = points; } else { glyph.points = []; } } else if (glyph.numberOfContours === 0) { glyph.points = []; } else { glyph.isComposite = true; glyph.points = []; glyph.components = []; var moreComponents = true; while (moreComponents) { flags = p.parseUShort(); var component = { glyphIndex: p.parseUShort(), xScale: 1, scale01: 0, scale10: 0, yScale: 1, dx: 0, dy: 0 }; if ((flags & 1) > 0) { // The arguments are words if ((flags & 2) > 0) { // values are offset component.dx = p.parseShort(); component.dy = p.parseShort(); } else { // values are matched points component.matchedPoints = [p.parseUShort(), p.parseUShort()]; } } else { // The arguments are bytes if ((flags & 2) > 0) { // values are offset component.dx = p.parseChar(); component.dy = p.parseChar(); } else { // values are matched points component.matchedPoints = [p.parseByte(), p.parseByte()]; } } if ((flags & 8) > 0) { // We have a scale component.xScale = component.yScale = p.parseF2Dot14(); } else if ((flags & 64) > 0) { // We have an X / Y scale component.xScale = p.parseF2Dot14(); component.yScale = p.parseF2Dot14(); } else if ((flags & 128) > 0) { // We have a 2x2 transformation component.xScale = p.parseF2Dot14(); component.scale01 = p.parseF2Dot14(); component.scale10 = p.parseF2Dot14(); component.yScale = p.parseF2Dot14(); } glyph.components.push(component); moreComponents = !!(flags & 32); } if (flags & 0x100) { // We have instructions glyph.instructionLength = p.parseUShort(); glyph.instructions = []; for (i = 0; i < glyph.instructionLength; i += 1) { glyph.instructions.push(p.parseByte()); } } } } // Transform an array of points and return a new array. function transformPoints(points, transform) { var newPoints = []; for (var i = 0; i < points.length; i += 1) { var pt = points[i]; var newPt = { x: transform.xScale * pt.x + transform.scale01 * pt.y + transform.dx, y: transform.scale10 * pt.x + transform.yScale * pt.y + transform.dy, onCurve: pt.onCurve, lastPointOfContour: pt.lastPointOfContour }; newPoints.push(newPt); } return newPoints; } function getContours(points) { var contours = []; var currentContour = []; for (var i = 0; i < points.length; i += 1) { var pt = points[i]; currentContour.push(pt); if (pt.lastPointOfContour) { contours.push(currentContour); currentContour = []; } } check.argument(currentContour.length === 0, 'There are still points left in the current contour.'); return contours; } // Convert the TrueType glyph outline to a Path. function getPath(points) { var p = new path.Path(); if (!points) { return p; } var contours = getContours(points); for (var contourIndex = 0; contourIndex < contours.length; ++contourIndex) { var contour = contours[contourIndex]; var prev = null; var curr = contour[contour.length - 1]; var next = contour[0]; if (curr.onCurve) { p.moveTo(curr.x, curr.y); } else { if (next.onCurve) { p.moveTo(next.x, next.y); } else { // If both first and last points are off-curve, start at their middle. var start = { x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5 }; p.moveTo(start.x, start.y); } } for (var i = 0; i < contour.length; ++i) { prev = curr; curr = next; next = contour[(i + 1) % contour.length]; if (curr.onCurve) { // This is a straight line. p.lineTo(curr.x, curr.y); } else { var prev2 = prev; var next2 = next; if (!prev.onCurve) { prev2 = { x: (curr.x + prev.x) * 0.5, y: (curr.y + prev.y) * 0.5 }; p.lineTo(prev2.x, prev2.y); } if (!next.onCurve) { next2 = { x: (curr.x + next.x) * 0.5, y: (curr.y + next.y) * 0.5 }; } p.lineTo(prev2.x, prev2.y); p.quadraticCurveTo(curr.x, curr.y, next2.x, next2.y); } } } p.closePath(); return p; } function buildPath(glyphs, glyph) { if (glyph.isComposite) { for (var j = 0; j < glyph.components.length; j += 1) { var component = glyph.components[j]; var componentGlyph = glyphs.get(component.glyphIndex); // Force the ttfGlyphLoader to parse the glyph. componentGlyph.getPath(); if (componentGlyph.points) { var transformedPoints; if (component.matchedPoints === undefined) { // component positioned by offset transformedPoints = transformPoints(componentGlyph.points, component); } else { // component positioned by matched points if ((component.matchedPoints[0] > glyph.points.length - 1) || (component.matchedPoints[1] > componentGlyph.points.length - 1)) { throw Error('Matched points out of range in ' + glyph.name); } var firstPt = glyph.points[component.matchedPoints[0]]; var secondPt = componentGlyph.points[component.matchedPoints[1]]; var transform = { xScale: component.xScale, scale01: component.scale01, scale10: component.scale10, yScale: component.yScale, dx: 0, dy: 0 }; secondPt = transformPoints([secondPt], transform)[0]; transform.dx = firstPt.x - secondPt.x; transform.dy = firstPt.y - secondPt.y; transformedPoints = transformPoints(componentGlyph.points, transform); } glyph.points = glyph.points.concat(transformedPoints); } } } return getPath(glyph.points); } // Parse all the glyphs according to the offsets from the `loca` table. function parseGlyfTable(data, start, loca, font) { var glyphs = new glyphset.GlyphSet(font); var i; // The last element of the loca table is invalid. for (i = 0; i < loca.length - 1; i += 1) { var offset = loca[i]; var nextOffset = loca[i + 1]; if (offset !== nextOffset) { glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data, start + offset, buildPath)); } else { glyphs.push(i, glyphset.glyphLoader(font, i)); } } return glyphs; } exports.getPath = getPath; exports.parse = parseGlyfTable; },{"../check":7,"../glyphset":12,"../parse":16,"../path":17}],24:[function(_dereq_,module,exports){ // The `GPOS` table contains kerning pairs, among other things. // https://www.microsoft.com/typography/OTSPEC/gpos.htm 'use strict'; var check = _dereq_('../check'); var parse = _dereq_('../parse'); // Parse ScriptList and FeatureList tables of GPOS, GSUB, GDEF, BASE, JSTF tables. // These lists are unused by now, this function is just the basis for a real parsing. function parseTaggedListTable(data, start) { var p = new parse.Parser(data, start); var n = p.parseUShort(); var list = []; for (var i = 0; i < n; i++) { list[p.parseTag()] = { offset: p.parseUShort() }; } return list; } // Parse a coverage table in a GSUB, GPOS or GDEF table. // Format 1 is a simple list of glyph ids, // Format 2 is a list of ranges. It is expanded in a list of glyphs, maybe not the best idea. function parseCoverageTable(data, start) { var p = new parse.Parser(data, start); var format = p.parseUShort(); var count = p.parseUShort(); if (format === 1) { return p.parseUShortList(count); } else if (format === 2) { var coverage = []; for (; count--;) { var begin = p.parseUShort(); var end = p.parseUShort(); var index = p.parseUShort(); for (var i = begin; i <= end; i++) { coverage[index++] = i; } } return coverage; } } // Parse a Class Definition Table in a GSUB, GPOS or GDEF table. // Returns a function that gets a class value from a glyph ID. function parseClassDefTable(data, start) { var p = new parse.Parser(data, start); var format = p.parseUShort(); if (format === 1) { // Format 1 specifies a range of consecutive glyph indices, one class per glyph ID. var startGlyph = p.parseUShort(); var glyphCount = p.parseUShort(); var classes = p.parseUShortList(glyphCount); return function(glyphID) { return classes[glyphID - startGlyph] || 0; }; } else if (format === 2) { // Format 2 defines multiple groups of glyph indices that belong to the same class. var rangeCount = p.parseUShort(); var startGlyphs = []; var endGlyphs = []; var classValues = []; for (var i = 0; i < rangeCount; i++) { startGlyphs[i] = p.parseUShort(); endGlyphs[i] = p.parseUShort(); classValues[i] = p.parseUShort(); } return function(glyphID) { var l = 0; var r = startGlyphs.length - 1; while (l < r) { var c = (l + r + 1) >> 1; if (glyphID < startGlyphs[c]) { r = c - 1; } else { l = c; } } if (startGlyphs[l] <= glyphID && glyphID <= endGlyphs[l]) { return classValues[l] || 0; } return 0; }; } } // Parse a pair adjustment positioning subtable, format 1 or format 2 // The subtable is returned in the form of a lookup function. function parsePairPosSubTable(data, start) { var p = new parse.Parser(data, start); // This part is common to format 1 and format 2 subtables var format = p.parseUShort(); var coverageOffset = p.parseUShort(); var coverage = parseCoverageTable(data, start + coverageOffset); // valueFormat 4: XAdvance only, 1: XPlacement only, 0: no ValueRecord for second glyph // Only valueFormat1=4 and valueFormat2=0 is supported. var valueFormat1 = p.parseUShort(); var valueFormat2 = p.parseUShort(); var value1; var value2; if (valueFormat1 !== 4 || valueFormat2 !== 0) return; var sharedPairSets = {}; if (format === 1) { // Pair Positioning Adjustment: Format 1 var pairSetCount = p.parseUShort(); var pairSet = []; // Array of offsets to PairSet tables-from beginning of PairPos subtable-ordered by Coverage Index var pairSetOffsets = p.parseOffset16List(pairSetCount); for (var firstGlyph = 0; firstGlyph < pairSetCount; firstGlyph++) { var pairSetOffset = pairSetOffsets[firstGlyph]; var sharedPairSet = sharedPairSets[pairSetOffset]; if (!sharedPairSet) { // Parse a pairset table in a pair adjustment subtable format 1 sharedPairSet = {}; p.relativeOffset = pairSetOffset; var pairValueCount = p.parseUShort(); for (; pairValueCount--;) { var secondGlyph = p.parseUShort(); if (valueFormat1) value1 = p.parseShort(); if (valueFormat2) value2 = p.parseShort(); // We only support valueFormat1 = 4 and valueFormat2 = 0, // so value1 is the XAdvance and value2 is empty. sharedPairSet[secondGlyph] = value1; } } pairSet[coverage[firstGlyph]] = sharedPairSet; } return function(leftGlyph, rightGlyph) { var pairs = pairSet[leftGlyph]; if (pairs) return pairs[rightGlyph]; }; } else if (format === 2) { // Pair Positioning Adjustment: Format 2 var classDef1Offset = p.parseUShort(); var classDef2Offset = p.parseUShort(); var class1Count = p.parseUShort(); var class2Count = p.parseUShort(); var getClass1 = parseClassDefTable(data, start + classDef1Offset); var getClass2 = parseClassDefTable(data, start + classDef2Offset); // Parse kerning values by class pair. var kerningMatrix = []; for (var i = 0; i < class1Count; i++) { var kerningRow = kerningMatrix[i] = []; for (var j = 0; j < class2Count; j++) { if (valueFormat1) value1 = p.parseShort(); if (valueFormat2) value2 = p.parseShort(); // We only support valueFormat1 = 4 and valueFormat2 = 0, // so value1 is the XAdvance and value2 is empty. kerningRow[j] = value1; } } // Convert coverage list to a hash var covered = {}; for (i = 0; i < coverage.length; i++) covered[coverage[i]] = 1; // Get the kerning value for a specific glyph pair. return function(leftGlyph, rightGlyph) { if (!covered[leftGlyph]) return; var class1 = getClass1(leftGlyph); var class2 = getClass2(rightGlyph); var kerningRow = kerningMatrix[class1]; if (kerningRow) { return kerningRow[class2]; } }; } } // Parse a LookupTable (present in of GPOS, GSUB, GDEF, BASE, JSTF tables). function parseLookupTable(data, start) { var p = new parse.Parser(data, start); var lookupType = p.parseUShort(); var lookupFlag = p.parseUShort(); var useMarkFilteringSet = lookupFlag & 0x10; var subTableCount = p.parseUShort(); var subTableOffsets = p.parseOffset16List(subTableCount); var table = { lookupType: lookupType, lookupFlag: lookupFlag, markFilteringSet: useMarkFilteringSet ? p.parseUShort() : -1 }; // LookupType 2, Pair adjustment if (lookupType === 2) { var subtables = []; for (var i = 0; i < subTableCount; i++) { var pairPosSubTable = parsePairPosSubTable(data, start + subTableOffsets[i]); if (pairPosSubTable) subtables.push(pairPosSubTable); } // Return a function which finds the kerning values in the subtables. table.getKerningValue = function(leftGlyph, rightGlyph) { for (var i = subtables.length; i--;) { var value = subtables[i](leftGlyph, rightGlyph); if (value !== undefined) return value; } return 0; }; } return table; } // Parse the `GPOS` table which contains, among other things, kerning pairs. // https://www.microsoft.com/typography/OTSPEC/gpos.htm function parseGposTable(data, start, font) { var p = new parse.Parser(data, start); var tableVersion = p.parseFixed(); check.argument(tableVersion === 1, 'Unsupported GPOS table version.'); // ScriptList and FeatureList - ignored for now parseTaggedListTable(data, start + p.parseUShort()); // 'kern' is the feature we are looking for. parseTaggedListTable(data, start + p.parseUShort()); // LookupList var lookupListOffset = p.parseUShort(); p.relativeOffset = lookupListOffset; var lookupCount = p.parseUShort(); var lookupTableOffsets = p.parseOffset16List(lookupCount); var lookupListAbsoluteOffset = start + lookupListOffset; for (var i = 0; i < lookupCount; i++) { var table = parseLookupTable(data, lookupListAbsoluteOffset + lookupTableOffsets[i]); if (table.lookupType === 2 && !font.getGposKerningValue) font.getGposKerningValue = table.getKerningValue; } } exports.parse = parseGposTable; },{"../check":7,"../parse":16}],25:[function(_dereq_,module,exports){ // The `GSUB` table contains ligatures, among other things. // https://www.microsoft.com/typography/OTSPEC/gsub.htm 'use strict'; var check = _dereq_('../check'); var Parser = _dereq_('../parse').Parser; var subtableParsers = new Array(9); // subtableParsers[0] is unused var table = _dereq_('../table'); // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#SS subtableParsers[1] = function parseLookup1() { var start = this.offset + this.relativeOffset; var substFormat = this.parseUShort(); if (substFormat === 1) { return { substFormat: 1, coverage: this.parsePointer(Parser.coverage), deltaGlyphId: this.parseUShort() }; } else if (substFormat === 2) { return { substFormat: 2, coverage: this.parsePointer(Parser.coverage), substitute: this.parseOffset16List() }; } check.assert(false, '0x' + start.toString(16) + ': lookup type 1 format must be 1 or 2.'); }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#MS subtableParsers[2] = function parseLookup2() { var substFormat = this.parseUShort(); check.argument(substFormat === 1, 'GSUB Multiple Substitution Subtable identifier-format must be 1'); return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), sequences: this.parseListOfLists() }; }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#AS subtableParsers[3] = function parseLookup3() { var substFormat = this.parseUShort(); check.argument(substFormat === 1, 'GSUB Alternate Substitution Subtable identifier-format must be 1'); return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), alternateSets: this.parseListOfLists() }; }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#LS subtableParsers[4] = function parseLookup4() { var substFormat = this.parseUShort(); check.argument(substFormat === 1, 'GSUB ligature table identifier-format must be 1'); return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), ligatureSets: this.parseListOfLists(function() { return { ligGlyph: this.parseUShort(), components: this.parseUShortList(this.parseUShort() - 1) }; }) }; }; var lookupRecordDesc = { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CSF subtableParsers[5] = function parseLookup5() { var start = this.offset + this.relativeOffset; var substFormat = this.parseUShort(); if (substFormat === 1) { return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), ruleSets: this.parseListOfLists(function() { var glyphCount = this.parseUShort(); var substCount = this.parseUShort(); return { input: this.parseUShortList(glyphCount - 1), lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) }; }) }; } else if (substFormat === 2) { return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), classDef: this.parsePointer(Parser.classDef), classSets: this.parseListOfLists(function() { var glyphCount = this.parseUShort(); var substCount = this.parseUShort(); return { classes: this.parseUShortList(glyphCount - 1), lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) }; }) }; } else if (substFormat === 3) { var glyphCount = this.parseUShort(); var substCount = this.parseUShort(); return { substFormat: substFormat, coverages: this.parseList(glyphCount, Parser.pointer(Parser.coverage)), lookupRecords: this.parseRecordList(substCount, lookupRecordDesc) }; } check.assert(false, '0x' + start.toString(16) + ': lookup type 5 format must be 1, 2 or 3.'); }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CC subtableParsers[6] = function parseLookup6() { var start = this.offset + this.relativeOffset; var substFormat = this.parseUShort(); if (substFormat === 1) { return { substFormat: 1, coverage: this.parsePointer(Parser.coverage), chainRuleSets: this.parseListOfLists(function() { return { backtrack: this.parseUShortList(), input: this.parseUShortList(this.parseShort() - 1), lookahead: this.parseUShortList(), lookupRecords: this.parseRecordList(lookupRecordDesc) }; }) }; } else if (substFormat === 2) { return { substFormat: 2, coverage: this.parsePointer(Parser.coverage), backtrackClassDef: this.parsePointer(Parser.classDef), inputClassDef: this.parsePointer(Parser.classDef), lookaheadClassDef: this.parsePointer(Parser.classDef), chainClassSet: this.parseListOfLists(function() { return { backtrack: this.parseUShortList(), input: this.parseUShortList(this.parseShort() - 1), lookahead: this.parseUShortList(), lookupRecords: this.parseRecordList(lookupRecordDesc) }; }) }; } else if (substFormat === 3) { return { substFormat: 3, backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), inputCoverage: this.parseList(Parser.pointer(Parser.coverage)), lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), lookupRecords: this.parseRecordList(lookupRecordDesc) }; } check.assert(false, '0x' + start.toString(16) + ': lookup type 6 format must be 1, 2 or 3.'); }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#ES subtableParsers[7] = function parseLookup7() { // Extension Substitution subtable var substFormat = this.parseUShort(); check.argument(substFormat === 1, 'GSUB Extension Substitution subtable identifier-format must be 1'); var extensionLookupType = this.parseUShort(); var extensionParser = new Parser(this.data, this.offset + this.parseULong()); return { substFormat: 1, lookupType: extensionLookupType, extension: subtableParsers[extensionLookupType].call(extensionParser) }; }; // https://www.microsoft.com/typography/OTSPEC/GSUB.htm#RCCS subtableParsers[8] = function parseLookup8() { var substFormat = this.parseUShort(); check.argument(substFormat === 1, 'GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1'); return { substFormat: substFormat, coverage: this.parsePointer(Parser.coverage), backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)), lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)), substitutes: this.parseUShortList() }; }; // https://www.microsoft.com/typography/OTSPEC/gsub.htm function parseGsubTable(data, start) { start = start || 0; var p = new Parser(data, start); var tableVersion = p.parseVersion(); check.argument(tableVersion === 1, 'Unsupported GSUB table version.'); return { version: tableVersion, scripts: p.parseScriptList(), features: p.parseFeatureList(), lookups: p.parseLookupList(subtableParsers) }; } // GSUB Writing ////////////////////////////////////////////// var subtableMakers = new Array(9); subtableMakers[1] = function makeLookup1(subtable) { if (subtable.substFormat === 1) { return new table.Table('substitutionTable', [ {name: 'substFormat', type: 'USHORT', value: 1}, {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)}, {name: 'deltaGlyphID', type: 'USHORT', value: subtable.deltaGlyphId} ]); } else { return new table.Table('substitutionTable', [ {name: 'substFormat', type: 'USHORT', value: 2}, {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} ].concat(table.ushortList('substitute', subtable.substitute))); } check.fail('Lookup type 1 substFormat must be 1 or 2.'); }; subtableMakers[3] = function makeLookup3(subtable) { check.assert(subtable.substFormat === 1, 'Lookup type 3 substFormat must be 1.'); return new table.Table('substitutionTable', [ {name: 'substFormat', type: 'USHORT', value: 1}, {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} ].concat(table.tableList('altSet', subtable.alternateSets, function(alternateSet) { return new table.Table('alternateSetTable', table.ushortList('alternate', alternateSet)); }))); }; subtableMakers[4] = function makeLookup4(subtable) { check.assert(subtable.substFormat === 1, 'Lookup type 4 substFormat must be 1.'); return new table.Table('substitutionTable', [ {name: 'substFormat', type: 'USHORT', value: 1}, {name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)} ].concat(table.tableList('ligSet', subtable.ligatureSets, function(ligatureSet) { return new table.Table('ligatureSetTable', table.tableList('ligature', ligatureSet, function(ligature) { return new table.Table('ligatureTable', [{name: 'ligGlyph', type: 'USHORT', value: ligature.ligGlyph}] .concat(table.ushortList('component', ligature.components, ligature.components.length + 1)) ); })); }))); }; function makeGsubTable(gsub) { return new table.Table('GSUB', [ {name: 'version', type: 'ULONG', value: 0x10000}, {name: 'scripts', type: 'TABLE', value: new table.ScriptList(gsub.scripts)}, {name: 'features', type: 'TABLE', value: new table.FeatureList(gsub.features)}, {name: 'lookups', type: 'TABLE', value: new table.LookupList(gsub.lookups, subtableMakers)} ]); } exports.parse = parseGsubTable; exports.make = makeGsubTable; },{"../check":7,"../parse":16,"../table":19}],26:[function(_dereq_,module,exports){ // The `head` table contains global information about the font. // https://www.microsoft.com/typography/OTSPEC/head.htm 'use strict'; var check = _dereq_('../check'); var parse = _dereq_('../parse'); var table = _dereq_('../table'); // Parse the header `head` table function parseHeadTable(data, start) { var head = {}; var p = new parse.Parser(data, start); head.version = p.parseVersion(); head.fontRevision = Math.round(p.parseFixed() * 1000) / 1000; head.checkSumAdjustment = p.parseULong(); head.magicNumber = p.parseULong(); check.argument(head.magicNumber === 0x5F0F3CF5, 'Font header has wrong magic number.'); head.flags = p.parseUShort(); head.unitsPerEm = p.parseUShort(); head.created = p.parseLongDateTime(); head.modified = p.parseLongDateTime(); head.xMin = p.parseShort(); head.yMin = p.parseShort(); head.xMax = p.parseShort(); head.yMax = p.parseShort(); head.macStyle = p.parseUShort(); head.lowestRecPPEM = p.parseUShort(); head.fontDirectionHint = p.parseShort(); head.indexToLocFormat = p.parseShort(); head.glyphDataFormat = p.parseShort(); return head; } function makeHeadTable(options) { // Apple Mac timestamp epoch is 01/01/1904 not 01/01/1970 var timestamp = Math.round(new Date().getTime() / 1000) + 2082844800; var createdTimestamp = timestamp; if (options.createdTimestamp) { createdTimestamp = options.createdTimestamp + 2082844800; } return new table.Table('head', [ {name: 'version', type: 'FIXED', value: 0x00010000}, {name: 'fontRevision', type: 'FIXED', value: 0x00010000}, {name: 'checkSumAdjustment', type: 'ULONG', value: 0}, {name: 'magicNumber', type: 'ULONG', value: 0x5F0F3CF5}, {name: 'flags', type: 'USHORT', value: 0}, {name: 'unitsPerEm', type: 'USHORT', value: 1000}, {name: 'created', type: 'LONGDATETIME', value: createdTimestamp}, {name: 'modified', type: 'LONGDATETIME', value: timestamp}, {name: 'xMin', type: 'SHORT', value: 0}, {name: 'yMin', type: 'SHORT', value: 0}, {name: 'xMax', type: 'SHORT', value: 0}, {name: 'yMax', type: 'SHORT', value: 0}, {name: 'macStyle', type: 'USHORT', value: 0}, {name: 'lowestRecPPEM', type: 'USHORT', value: 0}, {name: 'fontDirectionHint', type: 'SHORT', value: 2}, {name: 'indexToLocFormat', type: 'SHORT', value: 0}, {name: 'glyphDataFormat', type: 'SHORT', value: 0} ], options); } exports.parse = parseHeadTable; exports.make = makeHeadTable; },{"../check":7,"../parse":16,"../table":19}],27:[function(_dereq_,module,exports){ // The `hhea` table contains information for horizontal layout. // https://www.microsoft.com/typography/OTSPEC/hhea.htm 'use strict'; var parse = _dereq_('../parse'); var table = _dereq_('../table'); // Parse the horizontal header `hhea` table function parseHheaTable(data, start) { var hhea = {}; var p = new parse.Parser(data, start); hhea.version = p.parseVersion(); hhea.ascender = p.parseShort(); hhea.descender = p.parseShort(); hhea.lineGap = p.parseShort(); hhea.advanceWidthMax = p.parseUShort(); hhea.minLeftSideBearing = p.parseShort(); hhea.minRightSideBearing = p.parseShort(); hhea.xMaxExtent = p.parseShort(); hhea.caretSlopeRise = p.parseShort(); hhea.caretSlopeRun = p.parseShort(); hhea.caretOffset = p.parseShort(); p.relativeOffset += 8; hhea.metricDataFormat = p.parseShort(); hhea.numberOfHMetrics = p.parseUShort(); return hhea; } function makeHheaTable(options) { return new table.Table('hhea', [ {name: 'version', type: 'FIXED', value: 0x00010000}, {name: 'ascender', type: 'FWORD', value: 0}, {name: 'descender', type: 'FWORD', value: 0}, {name: 'lineGap', type: 'FWORD', value: 0}, {name: 'advanceWidthMax', type: 'UFWORD', value: 0}, {name: 'minLeftSideBearing', type: 'FWORD', value: 0}, {name: 'minRightSideBearing', type: 'FWORD', value: 0}, {name: 'xMaxExtent', type: 'FWORD', value: 0}, {name: 'caretSlopeRise', type: 'SHORT', value: 1}, {name: 'caretSlopeRun', type: 'SHORT', value: 0}, {name: 'caretOffset', type: 'SHORT', value: 0}, {name: 'reserved1', type: 'SHORT', value: 0}, {name: 'reserved2', type: 'SHORT', value: 0}, {name: 'reserved3', type: 'SHORT', value: 0}, {name: 'reserved4', type: 'SHORT', value: 0}, {name: 'metricDataFormat', type: 'SHORT', value: 0}, {name: 'numberOfHMetrics', type: 'USHORT', value: 0} ], options); } exports.parse = parseHheaTable; exports.make = makeHheaTable; },{"../parse":16,"../table":19}],28:[function(_dereq_,module,exports){ // The `hmtx` table contains the horizontal metrics for all glyphs. // https://www.microsoft.com/typography/OTSPEC/hmtx.htm 'use strict'; var parse = _dereq_('../parse'); var table = _dereq_('../table'); // Parse the `hmtx` table, which contains the horizontal metrics for all glyphs. // This function augments the glyph array, adding the advanceWidth and leftSideBearing to each glyph. function parseHmtxTable(data, start, numMetrics, numGlyphs, glyphs) { var advanceWidth; var leftSideBearing; var p = new parse.Parser(data, start); for (var i = 0; i < numGlyphs; i += 1) { // If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs. if (i < numMetrics) { advanceWidth = p.parseUShort(); leftSideBearing = p.parseShort(); } var glyph = glyphs.get(i); glyph.advanceWidth = advanceWidth; glyph.leftSideBearing = leftSideBearing; } } function makeHmtxTable(glyphs) { var t = new table.Table('hmtx', []); for (var i = 0; i < glyphs.length; i += 1) { var glyph = glyphs.get(i); var advanceWidth = glyph.advanceWidth || 0; var leftSideBearing = glyph.leftSideBearing || 0; t.fields.push({name: 'advanceWidth_' + i, type: 'USHORT', value: advanceWidth}); t.fields.push({name: 'leftSideBearing_' + i, type: 'SHORT', value: leftSideBearing}); } return t; } exports.parse = parseHmtxTable; exports.make = makeHmtxTable; },{"../parse":16,"../table":19}],29:[function(_dereq_,module,exports){ // The `kern` table contains kerning pairs. // Note that some fonts use the GPOS OpenType layout table to specify kerning. // https://www.microsoft.com/typography/OTSPEC/kern.htm 'use strict'; var check = _dereq_('../check'); var parse = _dereq_('../parse'); function parseWindowsKernTable(p) { var pairs = {}; // Skip nTables. p.skip('uShort'); var subtableVersion = p.parseUShort(); check.argument(subtableVersion === 0, 'Unsupported kern sub-table version.'); // Skip subtableLength, subtableCoverage p.skip('uShort', 2); var nPairs = p.parseUShort(); // Skip searchRange, entrySelector, rangeShift. p.skip('uShort', 3); for (var i = 0; i < nPairs; i += 1) { var leftIndex = p.parseUShort(); var rightIndex = p.parseUShort(); var value = p.parseShort(); pairs[leftIndex + ',' + rightIndex] = value; } return pairs; } function parseMacKernTable(p) { var pairs = {}; // The Mac kern table stores the version as a fixed (32 bits) but we only loaded the first 16 bits. // Skip the rest. p.skip('uShort'); var nTables = p.parseULong(); //check.argument(nTables === 1, 'Only 1 subtable is supported (got ' + nTables + ').'); if (nTables > 1) { console.warn('Only the first kern subtable is supported.'); } p.skip('uLong'); var coverage = p.parseUShort(); var subtableVersion = coverage & 0xFF; p.skip('uShort'); if (subtableVersion === 0) { var nPairs = p.parseUShort(); // Skip searchRange, entrySelector, rangeShift. p.skip('uShort', 3); for (var i = 0; i < nPairs; i += 1) { var leftIndex = p.parseUShort(); var rightIndex = p.parseUShort(); var value = p.parseShort(); pairs[leftIndex + ',' + rightIndex] = value; } } return pairs; } // Parse the `kern` table which contains kerning pairs. function parseKernTable(data, start) { var p = new parse.Parser(data, start); var tableVersion = p.parseUShort(); if (tableVersion === 0) { return parseWindowsKernTable(p); } else if (tableVersion === 1) { return parseMacKernTable(p); } else { throw new Error('Unsupported kern table version (' + tableVersion + ').'); } } exports.parse = parseKernTable; },{"../check":7,"../parse":16}],30:[function(_dereq_,module,exports){ // The `loca` table stores the offsets to the locations of the glyphs in the font. // https://www.microsoft.com/typography/OTSPEC/loca.htm 'use strict'; var parse = _dereq_('../parse'); // Parse the `loca` table. This table stores the offsets to the locations of the glyphs in the font, // relative to the beginning of the glyphData table. // The number of glyphs stored in the `loca` table is specified in the `maxp` table (under numGlyphs) // The loca table has two versions: a short version where offsets are stored as uShorts, and a long // version where offsets are stored as uLongs. The `head` table specifies which version to use // (under indexToLocFormat). function parseLocaTable(data, start, numGlyphs, shortVersion) { var p = new parse.Parser(data, start); var parseFn = shortVersion ? p.parseUShort : p.parseULong; // There is an extra entry after the last index element to compute the length of the last glyph. // That's why we use numGlyphs + 1. var glyphOffsets = []; for (var i = 0; i < numGlyphs + 1; i += 1) { var glyphOffset = parseFn.call(p); if (shortVersion) { // The short table version stores the actual offset divided by 2. glyphOffset *= 2; } glyphOffsets.push(glyphOffset); } return glyphOffsets; } exports.parse = parseLocaTable; },{"../parse":16}],31:[function(_dereq_,module,exports){ // The `ltag` table stores IETF BCP-47 language tags. It allows supporting // languages for which TrueType does not assign a numeric code. // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6ltag.html // http://www.w3.org/International/articles/language-tags/ // http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry 'use strict'; var check = _dereq_('../check'); var parse = _dereq_('../parse'); var table = _dereq_('../table'); function makeLtagTable(tags) { var result = new table.Table('ltag', [ {name: 'version', type: 'ULONG', value: 1}, {name: 'flags', type: 'ULONG', value: 0}, {name: 'numTags', type: 'ULONG', value: tags.length} ]); var stringPool = ''; var stringPoolOffset = 12 + tags.length * 4; for (var i = 0; i < tags.length; ++i) { var pos = stringPool.indexOf(tags[i]); if (pos < 0) { pos = stringPool.length; stringPool += tags[i]; } result.fields.push({name: 'offset ' + i, type: 'USHORT', value: stringPoolOffset + pos}); result.fields.push({name: 'length ' + i, type: 'USHORT', value: tags[i].length}); } result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool}); return result; } function parseLtagTable(data, start) { var p = new parse.Parser(data, start); var tableVersion = p.parseULong(); check.argument(tableVersion === 1, 'Unsupported ltag table version.'); // The 'ltag' specification does not define any flags; skip the field. p.skip('uLong', 1); var numTags = p.parseULong(); var tags = []; for (var i = 0; i < numTags; i++) { var tag = ''; var offset = start + p.parseUShort(); var length = p.parseUShort(); for (var j = offset; j < offset + length; ++j) { tag += String.fromCharCode(data.getInt8(j)); } tags.push(tag); } return tags; } exports.make = makeLtagTable; exports.parse = parseLtagTable; },{"../check":7,"../parse":16,"../table":19}],32:[function(_dereq_,module,exports){ // The `maxp` table establishes the memory requirements for the font. // We need it just to get the number of glyphs in the font. // https://www.microsoft.com/typography/OTSPEC/maxp.htm 'use strict'; var parse = _dereq_('../parse'); var table = _dereq_('../table'); // Parse the maximum profile `maxp` table. function parseMaxpTable(data, start) { var maxp = {}; var p = new parse.Parser(data, start); maxp.version = p.parseVersion(); maxp.numGlyphs = p.parseUShort(); if (maxp.version === 1.0) { maxp.maxPoints = p.parseUShort(); maxp.maxContours = p.parseUShort(); maxp.maxCompositePoints = p.parseUShort(); maxp.maxCompositeContours = p.parseUShort(); maxp.maxZones = p.parseUShort(); maxp.maxTwilightPoints = p.parseUShort(); maxp.maxStorage = p.parseUShort(); maxp.maxFunctionDefs = p.parseUShort(); maxp.maxInstructionDefs = p.parseUShort(); maxp.maxStackElements = p.parseUShort(); maxp.maxSizeOfInstructions = p.parseUShort(); maxp.maxComponentElements = p.parseUShort(); maxp.maxComponentDepth = p.parseUShort(); } return maxp; } function makeMaxpTable(numGlyphs) { return new table.Table('maxp', [ {name: 'version', type: 'FIXED', value: 0x00005000}, {name: 'numGlyphs', type: 'USHORT', value: numGlyphs} ]); } exports.parse = parseMaxpTable; exports.make = makeMaxpTable; },{"../parse":16,"../table":19}],33:[function(_dereq_,module,exports){ // The `GPOS` table contains kerning pairs, among other things. // https://www.microsoft.com/typography/OTSPEC/gpos.htm 'use strict'; var types = _dereq_('../types'); var decode = types.decode; var check = _dereq_('../check'); var parse = _dereq_('../parse'); var table = _dereq_('../table'); // Parse the metadata `meta` table. // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6meta.html function parseMetaTable(data, start) { var p = new parse.Parser(data, start); var tableVersion = p.parseULong(); check.argument(tableVersion === 1, 'Unsupported META table version.'); p.parseULong(); // flags - currently unused and set to 0 p.parseULong(); // tableOffset var numDataMaps = p.parseULong(); var tags = {}; for (var i = 0; i < numDataMaps; i++) { var tag = p.parseTag(); var dataOffset = p.parseULong(); var dataLength = p.parseULong(); var text = decode.UTF8(data, start + dataOffset, dataLength); tags[tag] = text; } return tags; } function makeMetaTable(tags) { var numTags = Object.keys(tags).length; var stringPool = ''; var stringPoolOffset = 16 + numTags * 12; var result = new table.Table('meta', [ {name: 'version', type: 'ULONG', value: 1}, {name: 'flags', type: 'ULONG', value: 0}, {name: 'offset', type: 'ULONG', value: stringPoolOffset}, {name: 'numTags', type: 'ULONG', value: numTags} ]); for (var tag in tags) { var pos = stringPool.length; stringPool += tags[tag]; result.fields.push({name: 'tag ' + tag, type: 'TAG', value: tag}); result.fields.push({name: 'offset ' + tag, type: 'ULONG', value: stringPoolOffset + pos}); result.fields.push({name: 'length ' + tag, type: 'ULONG', value: tags[tag].length}); } result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool}); return result; } exports.parse = parseMetaTable; exports.make = makeMetaTable; },{"../check":7,"../parse":16,"../table":19,"../types":38}],34:[function(_dereq_,module,exports){ // The `name` naming table. // https://www.microsoft.com/typography/OTSPEC/name.htm 'use strict'; var types = _dereq_('../types'); var decode = types.decode; var encode = types.encode; var parse = _dereq_('../parse'); var table = _dereq_('../table'); // NameIDs for the name table. var nameTableNames = [ 'copyright', // 0 'fontFamily', // 1 'fontSubfamily', // 2 'uniqueID', // 3 'fullName', // 4 'version', // 5 'postScriptName', // 6 'trademark', // 7 'manufacturer', // 8 'designer', // 9 'description', // 10 'manufacturerURL', // 11 'designerURL', // 12 'license', // 13 'licenseURL', // 14 'reserved', // 15 'preferredFamily', // 16 'preferredSubfamily', // 17 'compatibleFullName', // 18 'sampleText', // 19 'postScriptFindFontName', // 20 'wwsFamily', // 21 'wwsSubfamily' // 22 ]; var macLanguages = { 0: 'en', 1: 'fr', 2: 'de', 3: 'it', 4: 'nl', 5: 'sv', 6: 'es', 7: 'da', 8: 'pt', 9: 'no', 10: 'he', 11: 'ja', 12: 'ar', 13: 'fi', 14: 'el', 15: 'is', 16: 'mt', 17: 'tr', 18: 'hr', 19: 'zh-Hant', 20: 'ur', 21: 'hi', 22: 'th', 23: 'ko', 24: 'lt', 25: 'pl', 26: 'hu', 27: 'es', 28: 'lv', 29: 'se', 30: 'fo', 31: 'fa', 32: 'ru', 33: 'zh', 34: 'nl-BE', 35: 'ga', 36: 'sq', 37: 'ro', 38: 'cz', 39: 'sk', 40: 'si', 41: 'yi', 42: 'sr', 43: 'mk', 44: 'bg', 45: 'uk', 46: 'be', 47: 'uz', 48: 'kk', 49: 'az-Cyrl', 50: 'az-Arab', 51: 'hy', 52: 'ka', 53: 'mo', 54: 'ky', 55: 'tg', 56: 'tk', 57: 'mn-CN', 58: 'mn', 59: 'ps', 60: 'ks', 61: 'ku', 62: 'sd', 63: 'bo', 64: 'ne', 65: 'sa', 66: 'mr', 67: 'bn', 68: 'as', 69: 'gu', 70: 'pa', 71: 'or', 72: 'ml', 73: 'kn', 74: 'ta', 75: 'te', 76: 'si', 77: 'my', 78: 'km', 79: 'lo', 80: 'vi', 81: 'id', 82: 'tl', 83: 'ms', 84: 'ms-Arab', 85: 'am', 86: 'ti', 87: 'om', 88: 'so', 89: 'sw', 90: 'rw', 91: 'rn', 92: 'ny', 93: 'mg', 94: 'eo', 128: 'cy', 129: 'eu', 130: 'ca', 131: 'la', 132: 'qu', 133: 'gn', 134: 'ay', 135: 'tt', 136: 'ug', 137: 'dz', 138: 'jv', 139: 'su', 140: 'gl', 141: 'af', 142: 'br', 143: 'iu', 144: 'gd', 145: 'gv', 146: 'ga', 147: 'to', 148: 'el-polyton', 149: 'kl', 150: 'az', 151: 'nn' }; // MacOS language ID → MacOS script ID // // Note that the script ID is not sufficient to determine what encoding // to use in TrueType files. For some languages, MacOS used a modification // of a mainstream script. For example, an Icelandic name would be stored // with smRoman in the TrueType naming table, but the actual encoding // is a special Icelandic version of the normal Macintosh Roman encoding. // As another example, Inuktitut uses an 8-bit encoding for Canadian Aboriginal // Syllables but MacOS had run out of available script codes, so this was // done as a (pretty radical) "modification" of Ethiopic. // // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt var macLanguageToScript = { 0: 0, // langEnglish → smRoman 1: 0, // langFrench → smRoman 2: 0, // langGerman → smRoman 3: 0, // langItalian → smRoman 4: 0, // langDutch → smRoman 5: 0, // langSwedish → smRoman 6: 0, // langSpanish → smRoman 7: 0, // langDanish → smRoman 8: 0, // langPortuguese → smRoman 9: 0, // langNorwegian → smRoman 10: 5, // langHebrew → smHebrew 11: 1, // langJapanese → smJapanese 12: 4, // langArabic → smArabic 13: 0, // langFinnish → smRoman 14: 6, // langGreek → smGreek 15: 0, // langIcelandic → smRoman (modified) 16: 0, // langMaltese → smRoman 17: 0, // langTurkish → smRoman (modified) 18: 0, // langCroatian → smRoman (modified) 19: 2, // langTradChinese → smTradChinese 20: 4, // langUrdu → smArabic 21: 9, // langHindi → smDevanagari 22: 21, // langThai → smThai 23: 3, // langKorean → smKorean 24: 29, // langLithuanian → smCentralEuroRoman 25: 29, // langPolish → smCentralEuroRoman 26: 29, // langHungarian → smCentralEuroRoman 27: 29, // langEstonian → smCentralEuroRoman 28: 29, // langLatvian → smCentralEuroRoman 29: 0, // langSami → smRoman 30: 0, // langFaroese → smRoman (modified) 31: 4, // langFarsi → smArabic (modified) 32: 7, // langRussian → smCyrillic 33: 25, // langSimpChinese → smSimpChinese 34: 0, // langFlemish → smRoman 35: 0, // langIrishGaelic → smRoman (modified) 36: 0, // langAlbanian → smRoman 37: 0, // langRomanian → smRoman (modified) 38: 29, // langCzech → smCentralEuroRoman 39: 29, // langSlovak → smCentralEuroRoman 40: 0, // langSlovenian → smRoman (modified) 41: 5, // langYiddish → smHebrew 42: 7, // langSerbian → smCyrillic 43: 7, // langMacedonian → smCyrillic 44: 7, // langBulgarian → smCyrillic 45: 7, // langUkrainian → smCyrillic (modified) 46: 7, // langByelorussian → smCyrillic 47: 7, // langUzbek → smCyrillic 48: 7, // langKazakh → smCyrillic 49: 7, // langAzerbaijani → smCyrillic 50: 4, // langAzerbaijanAr → smArabic 51: 24, // langArmenian → smArmenian 52: 23, // langGeorgian → smGeorgian 53: 7, // langMoldavian → smCyrillic 54: 7, // langKirghiz → smCyrillic 55: 7, // langTajiki → smCyrillic 56: 7, // langTurkmen → smCyrillic 57: 27, // langMongolian → smMongolian 58: 7, // langMongolianCyr → smCyrillic 59: 4, // langPashto → smArabic 60: 4, // langKurdish → smArabic 61: 4, // langKashmiri → smArabic 62: 4, // langSindhi → smArabic 63: 26, // langTibetan → smTibetan 64: 9, // langNepali → smDevanagari 65: 9, // langSanskrit → smDevanagari 66: 9, // langMarathi → smDevanagari 67: 13, // langBengali → smBengali 68: 13, // langAssamese → smBengali 69: 11, // langGujarati → smGujarati 70: 10, // langPunjabi → smGurmukhi 71: 12, // langOriya → smOriya 72: 17, // langMalayalam → smMalayalam 73: 16, // langKannada → smKannada 74: 14, // langTamil → smTamil 75: 15, // langTelugu → smTelugu 76: 18, // langSinhalese → smSinhalese 77: 19, // langBurmese → smBurmese 78: 20, // langKhmer → smKhmer 79: 22, // langLao → smLao 80: 30, // langVietnamese → smVietnamese 81: 0, // langIndonesian → smRoman 82: 0, // langTagalog → smRoman 83: 0, // langMalayRoman → smRoman 84: 4, // langMalayArabic → smArabic 85: 28, // langAmharic → smEthiopic 86: 28, // langTigrinya → smEthiopic 87: 28, // langOromo → smEthiopic 88: 0, // langSomali → smRoman 89: 0, // langSwahili → smRoman 90: 0, // langKinyarwanda → smRoman 91: 0, // langRundi → smRoman 92: 0, // langNyanja → smRoman 93: 0, // langMalagasy → smRoman 94: 0, // langEsperanto → smRoman 128: 0, // langWelsh → smRoman (modified) 129: 0, // langBasque → smRoman 130: 0, // langCatalan → smRoman 131: 0, // langLatin → smRoman 132: 0, // langQuechua → smRoman 133: 0, // langGuarani → smRoman 134: 0, // langAymara → smRoman 135: 7, // langTatar → smCyrillic 136: 4, // langUighur → smArabic 137: 26, // langDzongkha → smTibetan 138: 0, // langJavaneseRom → smRoman 139: 0, // langSundaneseRom → smRoman 140: 0, // langGalician → smRoman 141: 0, // langAfrikaans → smRoman 142: 0, // langBreton → smRoman (modified) 143: 28, // langInuktitut → smEthiopic (modified) 144: 0, // langScottishGaelic → smRoman (modified) 145: 0, // langManxGaelic → smRoman (modified) 146: 0, // langIrishGaelicScript → smRoman (modified) 147: 0, // langTongan → smRoman 148: 6, // langGreekAncient → smRoman 149: 0, // langGreenlandic → smRoman 150: 0, // langAzerbaijanRoman → smRoman 151: 0 // langNynorsk → smRoman }; // While Microsoft indicates a region/country for all its language // IDs, we omit the region code if it's equal to the "most likely // region subtag" according to Unicode CLDR. For scripts, we omit // the subtag if it is equal to the Suppress-Script entry in the // IANA language subtag registry for IETF BCP 47. // // For example, Microsoft states that its language code 0x041A is // Croatian in Croatia. We transform this to the BCP 47 language code 'hr' // and not 'hr-HR' because Croatia is the default country for Croatian, // according to Unicode CLDR. As another example, Microsoft states // that 0x101A is Croatian (Latin) in Bosnia-Herzegovina. We transform // this to 'hr-BA' and not 'hr-Latn-BA' because Latin is the default script // for the Croatian language, according to IANA. // // http://www.unicode.org/cldr/charts/latest/supplemental/likely_subtags.html // http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry var windowsLanguages = { 0x0436: 'af', 0x041C: 'sq', 0x0484: 'gsw', 0x045E: 'am', 0x1401: 'ar-DZ', 0x3C01: 'ar-BH', 0x0C01: 'ar', 0x0801: 'ar-IQ', 0x2C01: 'ar-JO', 0x3401: 'ar-KW', 0x3001: 'ar-LB', 0x1001: 'ar-LY', 0x1801: 'ary', 0x2001: 'ar-OM', 0x4001: 'ar-QA', 0x0401: 'ar-SA', 0x2801: 'ar-SY', 0x1C01: 'aeb', 0x3801: 'ar-AE', 0x2401: 'ar-YE', 0x042B: 'hy', 0x044D: 'as', 0x082C: 'az-Cyrl', 0x042C: 'az', 0x046D: 'ba', 0x042D: 'eu', 0x0423: 'be', 0x0845: 'bn', 0x0445: 'bn-IN', 0x201A: 'bs-Cyrl', 0x141A: 'bs', 0x047E: 'br', 0x0402: 'bg', 0x0403: 'ca', 0x0C04: 'zh-HK', 0x1404: 'zh-MO', 0x0804: 'zh', 0x1004: 'zh-SG', 0x0404: 'zh-TW', 0x0483: 'co', 0x041A: 'hr', 0x101A: 'hr-BA', 0x0405: 'cs', 0x0406: 'da', 0x048C: 'prs', 0x0465: 'dv', 0x0813: 'nl-BE', 0x0413: 'nl', 0x0C09: 'en-AU', 0x2809: 'en-BZ', 0x1009: 'en-CA', 0x2409: 'en-029', 0x4009: 'en-IN', 0x1809: 'en-IE', 0x2009: 'en-JM', 0x4409: 'en-MY', 0x1409: 'en-NZ', 0x3409: 'en-PH', 0x4809: 'en-SG', 0x1C09: 'en-ZA', 0x2C09: 'en-TT', 0x0809: 'en-GB', 0x0409: 'en', 0x3009: 'en-ZW', 0x0425: 'et', 0x0438: 'fo', 0x0464: 'fil', 0x040B: 'fi', 0x080C: 'fr-BE', 0x0C0C: 'fr-CA', 0x040C: 'fr', 0x140C: 'fr-LU', 0x180C: 'fr-MC', 0x100C: 'fr-CH', 0x0462: 'fy', 0x0456: 'gl', 0x0437: 'ka', 0x0C07: 'de-AT', 0x0407: 'de', 0x1407: 'de-LI', 0x1007: 'de-LU', 0x0807: 'de-CH', 0x0408: 'el', 0x046F: 'kl', 0x0447: 'gu', 0x0468: 'ha', 0x040D: 'he', 0x0439: 'hi', 0x040E: 'hu', 0x040F: 'is', 0x0470: 'ig', 0x0421: 'id', 0x045D: 'iu', 0x085D: 'iu-Latn', 0x083C: 'ga', 0x0434: 'xh', 0x0435: 'zu', 0x0410: 'it', 0x0810: 'it-CH', 0x0411: 'ja', 0x044B: 'kn', 0x043F: 'kk', 0x0453: 'km', 0x0486: 'quc', 0x0487: 'rw', 0x0441: 'sw', 0x0457: 'kok', 0x0412: 'ko', 0x0440: 'ky', 0x0454: 'lo', 0x0426: 'lv', 0x0427: 'lt', 0x082E: 'dsb', 0x046E: 'lb', 0x042F: 'mk', 0x083E: 'ms-BN', 0x043E: 'ms', 0x044C: 'ml', 0x043A: 'mt', 0x0481: 'mi', 0x047A: 'arn', 0x044E: 'mr', 0x047C: 'moh', 0x0450: 'mn', 0x0850: 'mn-CN', 0x0461: 'ne', 0x0414: 'nb', 0x0814: 'nn', 0x0482: 'oc', 0x0448: 'or', 0x0463: 'ps', 0x0415: 'pl', 0x0416: 'pt', 0x0816: 'pt-PT', 0x0446: 'pa', 0x046B: 'qu-BO', 0x086B: 'qu-EC', 0x0C6B: 'qu', 0x0418: 'ro', 0x0417: 'rm', 0x0419: 'ru', 0x243B: 'smn', 0x103B: 'smj-NO', 0x143B: 'smj', 0x0C3B: 'se-FI', 0x043B: 'se', 0x083B: 'se-SE', 0x203B: 'sms', 0x183B: 'sma-NO', 0x1C3B: 'sms', 0x044F: 'sa', 0x1C1A: 'sr-Cyrl-BA', 0x0C1A: 'sr', 0x181A: 'sr-Latn-BA', 0x081A: 'sr-Latn', 0x046C: 'nso', 0x0432: 'tn', 0x045B: 'si', 0x041B: 'sk', 0x0424: 'sl', 0x2C0A: 'es-AR', 0x400A: 'es-BO', 0x340A: 'es-CL', 0x240A: 'es-CO', 0x140A: 'es-CR', 0x1C0A: 'es-DO', 0x300A: 'es-EC', 0x440A: 'es-SV', 0x100A: 'es-GT', 0x480A: 'es-HN', 0x080A: 'es-MX', 0x4C0A: 'es-NI', 0x180A: 'es-PA', 0x3C0A: 'es-PY', 0x280A: 'es-PE', 0x500A: 'es-PR', // Microsoft has defined two different language codes for // “Spanish with modern sorting” and “Spanish with traditional // sorting”. This makes sense for collation APIs, and it would be // possible to express this in BCP 47 language tags via Unicode // extensions (eg., es-u-co-trad is Spanish with traditional // sorting). However, for storing names in fonts, the distinction // does not make sense, so we give “es” in both cases. 0x0C0A: 'es', 0x040A: 'es', 0x540A: 'es-US', 0x380A: 'es-UY', 0x200A: 'es-VE', 0x081D: 'sv-FI', 0x041D: 'sv', 0x045A: 'syr', 0x0428: 'tg', 0x085F: 'tzm', 0x0449: 'ta', 0x0444: 'tt', 0x044A: 'te', 0x041E: 'th', 0x0451: 'bo', 0x041F: 'tr', 0x0442: 'tk', 0x0480: 'ug', 0x0422: 'uk', 0x042E: 'hsb', 0x0420: 'ur', 0x0843: 'uz-Cyrl', 0x0443: 'uz', 0x042A: 'vi', 0x0452: 'cy', 0x0488: 'wo', 0x0485: 'sah', 0x0478: 'ii', 0x046A: 'yo' }; // Returns a IETF BCP 47 language code, for example 'zh-Hant' // for 'Chinese in the traditional script'. function getLanguageCode(platformID, languageID, ltag) { switch (platformID) { case 0: // Unicode if (languageID === 0xFFFF) { return 'und'; } else if (ltag) { return ltag[languageID]; } break; case 1: // Macintosh return macLanguages[languageID]; case 3: // Windows return windowsLanguages[languageID]; } return undefined; } var utf16 = 'utf-16'; // MacOS script ID → encoding. This table stores the default case, // which can be overridden by macLanguageEncodings. var macScriptEncodings = { 0: 'macintosh', // smRoman 1: 'x-mac-japanese', // smJapanese 2: 'x-mac-chinesetrad', // smTradChinese 3: 'x-mac-korean', // smKorean 6: 'x-mac-greek', // smGreek 7: 'x-mac-cyrillic', // smCyrillic 9: 'x-mac-devanagai', // smDevanagari 10: 'x-mac-gurmukhi', // smGurmukhi 11: 'x-mac-gujarati', // smGujarati 12: 'x-mac-oriya', // smOriya 13: 'x-mac-bengali', // smBengali 14: 'x-mac-tamil', // smTamil 15: 'x-mac-telugu', // smTelugu 16: 'x-mac-kannada', // smKannada 17: 'x-mac-malayalam', // smMalayalam 18: 'x-mac-sinhalese', // smSinhalese 19: 'x-mac-burmese', // smBurmese 20: 'x-mac-khmer', // smKhmer 21: 'x-mac-thai', // smThai 22: 'x-mac-lao', // smLao 23: 'x-mac-georgian', // smGeorgian 24: 'x-mac-armenian', // smArmenian 25: 'x-mac-chinesesimp', // smSimpChinese 26: 'x-mac-tibetan', // smTibetan 27: 'x-mac-mongolian', // smMongolian 28: 'x-mac-ethiopic', // smEthiopic 29: 'x-mac-ce', // smCentralEuroRoman 30: 'x-mac-vietnamese', // smVietnamese 31: 'x-mac-extarabic' // smExtArabic }; // MacOS language ID → encoding. This table stores the exceptional // cases, which override macScriptEncodings. For writing MacOS naming // tables, we need to emit a MacOS script ID. Therefore, we cannot // merge macScriptEncodings into macLanguageEncodings. // // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt var macLanguageEncodings = { 15: 'x-mac-icelandic', // langIcelandic 17: 'x-mac-turkish', // langTurkish 18: 'x-mac-croatian', // langCroatian 24: 'x-mac-ce', // langLithuanian 25: 'x-mac-ce', // langPolish 26: 'x-mac-ce', // langHungarian 27: 'x-mac-ce', // langEstonian 28: 'x-mac-ce', // langLatvian 30: 'x-mac-icelandic', // langFaroese 37: 'x-mac-romanian', // langRomanian 38: 'x-mac-ce', // langCzech 39: 'x-mac-ce', // langSlovak 40: 'x-mac-ce', // langSlovenian 143: 'x-mac-inuit', // langInuktitut 146: 'x-mac-gaelic' // langIrishGaelicScript }; function getEncoding(platformID, encodingID, languageID) { switch (platformID) { case 0: // Unicode return utf16; case 1: // Apple Macintosh return macLanguageEncodings[languageID] || macScriptEncodings[encodingID]; case 3: // Microsoft Windows if (encodingID === 1 || encodingID === 10) { return utf16; } break; } return undefined; } // Parse the naming `name` table. // FIXME: Format 1 additional fields are not supported yet. // ltag is the content of the `ltag' table, such as ['en', 'zh-Hans', 'de-CH-1904']. function parseNameTable(data, start, ltag) { var name = {}; var p = new parse.Parser(data, start); var format = p.parseUShort(); var count = p.parseUShort(); var stringOffset = p.offset + p.parseUShort(); for (var i = 0; i < count; i++) { var platformID = p.parseUShort(); var encodingID = p.parseUShort(); var languageID = p.parseUShort(); var nameID = p.parseUShort(); var property = nameTableNames[nameID] || nameID; var byteLength = p.parseUShort(); var offset = p.parseUShort(); var language = getLanguageCode(platformID, languageID, ltag); var encoding = getEncoding(platformID, encodingID, languageID); if (encoding !== undefined && language !== undefined) { var text; if (encoding === utf16) { text = decode.UTF16(data, stringOffset + offset, byteLength); } else { text = decode.MACSTRING(data, stringOffset + offset, byteLength, encoding); } if (text) { var translations = name[property]; if (translations === undefined) { translations = name[property] = {}; } translations[language] = text; } } } var langTagCount = 0; if (format === 1) { // FIXME: Also handle Microsoft's 'name' table 1. langTagCount = p.parseUShort(); } return name; } // {23: 'foo'} → {'foo': 23} // ['bar', 'baz'] → {'bar': 0, 'baz': 1} function reverseDict(dict) { var result = {}; for (var key in dict) { result[dict[key]] = parseInt(key); } return result; } function makeNameRecord(platformID, encodingID, languageID, nameID, length, offset) { return new table.Record('NameRecord', [ {name: 'platformID', type: 'USHORT', value: platformID}, {name: 'encodingID', type: 'USHORT', value: encodingID}, {name: 'languageID', type: 'USHORT', value: languageID}, {name: 'nameID', type: 'USHORT', value: nameID}, {name: 'length', type: 'USHORT', value: length}, {name: 'offset', type: 'USHORT', value: offset} ]); } // Finds the position of needle in haystack, or -1 if not there. // Like String.indexOf(), but for arrays. function findSubArray(needle, haystack) { var needleLength = needle.length; var limit = haystack.length - needleLength + 1; loop: for (var pos = 0; pos < limit; pos++) { for (; pos < limit; pos++) { for (var k = 0; k < needleLength; k++) { if (haystack[pos + k] !== needle[k]) { continue loop; } } return pos; } } return -1; } function addStringToPool(s, pool) { var offset = findSubArray(s, pool); if (offset < 0) { offset = pool.length; for (var i = 0, len = s.length; i < len; ++i) { pool.push(s[i]); } } return offset; } function makeNameTable(names, ltag) { var nameID; var nameIDs = []; var namesWithNumericKeys = {}; var nameTableIds = reverseDict(nameTableNames); for (var key in names) { var id = nameTableIds[key]; if (id === undefined) { id = key; } nameID = parseInt(id); if (isNaN(nameID)) { throw new Error('Name table entry "' + key + '" does not exist, see nameTableNames for complete list.'); } namesWithNumericKeys[nameID] = names[key]; nameIDs.push(nameID); } var macLanguageIds = reverseDict(macLanguages); var windowsLanguageIds = reverseDict(windowsLanguages); var nameRecords = []; var stringPool = []; for (var i = 0; i < nameIDs.length; i++) { nameID = nameIDs[i]; var translations = namesWithNumericKeys[nameID]; for (var lang in translations) { var text = translations[lang]; // For MacOS, we try to emit the name in the form that was introduced // in the initial version of the TrueType spec (in the late 1980s). // However, this can fail for various reasons: the requested BCP 47 // language code might not have an old-style Mac equivalent; // we might not have a codec for the needed character encoding; // or the name might contain characters that cannot be expressed // in the old-style Macintosh encoding. In case of failure, we emit // the name in a more modern fashion (Unicode encoding with BCP 47 // language tags) that is recognized by MacOS 10.5, released in 2009. // If fonts were only read by operating systems, we could simply // emit all names in the modern form; this would be much easier. // However, there are many applications and libraries that read // 'name' tables directly, and these will usually only recognize // the ancient form (silently skipping the unrecognized names). var macPlatform = 1; // Macintosh var macLanguage = macLanguageIds[lang]; var macScript = macLanguageToScript[macLanguage]; var macEncoding = getEncoding(macPlatform, macScript, macLanguage); var macName = encode.MACSTRING(text, macEncoding); if (macName === undefined) { macPlatform = 0; // Unicode macLanguage = ltag.indexOf(lang); if (macLanguage < 0) { macLanguage = ltag.length; ltag.push(lang); } macScript = 4; // Unicode 2.0 and later macName = encode.UTF16(text); } var macNameOffset = addStringToPool(macName, stringPool); nameRecords.push(makeNameRecord(macPlatform, macScript, macLanguage, nameID, macName.length, macNameOffset)); var winLanguage = windowsLanguageIds[lang]; if (winLanguage !== undefined) { var winName = encode.UTF16(text); var winNameOffset = addStringToPool(winName, stringPool); nameRecords.push(makeNameRecord(3, 1, winLanguage, nameID, winName.length, winNameOffset)); } } } nameRecords.sort(function(a, b) { return ((a.platformID - b.platformID) || (a.encodingID - b.encodingID) || (a.languageID - b.languageID) || (a.nameID - b.nameID)); }); var t = new table.Table('name', [ {name: 'format', type: 'USHORT', value: 0}, {name: 'count', type: 'USHORT', value: nameRecords.length}, {name: 'stringOffset', type: 'USHORT', value: 6 + nameRecords.length * 12} ]); for (var r = 0; r < nameRecords.length; r++) { t.fields.push({name: 'record_' + r, type: 'RECORD', value: nameRecords[r]}); } t.fields.push({name: 'strings', type: 'LITERAL', value: stringPool}); return t; } exports.parse = parseNameTable; exports.make = makeNameTable; },{"../parse":16,"../table":19,"../types":38}],35:[function(_dereq_,module,exports){ // The `OS/2` table contains metrics required in OpenType fonts. // https://www.microsoft.com/typography/OTSPEC/os2.htm 'use strict'; var parse = _dereq_('../parse'); var table = _dereq_('../table'); var unicodeRanges = [ {begin: 0x0000, end: 0x007F}, // Basic Latin {begin: 0x0080, end: 0x00FF}, // Latin-1 Supplement {begin: 0x0100, end: 0x017F}, // Latin Extended-A {begin: 0x0180, end: 0x024F}, // Latin Extended-B {begin: 0x0250, end: 0x02AF}, // IPA Extensions {begin: 0x02B0, end: 0x02FF}, // Spacing Modifier Letters {begin: 0x0300, end: 0x036F}, // Combining Diacritical Marks {begin: 0x0370, end: 0x03FF}, // Greek and Coptic {begin: 0x2C80, end: 0x2CFF}, // Coptic {begin: 0x0400, end: 0x04FF}, // Cyrillic {begin: 0x0530, end: 0x058F}, // Armenian {begin: 0x0590, end: 0x05FF}, // Hebrew {begin: 0xA500, end: 0xA63F}, // Vai {begin: 0x0600, end: 0x06FF}, // Arabic {begin: 0x07C0, end: 0x07FF}, // NKo {begin: 0x0900, end: 0x097F}, // Devanagari {begin: 0x0980, end: 0x09FF}, // Bengali {begin: 0x0A00, end: 0x0A7F}, // Gurmukhi {begin: 0x0A80, end: 0x0AFF}, // Gujarati {begin: 0x0B00, end: 0x0B7F}, // Oriya {begin: 0x0B80, end: 0x0BFF}, // Tamil {begin: 0x0C00, end: 0x0C7F}, // Telugu {begin: 0x0C80, end: 0x0CFF}, // Kannada {begin: 0x0D00, end: 0x0D7F}, // Malayalam {begin: 0x0E00, end: 0x0E7F}, // Thai {begin: 0x0E80, end: 0x0EFF}, // Lao {begin: 0x10A0, end: 0x10FF}, // Georgian {begin: 0x1B00, end: 0x1B7F}, // Balinese {begin: 0x1100, end: 0x11FF}, // Hangul Jamo {begin: 0x1E00, end: 0x1EFF}, // Latin Extended Additional {begin: 0x1F00, end: 0x1FFF}, // Greek Extended {begin: 0x2000, end: 0x206F}, // General Punctuation {begin: 0x2070, end: 0x209F}, // Superscripts And Subscripts {begin: 0x20A0, end: 0x20CF}, // Currency Symbol {begin: 0x20D0, end: 0x20FF}, // Combining Diacritical Marks For Symbols {begin: 0x2100, end: 0x214F}, // Letterlike Symbols {begin: 0x2150, end: 0x218F}, // Number Forms {begin: 0x2190, end: 0x21FF}, // Arrows {begin: 0x2200, end: 0x22FF}, // Mathematical Operators {begin: 0x2300, end: 0x23FF}, // Miscellaneous Technical {begin: 0x2400, end: 0x243F}, // Control Pictures {begin: 0x2440, end: 0x245F}, // Optical Character Recognition {begin: 0x2460, end: 0x24FF}, // Enclosed Alphanumerics {begin: 0x2500, end: 0x257F}, // Box Drawing {begin: 0x2580, end: 0x259F}, // Block Elements {begin: 0x25A0, end: 0x25FF}, // Geometric Shapes {begin: 0x2600, end: 0x26FF}, // Miscellaneous Symbols {begin: 0x2700, end: 0x27BF}, // Dingbats {begin: 0x3000, end: 0x303F}, // CJK Symbols And Punctuation {begin: 0x3040, end: 0x309F}, // Hiragana {begin: 0x30A0, end: 0x30FF}, // Katakana {begin: 0x3100, end: 0x312F}, // Bopomofo {begin: 0x3130, end: 0x318F}, // Hangul Compatibility Jamo {begin: 0xA840, end: 0xA87F}, // Phags-pa {begin: 0x3200, end: 0x32FF}, // Enclosed CJK Letters And Months {begin: 0x3300, end: 0x33FF}, // CJK Compatibility {begin: 0xAC00, end: 0xD7AF}, // Hangul Syllables {begin: 0xD800, end: 0xDFFF}, // Non-Plane 0 * {begin: 0x10900, end: 0x1091F}, // Phoenicia {begin: 0x4E00, end: 0x9FFF}, // CJK Unified Ideographs {begin: 0xE000, end: 0xF8FF}, // Private Use Area (plane 0) {begin: 0x31C0, end: 0x31EF}, // CJK Strokes {begin: 0xFB00, end: 0xFB4F}, // Alphabetic Presentation Forms {begin: 0xFB50, end: 0xFDFF}, // Arabic Presentation Forms-A {begin: 0xFE20, end: 0xFE2F}, // Combining Half Marks {begin: 0xFE10, end: 0xFE1F}, // Vertical Forms {begin: 0xFE50, end: 0xFE6F}, // Small Form Variants {begin: 0xFE70, end: 0xFEFF}, // Arabic Presentation Forms-B {begin: 0xFF00, end: 0xFFEF}, // Halfwidth And Fullwidth Forms {begin: 0xFFF0, end: 0xFFFF}, // Specials {begin: 0x0F00, end: 0x0FFF}, // Tibetan {begin: 0x0700, end: 0x074F}, // Syriac {begin: 0x0780, end: 0x07BF}, // Thaana {begin: 0x0D80, end: 0x0DFF}, // Sinhala {begin: 0x1000, end: 0x109F}, // Myanmar {begin: 0x1200, end: 0x137F}, // Ethiopic {begin: 0x13A0, end: 0x13FF}, // Cherokee {begin: 0x1400, end: 0x167F}, // Unified Canadian Aboriginal Syllabics {begin: 0x1680, end: 0x169F}, // Ogham {begin: 0x16A0, end: 0x16FF}, // Runic {begin: 0x1780, end: 0x17FF}, // Khmer {begin: 0x1800, end: 0x18AF}, // Mongolian {begin: 0x2800, end: 0x28FF}, // Braille Patterns {begin: 0xA000, end: 0xA48F}, // Yi Syllables {begin: 0x1700, end: 0x171F}, // Tagalog {begin: 0x10300, end: 0x1032F}, // Old Italic {begin: 0x10330, end: 0x1034F}, // Gothic {begin: 0x10400, end: 0x1044F}, // Deseret {begin: 0x1D000, end: 0x1D0FF}, // Byzantine Musical Symbols {begin: 0x1D400, end: 0x1D7FF}, // Mathematical Alphanumeric Symbols {begin: 0xFF000, end: 0xFFFFD}, // Private Use (plane 15) {begin: 0xFE00, end: 0xFE0F}, // Variation Selectors {begin: 0xE0000, end: 0xE007F}, // Tags {begin: 0x1900, end: 0x194F}, // Limbu {begin: 0x1950, end: 0x197F}, // Tai Le {begin: 0x1980, end: 0x19DF}, // New Tai Lue {begin: 0x1A00, end: 0x1A1F}, // Buginese {begin: 0x2C00, end: 0x2C5F}, // Glagolitic {begin: 0x2D30, end: 0x2D7F}, // Tifinagh {begin: 0x4DC0, end: 0x4DFF}, // Yijing Hexagram Symbols {begin: 0xA800, end: 0xA82F}, // Syloti Nagri {begin: 0x10000, end: 0x1007F}, // Linear B Syllabary {begin: 0x10140, end: 0x1018F}, // Ancient Greek Numbers {begin: 0x10380, end: 0x1039F}, // Ugaritic {begin: 0x103A0, end: 0x103DF}, // Old Persian {begin: 0x10450, end: 0x1047F}, // Shavian {begin: 0x10480, end: 0x104AF}, // Osmanya {begin: 0x10800, end: 0x1083F}, // Cypriot Syllabary {begin: 0x10A00, end: 0x10A5F}, // Kharoshthi {begin: 0x1D300, end: 0x1D35F}, // Tai Xuan Jing Symbols {begin: 0x12000, end: 0x123FF}, // Cuneiform {begin: 0x1D360, end: 0x1D37F}, // Counting Rod Numerals {begin: 0x1B80, end: 0x1BBF}, // Sundanese {begin: 0x1C00, end: 0x1C4F}, // Lepcha {begin: 0x1C50, end: 0x1C7F}, // Ol Chiki {begin: 0xA880, end: 0xA8DF}, // Saurashtra {begin: 0xA900, end: 0xA92F}, // Kayah Li {begin: 0xA930, end: 0xA95F}, // Rejang {begin: 0xAA00, end: 0xAA5F}, // Cham {begin: 0x10190, end: 0x101CF}, // Ancient Symbols {begin: 0x101D0, end: 0x101FF}, // Phaistos Disc {begin: 0x102A0, end: 0x102DF}, // Carian {begin: 0x1F030, end: 0x1F09F} // Domino Tiles ]; function getUnicodeRange(unicode) { for (var i = 0; i < unicodeRanges.length; i += 1) { var range = unicodeRanges[i]; if (unicode >= range.begin && unicode < range.end) { return i; } } return -1; } // Parse the OS/2 and Windows metrics `OS/2` table function parseOS2Table(data, start) { var os2 = {}; var p = new parse.Parser(data, start); os2.version = p.parseUShort(); os2.xAvgCharWidth = p.parseShort(); os2.usWeightClass = p.parseUShort(); os2.usWidthClass = p.parseUShort(); os2.fsType = p.parseUShort(); os2.ySubscriptXSize = p.parseShort(); os2.ySubscriptYSize = p.parseShort(); os2.ySubscriptXOffset = p.parseShort(); os2.ySubscriptYOffset = p.parseShort(); os2.ySuperscriptXSize = p.parseShort(); os2.ySuperscriptYSize = p.parseShort(); os2.ySuperscriptXOffset = p.parseShort(); os2.ySuperscriptYOffset = p.parseShort(); os2.yStrikeoutSize = p.parseShort(); os2.yStrikeoutPosition = p.parseShort(); os2.sFamilyClass = p.parseShort(); os2.panose = []; for (var i = 0; i < 10; i++) { os2.panose[i] = p.parseByte(); } os2.ulUnicodeRange1 = p.parseULong(); os2.ulUnicodeRange2 = p.parseULong(); os2.ulUnicodeRange3 = p.parseULong(); os2.ulUnicodeRange4 = p.parseULong(); os2.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte()); os2.fsSelection = p.parseUShort(); os2.usFirstCharIndex = p.parseUShort(); os2.usLastCharIndex = p.parseUShort(); os2.sTypoAscender = p.parseShort(); os2.sTypoDescender = p.parseShort(); os2.sTypoLineGap = p.parseShort(); os2.usWinAscent = p.parseUShort(); os2.usWinDescent = p.parseUShort(); if (os2.version >= 1) { os2.ulCodePageRange1 = p.parseULong(); os2.ulCodePageRange2 = p.parseULong(); } if (os2.version >= 2) { os2.sxHeight = p.parseShort(); os2.sCapHeight = p.parseShort(); os2.usDefaultChar = p.parseUShort(); os2.usBreakChar = p.parseUShort(); os2.usMaxContent = p.parseUShort(); } return os2; } function makeOS2Table(options) { return new table.Table('OS/2', [ {name: 'version', type: 'USHORT', value: 0x0003}, {name: 'xAvgCharWidth', type: 'SHORT', value: 0}, {name: 'usWeightClass', type: 'USHORT', value: 0}, {name: 'usWidthClass', type: 'USHORT', value: 0}, {name: 'fsType', type: 'USHORT', value: 0}, {name: 'ySubscriptXSize', type: 'SHORT', value: 650}, {name: 'ySubscriptYSize', type: 'SHORT', value: 699}, {name: 'ySubscriptXOffset', type: 'SHORT', value: 0}, {name: 'ySubscriptYOffset', type: 'SHORT', value: 140}, {name: 'ySuperscriptXSize', type: 'SHORT', value: 650}, {name: 'ySuperscriptYSize', type: 'SHORT', value: 699}, {name: 'ySuperscriptXOffset', type: 'SHORT', value: 0}, {name: 'ySuperscriptYOffset', type: 'SHORT', value: 479}, {name: 'yStrikeoutSize', type: 'SHORT', value: 49}, {name: 'yStrikeoutPosition', type: 'SHORT', value: 258}, {name: 'sFamilyClass', type: 'SHORT', value: 0}, {name: 'bFamilyType', type: 'BYTE', value: 0}, {name: 'bSerifStyle', type: 'BYTE', value: 0}, {name: 'bWeight', type: 'BYTE', value: 0}, {name: 'bProportion', type: 'BYTE', value: 0}, {name: 'bContrast', type: 'BYTE', value: 0}, {name: 'bStrokeVariation', type: 'BYTE', value: 0}, {name: 'bArmStyle', type: 'BYTE', value: 0}, {name: 'bLetterform', type: 'BYTE', value: 0}, {name: 'bMidline', type: 'BYTE', value: 0}, {name: 'bXHeight', type: 'BYTE', value: 0}, {name: 'ulUnicodeRange1', type: 'ULONG', value: 0}, {name: 'ulUnicodeRange2', type: 'ULONG', value: 0}, {name: 'ulUnicodeRange3', type: 'ULONG', value: 0}, {name: 'ulUnicodeRange4', type: 'ULONG', value: 0}, {name: 'achVendID', type: 'CHARARRAY', value: 'XXXX'}, {name: 'fsSelection', type: 'USHORT', value: 0}, {name: 'usFirstCharIndex', type: 'USHORT', value: 0}, {name: 'usLastCharIndex', type: 'USHORT', value: 0}, {name: 'sTypoAscender', type: 'SHORT', value: 0}, {name: 'sTypoDescender', type: 'SHORT', value: 0}, {name: 'sTypoLineGap', type: 'SHORT', value: 0}, {name: 'usWinAscent', type: 'USHORT', value: 0}, {name: 'usWinDescent', type: 'USHORT', value: 0}, {name: 'ulCodePageRange1', type: 'ULONG', value: 0}, {name: 'ulCodePageRange2', type: 'ULONG', value: 0}, {name: 'sxHeight', type: 'SHORT', value: 0}, {name: 'sCapHeight', type: 'SHORT', value: 0}, {name: 'usDefaultChar', type: 'USHORT', value: 0}, {name: 'usBreakChar', type: 'USHORT', value: 0}, {name: 'usMaxContext', type: 'USHORT', value: 0} ], options); } exports.unicodeRanges = unicodeRanges; exports.getUnicodeRange = getUnicodeRange; exports.parse = parseOS2Table; exports.make = makeOS2Table; },{"../parse":16,"../table":19}],36:[function(_dereq_,module,exports){ // The `post` table stores additional PostScript information, such as glyph names. // https://www.microsoft.com/typography/OTSPEC/post.htm 'use strict'; var encoding = _dereq_('../encoding'); var parse = _dereq_('../parse'); var table = _dereq_('../table'); // Parse the PostScript `post` table function parsePostTable(data, start) { var post = {}; var p = new parse.Parser(data, start); var i; post.version = p.parseVersion(); post.italicAngle = p.parseFixed(); post.underlinePosition = p.parseShort(); post.underlineThickness = p.parseShort(); post.isFixedPitch = p.parseULong(); post.minMemType42 = p.parseULong(); post.maxMemType42 = p.parseULong(); post.minMemType1 = p.parseULong(); post.maxMemType1 = p.parseULong(); switch (post.version) { case 1: post.names = encoding.standardNames.slice(); break; case 2: post.numberOfGlyphs = p.parseUShort(); post.glyphNameIndex = new Array(post.numberOfGlyphs); for (i = 0; i < post.numberOfGlyphs; i++) { post.glyphNameIndex[i] = p.parseUShort(); } post.names = []; for (i = 0; i < post.numberOfGlyphs; i++) { if (post.glyphNameIndex[i] >= encoding.standardNames.length) { var nameLength = p.parseChar(); post.names.push(p.parseString(nameLength)); } } break; case 2.5: post.numberOfGlyphs = p.parseUShort(); post.offset = new Array(post.numberOfGlyphs); for (i = 0; i < post.numberOfGlyphs; i++) { post.offset[i] = p.parseChar(); } break; } return post; } function makePostTable() { return new table.Table('post', [ {name: 'version', type: 'FIXED', value: 0x00030000}, {name: 'italicAngle', type: 'FIXED', value: 0}, {name: 'underlinePosition', type: 'FWORD', value: 0}, {name: 'underlineThickness', type: 'FWORD', value: 0}, {name: 'isFixedPitch', type: 'ULONG', value: 0}, {name: 'minMemType42', type: 'ULONG', value: 0}, {name: 'maxMemType42', type: 'ULONG', value: 0}, {name: 'minMemType1', type: 'ULONG', value: 0}, {name: 'maxMemType1', type: 'ULONG', value: 0} ]); } exports.parse = parsePostTable; exports.make = makePostTable; },{"../encoding":9,"../parse":16,"../table":19}],37:[function(_dereq_,module,exports){ // The `sfnt` wrapper provides organization for the tables in the font. // It is the top-level data structure in a font. // https://www.microsoft.com/typography/OTSPEC/otff.htm // Recommendations for creating OpenType Fonts: // http://www.microsoft.com/typography/otspec140/recom.htm 'use strict'; var check = _dereq_('../check'); var table = _dereq_('../table'); var cmap = _dereq_('./cmap'); var cff = _dereq_('./cff'); var head = _dereq_('./head'); var hhea = _dereq_('./hhea'); var hmtx = _dereq_('./hmtx'); var ltag = _dereq_('./ltag'); var maxp = _dereq_('./maxp'); var _name = _dereq_('./name'); var os2 = _dereq_('./os2'); var post = _dereq_('./post'); var gsub = _dereq_('./gsub'); var meta = _dereq_('./meta'); function log2(v) { return Math.log(v) / Math.log(2) | 0; } function computeCheckSum(bytes) { while (bytes.length % 4 !== 0) { bytes.push(0); } var sum = 0; for (var i = 0; i < bytes.length; i += 4) { sum += (bytes[i] << 24) + (bytes[i + 1] << 16) + (bytes[i + 2] << 8) + (bytes[i + 3]); } sum %= Math.pow(2, 32); return sum; } function makeTableRecord(tag, checkSum, offset, length) { return new table.Record('Table Record', [ {name: 'tag', type: 'TAG', value: tag !== undefined ? tag : ''}, {name: 'checkSum', type: 'ULONG', value: checkSum !== undefined ? checkSum : 0}, {name: 'offset', type: 'ULONG', value: offset !== undefined ? offset : 0}, {name: 'length', type: 'ULONG', value: length !== undefined ? length : 0} ]); } function makeSfntTable(tables) { var sfnt = new table.Table('sfnt', [ {name: 'version', type: 'TAG', value: 'OTTO'}, {name: 'numTables', type: 'USHORT', value: 0}, {name: 'searchRange', type: 'USHORT', value: 0}, {name: 'entrySelector', type: 'USHORT', value: 0}, {name: 'rangeShift', type: 'USHORT', value: 0} ]); sfnt.tables = tables; sfnt.numTables = tables.length; var highestPowerOf2 = Math.pow(2, log2(sfnt.numTables)); sfnt.searchRange = 16 * highestPowerOf2; sfnt.entrySelector = log2(highestPowerOf2); sfnt.rangeShift = sfnt.numTables * 16 - sfnt.searchRange; var recordFields = []; var tableFields = []; var offset = sfnt.sizeOf() + (makeTableRecord().sizeOf() * sfnt.numTables); while (offset % 4 !== 0) { offset += 1; tableFields.push({name: 'padding', type: 'BYTE', value: 0}); } for (var i = 0; i < tables.length; i += 1) { var t = tables[i]; check.argument(t.tableName.length === 4, 'Table name' + t.tableName + ' is invalid.'); var tableLength = t.sizeOf(); var tableRecord = makeTableRecord(t.tableName, computeCheckSum(t.encode()), offset, tableLength); recordFields.push({name: tableRecord.tag + ' Table Record', type: 'RECORD', value: tableRecord}); tableFields.push({name: t.tableName + ' table', type: 'RECORD', value: t}); offset += tableLength; check.argument(!isNaN(offset), 'Something went wrong calculating the offset.'); while (offset % 4 !== 0) { offset += 1; tableFields.push({name: 'padding', type: 'BYTE', value: 0}); } } // Table records need to be sorted alphabetically. recordFields.sort(function(r1, r2) { if (r1.value.tag > r2.value.tag) { return 1; } else { return -1; } }); sfnt.fields = sfnt.fields.concat(recordFields); sfnt.fields = sfnt.fields.concat(tableFields); return sfnt; } // Get the metrics for a character. If the string has more than one character // this function returns metrics for the first available character. // You can provide optional fallback metrics if no characters are available. function metricsForChar(font, chars, notFoundMetrics) { for (var i = 0; i < chars.length; i += 1) { var glyphIndex = font.charToGlyphIndex(chars[i]); if (glyphIndex > 0) { var glyph = font.glyphs.get(glyphIndex); return glyph.getMetrics(); } } return notFoundMetrics; } function average(vs) { var sum = 0; for (var i = 0; i < vs.length; i += 1) { sum += vs[i]; } return sum / vs.length; } // Convert the font object to a SFNT data structure. // This structure contains all the necessary tables and metadata to create a binary OTF file. function fontToSfntTable(font) { var xMins = []; var yMins = []; var xMaxs = []; var yMaxs = []; var advanceWidths = []; var leftSideBearings = []; var rightSideBearings = []; var firstCharIndex; var lastCharIndex = 0; var ulUnicodeRange1 = 0; var ulUnicodeRange2 = 0; var ulUnicodeRange3 = 0; var ulUnicodeRange4 = 0; for (var i = 0; i < font.glyphs.length; i += 1) { var glyph = font.glyphs.get(i); var unicode = glyph.unicode | 0; if (isNaN(glyph.advanceWidth)) { throw new Error('Glyph ' + glyph.name + ' (' + i + '): advanceWidth is not a number.'); } if (firstCharIndex > unicode || firstCharIndex === undefined) { // ignore .notdef char if (unicode > 0) { firstCharIndex = unicode; } } if (lastCharIndex < unicode) { lastCharIndex = unicode; } var position = os2.getUnicodeRange(unicode); if (position < 32) { ulUnicodeRange1 |= 1 << position; } else if (position < 64) { ulUnicodeRange2 |= 1 << position - 32; } else if (position < 96) { ulUnicodeRange3 |= 1 << position - 64; } else if (position < 123) { ulUnicodeRange4 |= 1 << position - 96; } else { throw new Error('Unicode ranges bits > 123 are reserved for internal usage'); } // Skip non-important characters. if (glyph.name === '.notdef') continue; var metrics = glyph.getMetrics(); xMins.push(metrics.xMin); yMins.push(metrics.yMin); xMaxs.push(metrics.xMax); yMaxs.push(metrics.yMax); leftSideBearings.push(metrics.leftSideBearing); rightSideBearings.push(metrics.rightSideBearing); advanceWidths.push(glyph.advanceWidth); } var globals = { xMin: Math.min.apply(null, xMins), yMin: Math.min.apply(null, yMins), xMax: Math.max.apply(null, xMaxs), yMax: Math.max.apply(null, yMaxs), advanceWidthMax: Math.max.apply(null, advanceWidths), advanceWidthAvg: average(advanceWidths), minLeftSideBearing: Math.min.apply(null, leftSideBearings), maxLeftSideBearing: Math.max.apply(null, leftSideBearings), minRightSideBearing: Math.min.apply(null, rightSideBearings) }; globals.ascender = font.ascender; globals.descender = font.descender; var headTable = head.make({ flags: 3, // 00000011 (baseline for font at y=0; left sidebearing point at x=0) unitsPerEm: font.unitsPerEm, xMin: globals.xMin, yMin: globals.yMin, xMax: globals.xMax, yMax: globals.yMax, lowestRecPPEM: 3, createdTimestamp: font.createdTimestamp }); var hheaTable = hhea.make({ ascender: globals.ascender, descender: globals.descender, advanceWidthMax: globals.advanceWidthMax, minLeftSideBearing: globals.minLeftSideBearing, minRightSideBearing: globals.minRightSideBearing, xMaxExtent: globals.maxLeftSideBearing + (globals.xMax - globals.xMin), numberOfHMetrics: font.glyphs.length }); var maxpTable = maxp.make(font.glyphs.length); var os2Table = os2.make({ xAvgCharWidth: Math.round(globals.advanceWidthAvg), usWeightClass: font.tables.os2.usWeightClass, usWidthClass: font.tables.os2.usWidthClass, usFirstCharIndex: firstCharIndex, usLastCharIndex: lastCharIndex, ulUnicodeRange1: ulUnicodeRange1, ulUnicodeRange2: ulUnicodeRange2, ulUnicodeRange3: ulUnicodeRange3, ulUnicodeRange4: ulUnicodeRange4, fsSelection: font.tables.os2.fsSelection, // REGULAR // See http://typophile.com/node/13081 for more info on vertical metrics. // We get metrics for typical characters (such as "x" for xHeight). // We provide some fallback characters if characters are unavailable: their // ordering was chosen experimentally. sTypoAscender: globals.ascender, sTypoDescender: globals.descender, sTypoLineGap: 0, usWinAscent: globals.yMax, usWinDescent: Math.abs(globals.yMin), ulCodePageRange1: 1, // FIXME: hard-code Latin 1 support for now sxHeight: metricsForChar(font, 'xyvw', {yMax: Math.round(globals.ascender / 2)}).yMax, sCapHeight: metricsForChar(font, 'HIKLEFJMNTZBDPRAGOQSUVWXY', globals).yMax, usDefaultChar: font.hasChar(' ') ? 32 : 0, // Use space as the default character, if available. usBreakChar: font.hasChar(' ') ? 32 : 0 // Use space as the break character, if available. }); var hmtxTable = hmtx.make(font.glyphs); var cmapTable = cmap.make(font.glyphs); var englishFamilyName = font.getEnglishName('fontFamily'); var englishStyleName = font.getEnglishName('fontSubfamily'); var englishFullName = englishFamilyName + ' ' + englishStyleName; var postScriptName = font.getEnglishName('postScriptName'); if (!postScriptName) { postScriptName = englishFamilyName.replace(/\s/g, '') + '-' + englishStyleName; } var names = {}; for (var n in font.names) { names[n] = font.names[n]; } if (!names.uniqueID) { names.uniqueID = {en: font.getEnglishName('manufacturer') + ':' + englishFullName}; } if (!names.postScriptName) { names.postScriptName = {en: postScriptName}; } if (!names.preferredFamily) { names.preferredFamily = font.names.fontFamily; } if (!names.preferredSubfamily) { names.preferredSubfamily = font.names.fontSubfamily; } var languageTags = []; var nameTable = _name.make(names, languageTags); var ltagTable = (languageTags.length > 0 ? ltag.make(languageTags) : undefined); var postTable = post.make(); var cffTable = cff.make(font.glyphs, { version: font.getEnglishName('version'), fullName: englishFullName, familyName: englishFamilyName, weightName: englishStyleName, postScriptName: postScriptName, unitsPerEm: font.unitsPerEm, fontBBox: [0, globals.yMin, globals.ascender, globals.advanceWidthMax] }); var metaTable = (font.metas && Object.keys(font.metas).length > 0) ? meta.make(font.metas) : undefined; // The order does not matter because makeSfntTable() will sort them. var tables = [headTable, hheaTable, maxpTable, os2Table, nameTable, cmapTable, postTable, cffTable, hmtxTable]; if (ltagTable) { tables.push(ltagTable); } // Optional tables if (font.tables.gsub) { tables.push(gsub.make(font.tables.gsub)); } if (metaTable) { tables.push(metaTable); } var sfntTable = makeSfntTable(tables); // Compute the font's checkSum and store it in head.checkSumAdjustment. var bytes = sfntTable.encode(); var checkSum = computeCheckSum(bytes); var tableFields = sfntTable.fields; var checkSumAdjusted = false; for (i = 0; i < tableFields.length; i += 1) { if (tableFields[i].name === 'head table') { tableFields[i].value.checkSumAdjustment = 0xB1B0AFBA - checkSum; checkSumAdjusted = true; break; } } if (!checkSumAdjusted) { throw new Error('Could not find head table with checkSum to adjust.'); } return sfntTable; } exports.computeCheckSum = computeCheckSum; exports.make = makeSfntTable; exports.fontToTable = fontToSfntTable; },{"../check":7,"../table":19,"./cff":20,"./cmap":21,"./gsub":25,"./head":26,"./hhea":27,"./hmtx":28,"./ltag":31,"./maxp":32,"./meta":33,"./name":34,"./os2":35,"./post":36}],38:[function(_dereq_,module,exports){ // Data types used in the OpenType font file. // All OpenType fonts use Motorola-style byte ordering (Big Endian) /* global WeakMap */ 'use strict'; var check = _dereq_('./check'); var LIMIT16 = 32768; // The limit at which a 16-bit number switches signs == 2^15 var LIMIT32 = 2147483648; // The limit at which a 32-bit number switches signs == 2 ^ 31 /** * @exports opentype.decode * @class */ var decode = {}; /** * @exports opentype.encode * @class */ var encode = {}; /** * @exports opentype.sizeOf * @class */ var sizeOf = {}; // Return a function that always returns the same value. function constant(v) { return function() { return v; }; } // OpenType data types ////////////////////////////////////////////////////// /** * Convert an 8-bit unsigned integer to a list of 1 byte. * @param {number} * @returns {Array} */ encode.BYTE = function(v) { check.argument(v >= 0 && v <= 255, 'Byte value should be between 0 and 255.'); return [v]; }; /** * @constant * @type {number} */ sizeOf.BYTE = constant(1); /** * Convert a 8-bit signed integer to a list of 1 byte. * @param {string} * @returns {Array} */ encode.CHAR = function(v) { return [v.charCodeAt(0)]; }; /** * @constant * @type {number} */ sizeOf.CHAR = constant(1); /** * Convert an ASCII string to a list of bytes. * @param {string} * @returns {Array} */ encode.CHARARRAY = function(v) { var b = []; for (var i = 0; i < v.length; i += 1) { b[i] = v.charCodeAt(i); } return b; }; /** * @param {Array} * @returns {number} */ sizeOf.CHARARRAY = function(v) { return v.length; }; /** * Convert a 16-bit unsigned integer to a list of 2 bytes. * @param {number} * @returns {Array} */ encode.USHORT = function(v) { return [(v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.USHORT = constant(2); /** * Convert a 16-bit signed integer to a list of 2 bytes. * @param {number} * @returns {Array} */ encode.SHORT = function(v) { // Two's complement if (v >= LIMIT16) { v = -(2 * LIMIT16 - v); } return [(v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.SHORT = constant(2); /** * Convert a 24-bit unsigned integer to a list of 3 bytes. * @param {number} * @returns {Array} */ encode.UINT24 = function(v) { return [(v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.UINT24 = constant(3); /** * Convert a 32-bit unsigned integer to a list of 4 bytes. * @param {number} * @returns {Array} */ encode.ULONG = function(v) { return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.ULONG = constant(4); /** * Convert a 32-bit unsigned integer to a list of 4 bytes. * @param {number} * @returns {Array} */ encode.LONG = function(v) { // Two's complement if (v >= LIMIT32) { v = -(2 * LIMIT32 - v); } return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.LONG = constant(4); encode.FIXED = encode.ULONG; sizeOf.FIXED = sizeOf.ULONG; encode.FWORD = encode.SHORT; sizeOf.FWORD = sizeOf.SHORT; encode.UFWORD = encode.USHORT; sizeOf.UFWORD = sizeOf.USHORT; /** * Convert a 32-bit Apple Mac timestamp integer to a list of 8 bytes, 64-bit timestamp. * @param {number} * @returns {Array} */ encode.LONGDATETIME = function(v) { return [0, 0, 0, 0, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.LONGDATETIME = constant(8); /** * Convert a 4-char tag to a list of 4 bytes. * @param {string} * @returns {Array} */ encode.TAG = function(v) { check.argument(v.length === 4, 'Tag should be exactly 4 ASCII characters.'); return [v.charCodeAt(0), v.charCodeAt(1), v.charCodeAt(2), v.charCodeAt(3)]; }; /** * @constant * @type {number} */ sizeOf.TAG = constant(4); // CFF data types /////////////////////////////////////////////////////////// encode.Card8 = encode.BYTE; sizeOf.Card8 = sizeOf.BYTE; encode.Card16 = encode.USHORT; sizeOf.Card16 = sizeOf.USHORT; encode.OffSize = encode.BYTE; sizeOf.OffSize = sizeOf.BYTE; encode.SID = encode.USHORT; sizeOf.SID = sizeOf.USHORT; // Convert a numeric operand or charstring number to a variable-size list of bytes. /** * Convert a numeric operand or charstring number to a variable-size list of bytes. * @param {number} * @returns {Array} */ encode.NUMBER = function(v) { if (v >= -107 && v <= 107) { return [v + 139]; } else if (v >= 108 && v <= 1131) { v = v - 108; return [(v >> 8) + 247, v & 0xFF]; } else if (v >= -1131 && v <= -108) { v = -v - 108; return [(v >> 8) + 251, v & 0xFF]; } else if (v >= -32768 && v <= 32767) { return encode.NUMBER16(v); } else { return encode.NUMBER32(v); } }; /** * @param {number} * @returns {number} */ sizeOf.NUMBER = function(v) { return encode.NUMBER(v).length; }; /** * Convert a signed number between -32768 and +32767 to a three-byte value. * This ensures we always use three bytes, but is not the most compact format. * @param {number} * @returns {Array} */ encode.NUMBER16 = function(v) { return [28, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.NUMBER16 = constant(3); /** * Convert a signed number between -(2^31) and +(2^31-1) to a five-byte value. * This is useful if you want to be sure you always use four bytes, * at the expense of wasting a few bytes for smaller numbers. * @param {number} * @returns {Array} */ encode.NUMBER32 = function(v) { return [29, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF]; }; /** * @constant * @type {number} */ sizeOf.NUMBER32 = constant(5); /** * @param {number} * @returns {Array} */ encode.REAL = function(v) { var value = v.toString(); // Some numbers use an epsilon to encode the value. (e.g. JavaScript will store 0.0000001 as 1e-7) // This code converts it back to a number without the epsilon. var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value); if (m) { var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length)); value = (Math.round(v * epsilon) / epsilon).toString(); } var nibbles = ''; var i; var ii; for (i = 0, ii = value.length; i < ii; i += 1) { var c = value[i]; if (c === 'e') { nibbles += value[++i] === '-' ? 'c' : 'b'; } else if (c === '.') { nibbles += 'a'; } else if (c === '-') { nibbles += 'e'; } else { nibbles += c; } } nibbles += (nibbles.length & 1) ? 'f' : 'ff'; var out = [30]; for (i = 0, ii = nibbles.length; i < ii; i += 2) { out.push(parseInt(nibbles.substr(i, 2), 16)); } return out; }; /** * @param {number} * @returns {number} */ sizeOf.REAL = function(v) { return encode.REAL(v).length; }; encode.NAME = encode.CHARARRAY; sizeOf.NAME = sizeOf.CHARARRAY; encode.STRING = encode.CHARARRAY; sizeOf.STRING = sizeOf.CHARARRAY; /** * @param {DataView} data * @param {number} offset * @param {number} numBytes * @returns {string} */ decode.UTF8 = function(data, offset, numBytes) { var codePoints = []; var numChars = numBytes; for (var j = 0; j < numChars; j++, offset += 1) { codePoints[j] = data.getUint8(offset); } return String.fromCharCode.apply(null, codePoints); }; /** * @param {DataView} data * @param {number} offset * @param {number} numBytes * @returns {string} */ decode.UTF16 = function(data, offset, numBytes) { var codePoints = []; var numChars = numBytes / 2; for (var j = 0; j < numChars; j++, offset += 2) { codePoints[j] = data.getUint16(offset); } return String.fromCharCode.apply(null, codePoints); }; /** * Convert a JavaScript string to UTF16-BE. * @param {string} * @returns {Array} */ encode.UTF16 = function(v) { var b = []; for (var i = 0; i < v.length; i += 1) { var codepoint = v.charCodeAt(i); b[b.length] = (codepoint >> 8) & 0xFF; b[b.length] = codepoint & 0xFF; } return b; }; /** * @param {string} * @returns {number} */ sizeOf.UTF16 = function(v) { return v.length * 2; }; // Data for converting old eight-bit Macintosh encodings to Unicode. // This representation is optimized for decoding; encoding is slower // and needs more memory. The assumption is that all opentype.js users // want to open fonts, but saving a font will be comperatively rare // so it can be more expensive. Keyed by IANA character set name. // // Python script for generating these strings: // // s = u''.join([chr(c).decode('mac_greek') for c in range(128, 256)]) // print(s.encode('utf-8')) /** * @private */ var eightBitMacEncodings = { 'x-mac-croatian': // Python: 'mac_croatian' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø' + '¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ', 'x-mac-cyrillic': // Python: 'mac_cyrillic' 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ' + 'јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю', 'x-mac-gaelic': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/GAELIC.TXT 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø' + 'ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ', 'x-mac-greek': // Python: 'mac_greek' 'Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ' + 'άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ\u00AD', 'x-mac-icelandic': // Python: 'mac_iceland' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', 'x-mac-inuit': // http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/INUIT.TXT 'ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ' + 'ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł', 'x-mac-ce': // Python: 'mac_latin2' 'ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ' + 'ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ', macintosh: // Python: 'mac_roman' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', 'x-mac-romanian': // Python: 'mac_romanian' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ', 'x-mac-turkish': // Python: 'mac_turkish' 'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' + '¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ' }; /** * Decodes an old-style Macintosh string. Returns either a Unicode JavaScript * string, or 'undefined' if the encoding is unsupported. For example, we do * not support Chinese, Japanese or Korean because these would need large * mapping tables. * @param {DataView} dataView * @param {number} offset * @param {number} dataLength * @param {string} encoding * @returns {string} */ decode.MACSTRING = function(dataView, offset, dataLength, encoding) { var table = eightBitMacEncodings[encoding]; if (table === undefined) { return undefined; } var result = ''; for (var i = 0; i < dataLength; i++) { var c = dataView.getUint8(offset + i); // In all eight-bit Mac encodings, the characters 0x00..0x7F are // mapped to U+0000..U+007F; we only need to look up the others. if (c <= 0x7F) { result += String.fromCharCode(c); } else { result += table[c & 0x7F]; } } return result; }; // Helper function for encode.MACSTRING. Returns a dictionary for mapping // Unicode character codes to their 8-bit MacOS equivalent. This table // is not exactly a super cheap data structure, but we do not care because // encoding Macintosh strings is only rarely needed in typical applications. var macEncodingTableCache = typeof WeakMap === 'function' && new WeakMap(); var macEncodingCacheKeys; var getMacEncodingTable = function(encoding) { // Since we use encoding as a cache key for WeakMap, it has to be // a String object and not a literal. And at least on NodeJS 2.10.1, // WeakMap requires that the same String instance is passed for cache hits. if (!macEncodingCacheKeys) { macEncodingCacheKeys = {}; for (var e in eightBitMacEncodings) { /*jshint -W053 */ // Suppress "Do not use String as a constructor." macEncodingCacheKeys[e] = new String(e); } } var cacheKey = macEncodingCacheKeys[encoding]; if (cacheKey === undefined) { return undefined; } // We can't do "if (cache.has(key)) {return cache.get(key)}" here: // since garbage collection may run at any time, it could also kick in // between the calls to cache.has() and cache.get(). In that case, // we would return 'undefined' even though we do support the encoding. if (macEncodingTableCache) { var cachedTable = macEncodingTableCache.get(cacheKey); if (cachedTable !== undefined) { return cachedTable; } } var decodingTable = eightBitMacEncodings[encoding]; if (decodingTable === undefined) { return undefined; } var encodingTable = {}; for (var i = 0; i < decodingTable.length; i++) { encodingTable[decodingTable.charCodeAt(i)] = i + 0x80; } if (macEncodingTableCache) { macEncodingTableCache.set(cacheKey, encodingTable); } return encodingTable; }; /** * Encodes an old-style Macintosh string. Returns a byte array upon success. * If the requested encoding is unsupported, or if the input string contains * a character that cannot be expressed in the encoding, the function returns * 'undefined'. * @param {string} str * @param {string} encoding * @returns {Array} */ encode.MACSTRING = function(str, encoding) { var table = getMacEncodingTable(encoding); if (table === undefined) { return undefined; } var result = []; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); // In all eight-bit Mac encodings, the characters 0x00..0x7F are // mapped to U+0000..U+007F; we only need to look up the others. if (c >= 0x80) { c = table[c]; if (c === undefined) { // str contains a Unicode character that cannot be encoded // in the requested encoding. return undefined; } } result[i] = c; // result.push(c); } return result; }; /** * @param {string} str * @param {string} encoding * @returns {number} */ sizeOf.MACSTRING = function(str, encoding) { var b = encode.MACSTRING(str, encoding); if (b !== undefined) { return b.length; } else { return 0; } }; // Helper for encode.VARDELTAS function isByteEncodable(value) { return value >= -128 && value <= 127; } // Helper for encode.VARDELTAS function encodeVarDeltaRunAsZeroes(deltas, pos, result) { var runLength = 0; var numDeltas = deltas.length; while (pos < numDeltas && runLength < 64 && deltas[pos] === 0) { ++pos; ++runLength; } result.push(0x80 | (runLength - 1)); return pos; } // Helper for encode.VARDELTAS function encodeVarDeltaRunAsBytes(deltas, offset, result) { var runLength = 0; var numDeltas = deltas.length; var pos = offset; while (pos < numDeltas && runLength < 64) { var value = deltas[pos]; if (!isByteEncodable(value)) { break; } // Within a byte-encoded run of deltas, a single zero is best // stored literally as 0x00 value. However, if we have two or // more zeroes in a sequence, it is better to start a new run. // Fore example, the sequence of deltas [15, 15, 0, 15, 15] // becomes 6 bytes (04 0F 0F 00 0F 0F) when storing the zero // within the current run, but 7 bytes (01 0F 0F 80 01 0F 0F) // when starting a new run. if (value === 0 && pos + 1 < numDeltas && deltas[pos + 1] === 0) { break; } ++pos; ++runLength; } result.push(runLength - 1); for (var i = offset; i < pos; ++i) { result.push((deltas[i] + 256) & 0xff); } return pos; } // Helper for encode.VARDELTAS function encodeVarDeltaRunAsWords(deltas, offset, result) { var runLength = 0; var numDeltas = deltas.length; var pos = offset; while (pos < numDeltas && runLength < 64) { var value = deltas[pos]; // Within a word-encoded run of deltas, it is easiest to start // a new run (with a different encoding) whenever we encounter // a zero value. For example, the sequence [0x6666, 0, 0x7777] // needs 7 bytes when storing the zero inside the current run // (42 66 66 00 00 77 77), and equally 7 bytes when starting a // new run (40 66 66 80 40 77 77). if (value === 0) { break; } // Within a word-encoded run of deltas, a single value in the // range (-128..127) should be encoded within the current run // because it is more compact. For example, the sequence // [0x6666, 2, 0x7777] becomes 7 bytes when storing the value // literally (42 66 66 00 02 77 77), but 8 bytes when starting // a new run (40 66 66 00 02 40 77 77). if (isByteEncodable(value) && pos + 1 < numDeltas && isByteEncodable(deltas[pos + 1])) { break; } ++pos; ++runLength; } result.push(0x40 | (runLength - 1)); for (var i = offset; i < pos; ++i) { var val = deltas[i]; result.push(((val + 0x10000) >> 8) & 0xff, (val + 0x100) & 0xff); } return pos; } /** * Encode a list of variation adjustment deltas. * * Variation adjustment deltas are used in ‘gvar’ and ‘cvar’ tables. * They indicate how points (in ‘gvar’) or values (in ‘cvar’) get adjusted * when generating instances of variation fonts. * * @see https://www.microsoft.com/typography/otspec/gvar.htm * @see https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gvar.html * @param {Array} * @return {Array} */ encode.VARDELTAS = function(deltas) { var pos = 0; var result = []; while (pos < deltas.length) { var value = deltas[pos]; if (value === 0) { pos = encodeVarDeltaRunAsZeroes(deltas, pos, result); } else if (value >= -128 && value <= 127) { pos = encodeVarDeltaRunAsBytes(deltas, pos, result); } else { pos = encodeVarDeltaRunAsWords(deltas, pos, result); } } return result; }; // Convert a list of values to a CFF INDEX structure. // The values should be objects containing name / type / value. /** * @param {Array} l * @returns {Array} */ encode.INDEX = function(l) { var i; //var offset, offsets, offsetEncoder, encodedOffsets, encodedOffset, data, // i, v; // Because we have to know which data type to use to encode the offsets, // we have to go through the values twice: once to encode the data and // calculate the offets, then again to encode the offsets using the fitting data type. var offset = 1; // First offset is always 1. var offsets = [offset]; var data = []; for (i = 0; i < l.length; i += 1) { var v = encode.OBJECT(l[i]); Array.prototype.push.apply(data, v); offset += v.length; offsets.push(offset); } if (data.length === 0) { return [0, 0]; } var encodedOffsets = []; var offSize = (1 + Math.floor(Math.log(offset) / Math.log(2)) / 8) | 0; var offsetEncoder = [undefined, encode.BYTE, encode.USHORT, encode.UINT24, encode.ULONG][offSize]; for (i = 0; i < offsets.length; i += 1) { var encodedOffset = offsetEncoder(offsets[i]); Array.prototype.push.apply(encodedOffsets, encodedOffset); } return Array.prototype.concat(encode.Card16(l.length), encode.OffSize(offSize), encodedOffsets, data); }; /** * @param {Array} * @returns {number} */ sizeOf.INDEX = function(v) { return encode.INDEX(v).length; }; /** * Convert an object to a CFF DICT structure. * The keys should be numeric. * The values should be objects containing name / type / value. * @param {Object} m * @returns {Array} */ encode.DICT = function(m) { var d = []; var keys = Object.keys(m); var length = keys.length; for (var i = 0; i < length; i += 1) { // Object.keys() return string keys, but our keys are always numeric. var k = parseInt(keys[i], 0); var v = m[k]; // Value comes before the key. d = d.concat(encode.OPERAND(v.value, v.type)); d = d.concat(encode.OPERATOR(k)); } return d; }; /** * @param {Object} * @returns {number} */ sizeOf.DICT = function(m) { return encode.DICT(m).length; }; /** * @param {number} * @returns {Array} */ encode.OPERATOR = function(v) { if (v < 1200) { return [v]; } else { return [12, v - 1200]; } }; /** * @param {Array} v * @param {string} * @returns {Array} */ encode.OPERAND = function(v, type) { var d = []; if (Array.isArray(type)) { for (var i = 0; i < type.length; i += 1) { check.argument(v.length === type.length, 'Not enough arguments given for type' + type); d = d.concat(encode.OPERAND(v[i], type[i])); } } else { if (type === 'SID') { d = d.concat(encode.NUMBER(v)); } else if (type === 'offset') { // We make it easy for ourselves and always encode offsets as // 4 bytes. This makes offset calculation for the top dict easier. d = d.concat(encode.NUMBER32(v)); } else if (type === 'number') { d = d.concat(encode.NUMBER(v)); } else if (type === 'real') { d = d.concat(encode.REAL(v)); } else { throw new Error('Unknown operand type ' + type); // FIXME Add support for booleans } } return d; }; encode.OP = encode.BYTE; sizeOf.OP = sizeOf.BYTE; // memoize charstring encoding using WeakMap if available var wmm = typeof WeakMap === 'function' && new WeakMap(); /** * Convert a list of CharString operations to bytes. * @param {Array} * @returns {Array} */ encode.CHARSTRING = function(ops) { // See encode.MACSTRING for why we don't do "if (wmm && wmm.has(ops))". if (wmm) { var cachedValue = wmm.get(ops); if (cachedValue !== undefined) { return cachedValue; } } var d = []; var length = ops.length; for (var i = 0; i < length; i += 1) { var op = ops[i]; d = d.concat(encode[op.type](op.value)); } if (wmm) { wmm.set(ops, d); } return d; }; /** * @param {Array} * @returns {number} */ sizeOf.CHARSTRING = function(ops) { return encode.CHARSTRING(ops).length; }; // Utility functions //////////////////////////////////////////////////////// /** * Convert an object containing name / type / value to bytes. * @param {Object} * @returns {Array} */ encode.OBJECT = function(v) { var encodingFunction = encode[v.type]; check.argument(encodingFunction !== undefined, 'No encoding function for type ' + v.type); return encodingFunction(v.value); }; /** * @param {Object} * @returns {number} */ sizeOf.OBJECT = function(v) { var sizeOfFunction = sizeOf[v.type]; check.argument(sizeOfFunction !== undefined, 'No sizeOf function for type ' + v.type); return sizeOfFunction(v.value); }; /** * Convert a table object to bytes. * A table contains a list of fields containing the metadata (name, type and default value). * The table itself has the field values set as attributes. * @param {opentype.Table} * @returns {Array} */ encode.TABLE = function(table) { var d = []; var length = table.fields.length; var subtables = []; var subtableOffsets = []; var i; for (i = 0; i < length; i += 1) { var field = table.fields[i]; var encodingFunction = encode[field.type]; check.argument(encodingFunction !== undefined, 'No encoding function for field type ' + field.type + ' (' + field.name + ')'); var value = table[field.name]; if (value === undefined) { value = field.value; } var bytes = encodingFunction(value); if (field.type === 'TABLE') { subtableOffsets.push(d.length); d = d.concat([0, 0]); subtables.push(bytes); } else { d = d.concat(bytes); } } for (i = 0; i < subtables.length; i += 1) { var o = subtableOffsets[i]; var offset = d.length; check.argument(offset < 65536, 'Table ' + table.tableName + ' too big.'); d[o] = offset >> 8; d[o + 1] = offset & 0xff; d = d.concat(subtables[i]); } return d; }; /** * @param {opentype.Table} * @returns {number} */ sizeOf.TABLE = function(table) { var numBytes = 0; var length = table.fields.length; for (var i = 0; i < length; i += 1) { var field = table.fields[i]; var sizeOfFunction = sizeOf[field.type]; check.argument(sizeOfFunction !== undefined, 'No sizeOf function for field type ' + field.type + ' (' + field.name + ')'); var value = table[field.name]; if (value === undefined) { value = field.value; } numBytes += sizeOfFunction(value); // Subtables take 2 more bytes for offsets. if (field.type === 'TABLE') { numBytes += 2; } } return numBytes; }; encode.RECORD = encode.TABLE; sizeOf.RECORD = sizeOf.TABLE; // Merge in a list of bytes. encode.LITERAL = function(v) { return v; }; sizeOf.LITERAL = function(v) { return v.length; }; exports.decode = decode; exports.encode = encode; exports.sizeOf = sizeOf; },{"./check":7}],39:[function(_dereq_,module,exports){ (function (Buffer){ 'use strict'; exports.isBrowser = function() { return typeof window !== 'undefined'; }; exports.isNode = function() { return typeof window === 'undefined'; }; exports.nodeBufferToArrayBuffer = function(buffer) { var ab = new ArrayBuffer(buffer.length); var view = new Uint8Array(ab); for (var i = 0; i < buffer.length; ++i) { view[i] = buffer[i]; } return ab; }; exports.arrayBufferToNodeBuffer = function(ab) { var buffer = new Buffer(ab.byteLength); var view = new Uint8Array(ab); for (var i = 0; i < buffer.length; ++i) { buffer[i] = view[i]; } return buffer; }; exports.checkArgument = function(expression, message) { if (!expression) { throw message; } }; }).call(this,_dereq_("buffer").Buffer) },{"buffer":3}],40:[function(_dereq_,module,exports){ var TINF_OK = 0; var TINF_DATA_ERROR = -3; function Tree() { this.table = new Uint16Array(16); /* table of code length counts */ this.trans = new Uint16Array(288); /* code -> symbol translation table */ } function Data(source, dest) { this.source = source; this.sourceIndex = 0; this.tag = 0; this.bitcount = 0; this.dest = dest; this.destLen = 0; this.ltree = new Tree(); /* dynamic length/symbol tree */ this.dtree = new Tree(); /* dynamic distance tree */ } /* --------------------------------------------------- * * -- uninitialized global data (static structures) -- * * --------------------------------------------------- */ var sltree = new Tree(); var sdtree = new Tree(); /* extra bits and base tables for length codes */ var length_bits = new Uint8Array(30); var length_base = new Uint16Array(30); /* extra bits and base tables for distance codes */ var dist_bits = new Uint8Array(30); var dist_base = new Uint16Array(30); /* special ordering of code length codes */ var clcidx = new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]); /* used by tinf_decode_trees, avoids allocations every call */ var code_tree = new Tree(); var lengths = new Uint8Array(288 + 32); /* ----------------------- * * -- utility functions -- * * ----------------------- */ /* build extra bits and base tables */ function tinf_build_bits_base(bits, base, delta, first) { var i, sum; /* build bits table */ for (i = 0; i < delta; ++i) bits[i] = 0; for (i = 0; i < 30 - delta; ++i) bits[i + delta] = i / delta | 0; /* build base table */ for (sum = first, i = 0; i < 30; ++i) { base[i] = sum; sum += 1 << bits[i]; } } /* build the fixed huffman trees */ function tinf_build_fixed_trees(lt, dt) { var i; /* build fixed length tree */ for (i = 0; i < 7; ++i) lt.table[i] = 0; lt.table[7] = 24; lt.table[8] = 152; lt.table[9] = 112; for (i = 0; i < 24; ++i) lt.trans[i] = 256 + i; for (i = 0; i < 144; ++i) lt.trans[24 + i] = i; for (i = 0; i < 8; ++i) lt.trans[24 + 144 + i] = 280 + i; for (i = 0; i < 112; ++i) lt.trans[24 + 144 + 8 + i] = 144 + i; /* build fixed distance tree */ for (i = 0; i < 5; ++i) dt.table[i] = 0; dt.table[5] = 32; for (i = 0; i < 32; ++i) dt.trans[i] = i; } /* given an array of code lengths, build a tree */ var offs = new Uint16Array(16); function tinf_build_tree(t, lengths, off, num) { var i, sum; /* clear code length count table */ for (i = 0; i < 16; ++i) t.table[i] = 0; /* scan symbol lengths, and sum code length counts */ for (i = 0; i < num; ++i) t.table[lengths[off + i]]++; t.table[0] = 0; /* compute offset table for distribution sort */ for (sum = 0, i = 0; i < 16; ++i) { offs[i] = sum; sum += t.table[i]; } /* create code->symbol translation table (symbols sorted by code) */ for (i = 0; i < num; ++i) { if (lengths[off + i]) t.trans[offs[lengths[off + i]]++] = i; } } /* ---------------------- * * -- decode functions -- * * ---------------------- */ /* get one bit from source stream */ function tinf_getbit(d) { /* check if tag is empty */ if (!d.bitcount--) { /* load next tag */ d.tag = d.source[d.sourceIndex++]; d.bitcount = 7; } /* shift bit out of tag */ var bit = d.tag & 1; d.tag >>>= 1; return bit; } /* read a num bit value from a stream and add base */ function tinf_read_bits(d, num, base) { if (!num) return base; while (d.bitcount < 24) { d.tag |= d.source[d.sourceIndex++] << d.bitcount; d.bitcount += 8; } var val = d.tag & (0xffff >>> (16 - num)); d.tag >>>= num; d.bitcount -= num; return val + base; } /* given a data stream and a tree, decode a symbol */ function tinf_decode_symbol(d, t) { while (d.bitcount < 24) { d.tag |= d.source[d.sourceIndex++] << d.bitcount; d.bitcount += 8; } var sum = 0, cur = 0, len = 0; var tag = d.tag; /* get more bits while code value is above sum */ do { cur = 2 * cur + (tag & 1); tag >>>= 1; ++len; sum += t.table[len]; cur -= t.table[len]; } while (cur >= 0); d.tag = tag; d.bitcount -= len; return t.trans[sum + cur]; } /* given a data stream, decode dynamic trees from it */ function tinf_decode_trees(d, lt, dt) { var hlit, hdist, hclen; var i, num, length; /* get 5 bits HLIT (257-286) */ hlit = tinf_read_bits(d, 5, 257); /* get 5 bits HDIST (1-32) */ hdist = tinf_read_bits(d, 5, 1); /* get 4 bits HCLEN (4-19) */ hclen = tinf_read_bits(d, 4, 4); for (i = 0; i < 19; ++i) lengths[i] = 0; /* read code lengths for code length alphabet */ for (i = 0; i < hclen; ++i) { /* get 3 bits code length (0-7) */ var clen = tinf_read_bits(d, 3, 0); lengths[clcidx[i]] = clen; } /* build code length tree */ tinf_build_tree(code_tree, lengths, 0, 19); /* decode code lengths for the dynamic trees */ for (num = 0; num < hlit + hdist;) { var sym = tinf_decode_symbol(d, code_tree); switch (sym) { case 16: /* copy previous code length 3-6 times (read 2 bits) */ var prev = lengths[num - 1]; for (length = tinf_read_bits(d, 2, 3); length; --length) { lengths[num++] = prev; } break; case 17: /* repeat code length 0 for 3-10 times (read 3 bits) */ for (length = tinf_read_bits(d, 3, 3); length; --length) { lengths[num++] = 0; } break; case 18: /* repeat code length 0 for 11-138 times (read 7 bits) */ for (length = tinf_read_bits(d, 7, 11); length; --length) { lengths[num++] = 0; } break; default: /* values 0-15 represent the actual code lengths */ lengths[num++] = sym; break; } } /* build dynamic trees */ tinf_build_tree(lt, lengths, 0, hlit); tinf_build_tree(dt, lengths, hlit, hdist); } /* ----------------------------- * * -- block inflate functions -- * * ----------------------------- */ /* given a stream and two trees, inflate a block of data */ function tinf_inflate_block_data(d, lt, dt) { while (1) { var sym = tinf_decode_symbol(d, lt); /* check for end of block */ if (sym === 256) { return TINF_OK; } if (sym < 256) { d.dest[d.destLen++] = sym; } else { var length, dist, offs; var i; sym -= 257; /* possibly get more bits from length code */ length = tinf_read_bits(d, length_bits[sym], length_base[sym]); dist = tinf_decode_symbol(d, dt); /* possibly get more bits from distance code */ offs = d.destLen - tinf_read_bits(d, dist_bits[dist], dist_base[dist]); /* copy match */ for (i = offs; i < offs + length; ++i) { d.dest[d.destLen++] = d.dest[i]; } } } } /* inflate an uncompressed block of data */ function tinf_inflate_uncompressed_block(d) { var length, invlength; var i; /* unread from bitbuffer */ while (d.bitcount > 8) { d.sourceIndex--; d.bitcount -= 8; } /* get length */ length = d.source[d.sourceIndex + 1]; length = 256 * length + d.source[d.sourceIndex]; /* get one's complement of length */ invlength = d.source[d.sourceIndex + 3]; invlength = 256 * invlength + d.source[d.sourceIndex + 2]; /* check length */ if (length !== (~invlength & 0x0000ffff)) return TINF_DATA_ERROR; d.sourceIndex += 4; /* copy block */ for (i = length; i; --i) d.dest[d.destLen++] = d.source[d.sourceIndex++]; /* make sure we start next block on a byte boundary */ d.bitcount = 0; return TINF_OK; } /* inflate stream from source to dest */ function tinf_uncompress(source, dest) { var d = new Data(source, dest); var bfinal, btype, res; do { /* read final block flag */ bfinal = tinf_getbit(d); /* read block type (2 bits) */ btype = tinf_read_bits(d, 2, 0); /* decompress block */ switch (btype) { case 0: /* decompress uncompressed block */ res = tinf_inflate_uncompressed_block(d); break; case 1: /* decompress block with fixed huffman trees */ res = tinf_inflate_block_data(d, sltree, sdtree); break; case 2: /* decompress block with dynamic huffman trees */ tinf_decode_trees(d, d.ltree, d.dtree); res = tinf_inflate_block_data(d, d.ltree, d.dtree); break; default: res = TINF_DATA_ERROR; } if (res !== TINF_OK) throw new Error('Data error'); } while (!bfinal); if (d.destLen < d.dest.length) { if (typeof d.dest.slice === 'function') return d.dest.slice(0, d.destLen); else return d.dest.subarray(0, d.destLen); } return d.dest; } /* -------------------- * * -- initialization -- * * -------------------- */ /* build fixed huffman trees */ tinf_build_fixed_trees(sltree, sdtree); /* build extra bits and base tables */ tinf_build_bits_base(length_bits, length_base, 4, 3); tinf_build_bits_base(dist_bits, dist_base, 2, 1); /* fix a special case */ length_bits[28] = 0; length_base[28] = 258; module.exports = tinf_uncompress; },{}],41:[function(_dereq_,module,exports){ /** * @module Shape * @submodule 2D Primitives * @for p5 * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('./core'); var constants = _dereq_('./constants'); var canvas = _dereq_('./canvas'); _dereq_('./error_helpers'); /** * Draw an arc to the screen. If called with only a, b, c, d, start, and * stop, the arc will be drawn as an open pie. If mode is provided, the arc * will be drawn either open, as a chord, or as a pie as specified. The * origin may be changed with the ellipseMode() function.

* Note that drawing a full circle (ex: 0 to TWO_PI) will appear blank * because 0 and TWO_PI are the same position on the unit circle. The * best way to handle this is by using the ellipse() function instead * to create a closed ellipse, and to use the arc() function * only to draw parts of an ellipse. * * @method arc * @param {Number} a x-coordinate of the arc's ellipse * @param {Number} b y-coordinate of the arc's ellipse * @param {Number} c width of the arc's ellipse by default * @param {Number} d height of the arc's ellipse by default * @param {Number} start angle to start the arc, specified in radians * @param {Number} stop angle to stop the arc, specified in radians * @param {Constant} [mode] optional parameter to determine the way of drawing * the arc. either CHORD or PIE * @chainable * @example *
* * arc(50, 55, 50, 50, 0, HALF_PI); * noFill(); * arc(50, 55, 60, 60, HALF_PI, PI); * arc(50, 55, 70, 70, PI, PI+QUARTER_PI); * arc(50, 55, 80, 80, PI+QUARTER_PI, TWO_PI); * *
* *
* * arc(50, 50, 80, 80, 0, PI+QUARTER_PI, OPEN); * *
* *
* * arc(50, 50, 80, 80, 0, PI+QUARTER_PI, CHORD); * *
* *
* * arc(50, 50, 80, 80, 0, PI+QUARTER_PI, PIE); * *
* * @alt *shattered outline of an ellipse with a quarter of a white circle bottom-right. *white ellipse with black outline with top right missing. *white ellipse with top right missing with black outline around shape. *white ellipse with top right quarter missing with black outline around the shape. * */ p5.prototype.arc = function(x, y, w, h, start, stop, mode) { var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } if (!this._renderer._doStroke && !this._renderer._doFill) { return this; } if (this._angleMode === constants.DEGREES) { start = this.radians(start); stop = this.radians(stop); } // Make all angles positive... while (start < 0) { start += constants.TWO_PI; } while (stop < 0) { stop += constants.TWO_PI; } // ...and confine them to the interval [0,TWO_PI). start %= constants.TWO_PI; stop %= constants.TWO_PI; // account for full circle if (stop === start) { stop += constants.TWO_PI; } // Adjust angles to counter linear scaling. if (start <= constants.HALF_PI) { start = Math.atan(w / h * Math.tan(start)); } else if (start > constants.HALF_PI && start <= 3 * constants.HALF_PI) { start = Math.atan(w / h * Math.tan(start)) + constants.PI; } else { start = Math.atan(w / h * Math.tan(start)) + constants.TWO_PI; } if (stop <= constants.HALF_PI) { stop = Math.atan(w / h * Math.tan(stop)); } else if (stop > constants.HALF_PI && stop <= 3 * constants.HALF_PI) { stop = Math.atan(w / h * Math.tan(stop)) + constants.PI; } else { stop = Math.atan(w / h * Math.tan(stop)) + constants.TWO_PI; } // Exceed the interval if necessary in order to preserve the size and // orientation of the arc. if (start > stop) { stop += constants.TWO_PI; } // p5 supports negative width and heights for ellipses w = Math.abs(w); h = Math.abs(h); this._renderer.arc(x, y, w, h, start, stop, mode); return this; }; /** * Draws an ellipse (oval) to the screen. An ellipse with equal width and * height is a circle. By default, the first two parameters set the location, * and the third and fourth parameters set the shape's width and height. If * no height is specified, the value of width is used for both the width and * height. If a negative height or width is specified, the absolute value is taken. * The origin may be changed with the ellipseMode() function. * * @method ellipse * @param {Number} x x-coordinate of the ellipse. * @param {Number} y y-coordinate of the ellipse. * @param {Number} w width of the ellipse. * @param {Number} [h] height of the ellipse. * @chainable * @example *
* * ellipse(56, 46, 55, 55); * *
* * @alt *white ellipse with black outline in middle-right of canvas that is 55x55. * */ p5.prototype.ellipse = function() { var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } // Duplicate 3rd argument if only 3 given. if (args.length === 3) { args.push(args[2]); } // p5 supports negative width and heights for rects if (args[2] < 0){args[2] = Math.abs(args[2]);} if (args[3] < 0){args[3] = Math.abs(args[3]);} if (!this._renderer._doStroke && !this._renderer._doFill) { return this; } var vals = canvas.modeAdjust( args[0], args[1], args[2], args[3], this._renderer._ellipseMode); args[0] = vals.x; args[1] = vals.y; args[2] = vals.w; args[3] = vals.h; this._renderer.ellipse(args); return this; }; /** * Draws a line (a direct path between two points) to the screen. The version * of line() with four parameters draws the line in 2D. To color a line, use * the stroke() function. A line cannot be filled, therefore the fill() * function will not affect the color of a line. 2D lines are drawn with a * width of one pixel by default, but this can be changed with the * strokeWeight() function. * * @method line * @param {Number} x1 the x-coordinate of the first point * @param {Number} y1 the y-coordinate of the first point * @param {Number} x2 the x-coordinate of the second point * @param {Number} y2 the y-coordinate of the second point * @chainable * @example *
* * line(30, 20, 85, 75); * *
* *
* * line(30, 20, 85, 20); * stroke(126); * line(85, 20, 85, 75); * stroke(255); * line(85, 75, 30, 75); * *
* * @alt *line 78 pixels long running from mid-top to bottom-right of canvas. *3 lines of various stroke sizes. Form top, bottom and right sides of a square. * */ ////commented out original // p5.prototype.line = function(x1, y1, x2, y2) { // if (!this._renderer._doStroke) { // return this; // } // if(this._renderer.isP3D){ // } else { // this._renderer.line(x1, y1, x2, y2); // } // }; p5.prototype.line = function() { if (!this._renderer._doStroke) { return this; } var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } //check whether we should draw a 3d line or 2d if(this._renderer.isP3D){ this._renderer.line( args[0], args[1], args[2], args[3], args[4], args[5]); } else { this._renderer.line( args[0], args[1], args[2], args[3]); } return this; }; /** * Draws a point, a coordinate in space at the dimension of one pixel. * The first parameter is the horizontal value for the point, the second * value is the vertical value for the point. The color of the point is * determined by the current stroke. * * @method point * @param {Number} x the x-coordinate * @param {Number} y the y-coordinate * @chainable * @example *
* * point(30, 20); * point(85, 20); * point(85, 75); * point(30, 75); * *
* * @alt *4 points centered in the middle-right of the canvas. * */ p5.prototype.point = function() { if (!this._renderer._doStroke) { return this; } var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } //check whether we should draw a 3d line or 2d if(this._renderer.isP3D){ this._renderer.point( args[0], args[1], args[2] ); } else { this._renderer.point( args[0], args[1] ); } return this; }; /** * Draw a quad. A quad is a quadrilateral, a four sided polygon. It is * similar to a rectangle, but the angles between its edges are not * constrained to ninety degrees. The first pair of parameters (x1,y1) * sets the first vertex and the subsequent pairs should proceed * clockwise or counter-clockwise around the defined shape. * * @method quad * @param {Number} x1 the x-coordinate of the first point * @param {Number} y1 the y-coordinate of the first point * @param {Number} x2 the x-coordinate of the second point * @param {Number} y2 the y-coordinate of the second point * @param {Number} x3 the x-coordinate of the third point * @param {Number} y3 the y-coordinate of the third point * @param {Number} x4 the x-coordinate of the fourth point * @param {Number} y4 the y-coordinate of the fourth point * @chainable * @example *
* * quad(38, 31, 86, 20, 69, 63, 30, 76); * *
* * @alt *irregular white quadrilateral shape with black outline mid-right of canvas. * */ /** * @method quad * @param {Number} x1 * @param {Number} y1 * @param {Number} x2 * @param {Number} y2 * @param {Number} x3 * @param {Number} y3 * @param {Number} x4 * @param {Number} y4 * @chainable */ p5.prototype.quad = function() { if (!this._renderer._doStroke && !this._renderer._doFill) { return this; } var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } if(this._renderer.isP3D){ this._renderer.quad( args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9], args[10], args[11] ); } else { this._renderer.quad( args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7] ); } return this; }; /** * Draws a rectangle to the screen. A rectangle is a four-sided shape with * every angle at ninety degrees. By default, the first two parameters set * the location of the upper-left corner, the third sets the width, and the * fourth sets the height. The way these parameters are interpreted, however, * may be changed with the rectMode() function. *

* The fifth, sixth, seventh and eighth parameters, if specified, * determine corner radius for the top-right, top-left, lower-right and * lower-left corners, respectively. An omitted corner radius parameter is set * to the value of the previously specified radius value in the parameter list. * * @method rect * @param {Number} x x-coordinate of the rectangle. * @param {Number} y y-coordinate of the rectangle. * @param {Number} w width of the rectangle. * @param {Number} h height of the rectangle. * @param {Number} [tl] optional radius of top-left corner. * @param {Number} [tr] optional radius of top-right corner. * @param {Number} [br] optional radius of bottom-right corner. * @param {Number} [bl] optional radius of bottom-left corner. * @return {p5} the p5 object. * @example *
* * // Draw a rectangle at location (30, 20) with a width and height of 55. * rect(30, 20, 55, 55); * *
* *
* * // Draw a rectangle with rounded corners, each having a radius of 20. * rect(30, 20, 55, 55, 20); * *
* *
* * // Draw a rectangle with rounded corners having the following radii: * // top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5. * rect(30, 20, 55, 55, 20, 15, 10, 5); * *
* * @alt * 55x55 white rect with black outline in mid-right of canvas. * 55x55 white rect with black outline and rounded edges in mid-right of canvas. * 55x55 white rect with black outline and rounded edges of different radii. */ /** * @method rect * @param {Number} x * @param {Number} y * @param {Number} w * @param {Number} h * @param {Number} [detailX] * @param {Number} [detailY] * @chainable */ p5.prototype.rect = function () { var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } if (!this._renderer._doStroke && !this._renderer._doFill) { return this; } var vals = canvas.modeAdjust( args[0], args[1], args[2], args[3], this._renderer._rectMode); args[0] = vals.x; args[1] = vals.y; args[2] = vals.w; args[3] = vals.h; this._renderer.rect(args); return this; }; /** * A triangle is a plane created by connecting three points. The first two * arguments specify the first point, the middle two arguments specify the * second point, and the last two arguments specify the third point. * * @method triangle * @param {Number} x1 x-coordinate of the first point * @param {Number} y1 y-coordinate of the first point * @param {Number} x2 x-coordinate of the second point * @param {Number} y2 y-coordinate of the second point * @param {Number} x3 x-coordinate of the third point * @param {Number} y3 y-coordinate of the third point * @chainable * @example *
* * triangle(30, 75, 58, 20, 86, 75); * *
* *@alt * white triangle with black outline in mid-right of canvas. * */ p5.prototype.triangle = function() { if (!this._renderer._doStroke && !this._renderer._doFill) { return this; } var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } this._renderer.triangle(args); return this; }; module.exports = p5; },{"./canvas":43,"./constants":44,"./core":45,"./error_helpers":48}],42:[function(_dereq_,module,exports){ /** * @module Shape * @submodule Attributes * @for p5 * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('./core'); var constants = _dereq_('./constants'); /** * Modifies the location from which ellipses are drawn by changing the way * in which parameters given to ellipse() are interpreted. *

* The default mode is ellipseMode(CENTER), which interprets the first two * parameters of ellipse() as the shape's center point, while the third and * fourth parameters are its width and height. *

* ellipseMode(RADIUS) also uses the first two parameters of ellipse() as * the shape's center point, but uses the third and fourth parameters to * specify half of the shapes's width and height. *

* ellipseMode(CORNER) interprets the first two parameters of ellipse() as * the upper-left corner of the shape, while the third and fourth parameters * are its width and height. *

* ellipseMode(CORNERS) interprets the first two parameters of ellipse() as * the location of one corner of the ellipse's bounding box, and the third * and fourth parameters as the location of the opposite corner. *

* The parameter must be written in ALL CAPS because Javascript is a * case-sensitive language. * * @method ellipseMode * @param {Constant} mode either CENTER, RADIUS, CORNER, or CORNERS * @chainable * @example *
* * ellipseMode(RADIUS); // Set ellipseMode to RADIUS * fill(255); // Set fill to white * ellipse(50, 50, 30, 30); // Draw white ellipse using RADIUS mode * * ellipseMode(CENTER); // Set ellipseMode to CENTER * fill(100); // Set fill to gray * ellipse(50, 50, 30, 30); // Draw gray ellipse using CENTER mode * *
* *
* * ellipseMode(CORNER); // Set ellipseMode is CORNER * fill(255); // Set fill to white * ellipse(25, 25, 50, 50); // Draw white ellipse using CORNER mode * * ellipseMode(CORNERS); // Set ellipseMode to CORNERS * fill(100); // Set fill to gray * ellipse(25, 25, 50, 50); // Draw gray ellipse using CORNERS mode * *
* * @alt * 60x60 white ellipse and 30x30 grey ellipse with black outlines at center. * 60x60 white ellipse @center and 30x30 grey ellipse top-right, black outlines. * */ p5.prototype.ellipseMode = function(m) { if (m === constants.CORNER || m === constants.CORNERS || m === constants.RADIUS || m === constants.CENTER) { this._renderer._ellipseMode = m; } return this; }; /** * Draws all geometry with jagged (aliased) edges. Note that smooth() is * active by default, so it is necessary to call noSmooth() to disable * smoothing of geometry, images, and fonts. * * @method noSmooth * @chainable * @example *
* * background(0); * noStroke(); * smooth(); * ellipse(30, 48, 36, 36); * noSmooth(); * ellipse(70, 48, 36, 36); * *
* * @alt * 2 pixelated 36x36 white ellipses to left & right of center, black background * */ p5.prototype.noSmooth = function() { this._renderer.noSmooth(); return this; }; /** * Modifies the location from which rectangles are drawn by changing the way * in which parameters given to rect() are interpreted. *

* The default mode is rectMode(CORNER), which interprets the first two * parameters of rect() as the upper-left corner of the shape, while the * third and fourth parameters are its width and height. *

* rectMode(CORNERS) interprets the first two parameters of rect() as the * location of one corner, and the third and fourth parameters as the * location of the opposite corner. *

* rectMode(CENTER) interprets the first two parameters of rect() as the * shape's center point, while the third and fourth parameters are its * width and height. *

* rectMode(RADIUS) also uses the first two parameters of rect() as the * shape's center point, but uses the third and fourth parameters to specify * half of the shapes's width and height. *

* The parameter must be written in ALL CAPS because Javascript is a * case-sensitive language. * * @method rectMode * @param {Constant} mode either CORNER, CORNERS, CENTER, or RADIUS * @chainable * @example *
* * rectMode(CORNER); // Default rectMode is CORNER * fill(255); // Set fill to white * rect(25, 25, 50, 50); // Draw white rect using CORNER mode * * rectMode(CORNERS); // Set rectMode to CORNERS * fill(100); // Set fill to gray * rect(25, 25, 50, 50); // Draw gray rect using CORNERS mode * *
* *
* * rectMode(RADIUS); // Set rectMode to RADIUS * fill(255); // Set fill to white * rect(50, 50, 30, 30); // Draw white rect using RADIUS mode * * rectMode(CENTER); // Set rectMode to CENTER * fill(100); // Set fill to gray * rect(50, 50, 30, 30); // Draw gray rect using CENTER mode * *
* * @alt * 50x50 white rect at center and 25x25 grey rect in the top left of the other. * 50x50 white rect at center and 25x25 grey rect in the center of the other. * */ p5.prototype.rectMode = function(m) { if (m === constants.CORNER || m === constants.CORNERS || m === constants.RADIUS || m === constants.CENTER) { this._renderer._rectMode = m; } return this; }; /** * Draws all geometry with smooth (anti-aliased) edges. smooth() will also * improve image quality of resized images. Note that smooth() is active by * default; noSmooth() can be used to disable smoothing of geometry, * images, and fonts. * * @method smooth * @chainable * @example *
* * background(0); * noStroke(); * smooth(); * ellipse(30, 48, 36, 36); * noSmooth(); * ellipse(70, 48, 36, 36); * *
* * @alt * 2 pixelated 36x36 white ellipses one left one right of center. On black. * */ p5.prototype.smooth = function() { this._renderer.smooth(); return this; }; /** * Sets the style for rendering line endings. These ends are either squared, * extended, or rounded, each of which specified with the corresponding * parameters: SQUARE, PROJECT, and ROUND. The default cap is ROUND. * * @method strokeCap * @param {Constant} cap either SQUARE, PROJECT, or ROUND * @chainable * @example *
* * strokeWeight(12.0); * strokeCap(ROUND); * line(20, 30, 80, 30); * strokeCap(SQUARE); * line(20, 50, 80, 50); * strokeCap(PROJECT); * line(20, 70, 80, 70); * *
* * @alt * 3 lines. Top line: rounded ends, mid: squared, bottom:longer squared ends. * */ p5.prototype.strokeCap = function(cap) { if (cap === constants.ROUND || cap === constants.SQUARE || cap === constants.PROJECT) { this._renderer.strokeCap(cap); } return this; }; /** * Sets the style of the joints which connect line segments. These joints * are either mitered, beveled, or rounded and specified with the * corresponding parameters MITER, BEVEL, and ROUND. The default joint is * MITER. * * @method strokeJoin * @param {Constant} join either MITER, BEVEL, ROUND * @chainable * @example *
* * noFill(); * strokeWeight(10.0); * strokeJoin(MITER); * beginShape(); * vertex(35, 20); * vertex(65, 50); * vertex(35, 80); * endShape(); * *
* *
* * noFill(); * strokeWeight(10.0); * strokeJoin(BEVEL); * beginShape(); * vertex(35, 20); * vertex(65, 50); * vertex(35, 80); * endShape(); * *
* *
* * noFill(); * strokeWeight(10.0); * strokeJoin(ROUND); * beginShape(); * vertex(35, 20); * vertex(65, 50); * vertex(35, 80); * endShape(); * *
* * @alt * Right-facing arrowhead shape with pointed tip in center of canvas. * Right-facing arrowhead shape with flat tip in center of canvas. * Right-facing arrowhead shape with rounded tip in center of canvas. * */ p5.prototype.strokeJoin = function(join) { if (join === constants.ROUND || join === constants.BEVEL || join === constants.MITER) { this._renderer.strokeJoin(join); } return this; }; /** * Sets the width of the stroke used for lines, points, and the border * around shapes. All widths are set in units of pixels. * * @method strokeWeight * @param {Number} weight the weight (in pixels) of the stroke * @return {p5} the p5 object * @example *
* * strokeWeight(1); // Default * line(20, 20, 80, 20); * strokeWeight(4); // Thicker * line(20, 40, 80, 40); * strokeWeight(10); // Beastly * line(20, 70, 80, 70); * *
* * @alt * 3 horizontal black lines. Top line: thin, mid: medium, bottom:thick. * */ p5.prototype.strokeWeight = function(w) { this._renderer.strokeWeight(w); return this; }; module.exports = p5; },{"./constants":44,"./core":45}],43:[function(_dereq_,module,exports){ /** * @requires constants */ var constants = _dereq_('./constants'); module.exports = { modeAdjust: function(a, b, c, d, mode) { if (mode === constants.CORNER) { return { x: a, y: b, w: c, h: d }; } else if (mode === constants.CORNERS) { return { x: a, y: b, w: c-a, h: d-b }; } else if (mode === constants.RADIUS) { return { x: a-c, y: b-d, w: 2*c, h: 2*d }; } else if (mode === constants.CENTER) { return { x: a-c*0.5, y: b-d*0.5, w: c, h: d }; } }, arcModeAdjust: function(a, b, c, d, mode) { if (mode === constants.CORNER) { return { x: a+c*0.5, y: b+d*0.5, w: c, h: d }; } else if (mode === constants.CORNERS) { return { x: a, y: b, w: c+a, h: d+b }; } else if (mode === constants.RADIUS) { return { x: a, y: b, w: 2*c, h: 2*d }; } else if (mode === constants.CENTER) { return { x: a, y: b, w: c, h: d }; } } }; },{"./constants":44}],44:[function(_dereq_,module,exports){ /** * @module Constants * @submodule Constants * @for p5 */ var PI = Math.PI; module.exports = { // GRAPHICS RENDERER /** * @property {String} P2D * @final */ P2D: 'p2d', /** * @property {String} WEBGL * @final */ WEBGL: 'webgl', // ENVIRONMENT ARROW: 'default', CROSS: 'crosshair', HAND: 'pointer', MOVE: 'move', TEXT: 'text', WAIT: 'wait', // TRIGONOMETRY /** * HALF_PI is a mathematical constant with the value * 1.57079632679489661923. It is half the ratio of the * circumference of a circle to its diameter. It is useful in * combination with the trigonometric functions sin() and cos(). * * @property {Number} HALF_PI * @final * * @example *
* arc(50, 50, 80, 80, 0, HALF_PI); *
* * @alt * 80x80 white quarter-circle with curve toward bottom right of canvas. * */ HALF_PI: PI / 2, /** * PI is a mathematical constant with the value * 3.14159265358979323846. It is the ratio of the circumference * of a circle to its diameter. It is useful in combination with * the trigonometric functions sin() and cos(). * * @property {Number} PI * @final * * @example *
* arc(50, 50, 80, 80, 0, PI); *
* * @alt * white half-circle with curve toward bottom of canvas. * */ PI: PI, /** * QUARTER_PI is a mathematical constant with the value 0.7853982. * It is one quarter the ratio of the circumference of a circle to * its diameter. It is useful in combination with the trigonometric * functions sin() and cos(). * * @property {Number} QUARTER_PI * @final * * @example *
* arc(50, 50, 80, 80, 0, QUARTER_PI); *
* * @alt * white eighth-circle rotated about 40 degrees with curve bottom right canvas. * */ QUARTER_PI: PI / 4, /** * TAU is an alias for TWO_PI, a mathematical constant with the * value 6.28318530717958647693. It is twice the ratio of the * circumference of a circle to its diameter. It is useful in * combination with the trigonometric functions sin() and cos(). * * @property {Number} TAU * @final * * @example *
* arc(50, 50, 80, 80, 0, TAU); *
* * @alt * 80x80 white ellipse shape in center of canvas. * */ TAU: PI * 2, /** * TWO_PI is a mathematical constant with the value * 6.28318530717958647693. It is twice the ratio of the * circumference of a circle to its diameter. It is useful in * combination with the trigonometric functions sin() and cos(). * * @property {Number} TWO_PI * @final * * @example *
* arc(50, 50, 80, 80, 0, TWO_PI); *
* * @alt * 80x80 white ellipse shape in center of canvas. * */ TWO_PI: PI * 2, /** * @property {String} DEGREES * @final */ DEGREES: 'degrees', /** * @property {String} RADIANS * @final */ RADIANS: 'radians', DEG_TO_RAD: PI / 180.0, RAD_TO_DEG: 180.0 / PI, // SHAPE /** * @property {String} CORNER * @final */ CORNER: 'corner', /** * @property {String} CORNERS * @final */ CORNERS: 'corners', /** * @property {String} RADIUS * @final */ RADIUS: 'radius', /** * @property {String} RIGHT * @final */ RIGHT: 'right', /** * @property {String} LEFT * @final */ LEFT: 'left', /** * @property {String} CENTER * @final */ CENTER: 'center', /** * @property {String} TOP * @final */ TOP: 'top', /** * @property {String} BOTTOM * @final */ BOTTOM: 'bottom', /** * @property {String} BASELINE * @final * @default alphabetic */ BASELINE: 'alphabetic', /** * @property {Number} POINTS * @final * @default 0x0000 */ POINTS: 0x0000, /** * @property {Number} LINES * @final * @default 0x0001 */ LINES: 0x0001, /** * @property {Number} LINE_STRIP * @final * @default 0x0003 */ LINE_STRIP: 0x0003, /** * @property {Number} LINE_LOOP * @final * @default 0x0002 */ LINE_LOOP: 0x0002, /** * @property {Number} TRIANGLES * @final * @default 0x0004 */ TRIANGLES: 0x0004, /** * @property {Number} TRIANGLE_FAN * @final * @default 0x0006 */ TRIANGLE_FAN: 0x0006, /** * @property {Number} TRIANGLE_STRIP * @final * @default 0x0005 */ TRIANGLE_STRIP: 0x0005, /** * @property {String} QUADS * @final */ QUADS: 'quads', /** * @property {String} QUAD_STRIP * @final * @default quad_strip */ QUAD_STRIP: 'quad_strip', /** * @property {String} CLOSE * @final */ CLOSE: 'close', /** * @property {String} OPEN * @final */ OPEN: 'open', /** * @property {String} CHORD * @final */ CHORD: 'chord', /** * @property {String} PIE * @final */ PIE: 'pie', /** * @property {String} PROJECT * @final * @default square */ PROJECT: 'square', // PEND: careful this is counterintuitive /** * @property {String} SQUARE * @final * @default butt */ SQUARE: 'butt', /** * @property {String} ROUND * @final */ ROUND: 'round', /** * @property {String} BEVEL * @final */ BEVEL: 'bevel', /** * @property {String} MITER * @final */ MITER: 'miter', // COLOR /** * @property {String} RGB * @final */ RGB: 'rgb', /** * @property {String} HSB * @final */ HSB: 'hsb', /** * @property {String} HSL * @final */ HSL: 'hsl', // DOM EXTENSION AUTO: 'auto', // INPUT ALT: 18, BACKSPACE: 8, CONTROL: 17, DELETE: 46, DOWN_ARROW: 40, ENTER: 13, ESCAPE: 27, LEFT_ARROW: 37, OPTION: 18, RETURN: 13, RIGHT_ARROW: 39, SHIFT: 16, TAB: 9, UP_ARROW: 38, // RENDERING /** * @property {String} BLEND * @final * @default source-over */ BLEND: 'source-over', /** * @property {String} ADD * @final * @default lighter */ ADD: 'lighter', //ADD: 'add', // //SUBTRACT: 'subtract', // /** * @property {String} DARKEST * @final */ DARKEST: 'darken', /** * @property {String} LIGHTEST * @final * @default lighten */ LIGHTEST: 'lighten', /** * @property {String} DIFFERENCE * @final */ DIFFERENCE: 'difference', /** * @property {String} EXCLUSION * @final */ EXCLUSION: 'exclusion', /** * @property {String} MULTIPLY * @final */ MULTIPLY: 'multiply', /** * @property {String} SCREEN * @final */ SCREEN: 'screen', /** * @property {String} REPLACE * @final * @default copy */ REPLACE: 'copy', /** * @property {String} OVERLAY * @final */ OVERLAY: 'overlay', /** * @property {String} HARD_LIGHT * @final */ HARD_LIGHT: 'hard-light', /** * @property {String} SOFT_LIGHT * @final */ SOFT_LIGHT: 'soft-light', /** * @property {String} DODGE * @final * @default color-dodge */ DODGE: 'color-dodge', /** * @property {String} BURN * @final * @default color-burn */ BURN: 'color-burn', // FILTERS /** * @property {String} THRESHOLD * @final */ THRESHOLD: 'threshold', /** * @property {String} GRAY * @final */ GRAY: 'gray', /** * @property {String} OPAQUE * @final */ OPAQUE: 'opaque', /** * @property {String} INVERT * @final */ INVERT: 'invert', /** * @property {String} POSTERIZE * @final */ POSTERIZE: 'posterize', /** * @property {String} DILATE * @final */ DILATE: 'dilate', /** * @property {String} ERODE * @final */ ERODE: 'erode', /** * @property {String} BLUR * @final */ BLUR: 'blur', // TYPOGRAPHY /** * @property {String} NORMAL * @final */ NORMAL: 'normal', /** * @property {String} ITALIC * @final */ ITALIC: 'italic', /** * @property {String} BOLD * @final */ BOLD: 'bold', // TYPOGRAPHY-INTERNAL _DEFAULT_TEXT_FILL: '#000000', _DEFAULT_LEADMULT: 1.25, _CTX_MIDDLE: 'middle', // VERTICES LINEAR: 'linear', QUADRATIC: 'quadratic', BEZIER: 'bezier', CURVE: 'curve', // DEVICE-ORIENTATION /** * @property {String} LANDSCAPE * @final */ LANDSCAPE: 'landscape', /** * @property {String} PORTRAIT * @final */ PORTRAIT: 'portrait', // DEFAULTS _DEFAULT_STROKE: '#000000', _DEFAULT_FILL: '#FFFFFF' }; },{}],45:[function(_dereq_,module,exports){ /** * @module Structure * @submodule Structure * @for p5 * @requires constants */ 'use strict'; _dereq_('./shim'); // Core needs the PVariables object var constants = _dereq_('./constants'); /** * This is the p5 instance constructor. * * A p5 instance holds all the properties and methods related to * a p5 sketch. It expects an incoming sketch closure and it can also * take an optional node parameter for attaching the generated p5 canvas * to a node. The sketch closure takes the newly created p5 instance as * its sole argument and may optionally set preload(), setup(), and/or * draw() properties on it for running a sketch. * * A p5 sketch can run in "global" or "instance" mode: * "global" - all properties and methods are attached to the window * "instance" - all properties and methods are bound to this p5 object * * @param {function} sketch a closure that can set optional preload(), * setup(), and/or draw() properties on the * given p5 instance * @param {HTMLElement|boolean} [node] element to attach canvas to, if a * boolean is passed in use it as sync * @param {boolean} [sync] start synchronously (optional) * @return {p5} a p5 instance */ var p5 = function(sketch, node, sync) { if (arguments.length === 2 && typeof node === 'boolean') { sync = node; node = undefined; } ////////////////////////////////////////////// // PUBLIC p5 PROPERTIES AND METHODS ////////////////////////////////////////////// /** * Called directly before setup(), the preload() function is used to handle * asynchronous loading of external files. If a preload function is * defined, setup() will wait until any load calls within have finished. * Nothing besides load calls should be inside preload (loadImage, * loadJSON, loadFont, loadStrings, etc).

* By default the text "loading..." will be displayed. To make your own * loading page, include an HTML element with id "p5_loading" in your * page. More information here. * * @method preload * @example *
* var img; * var c; * function preload() { // preload() runs once * img = loadImage('assets/laDefense.jpg'); * } * * function setup() { // setup() waits until preload() is done * img.loadPixels(); * // get color of middle pixel * c = img.get(img.width/2, img.height/2); * } * * function draw() { * background(c); * image(img, 25, 25, 50, 50); * } *
* * @alt * nothing displayed * */ /** * The setup() function is called once when the program starts. It's used to * define initial environment properties such as screen size and background * color and to load media such as images and fonts as the program starts. * There can only be one setup() function for each program and it shouldn't * be called again after its initial execution. *

* Note: Variables declared within setup() are not accessible within other * functions, including draw(). * * @method setup * @example *
* var a = 0; * * function setup() { * background(0); * noStroke(); * fill(102); * } * * function draw() { * rect(a++%width, 10, 2, 80); * } *
* * @alt * nothing displayed * */ /** * Called directly after setup(), the draw() function continuously executes * the lines of code contained inside its block until the program is stopped * or noLoop() is called. Note if noLoop() is called in setup(), draw() will * still be executed once before stopping. draw() is called automatically and * should never be called explicitly. *

* It should always be controlled with noLoop(), redraw() and loop(). After * noLoop() stops the code in draw() from executing, redraw() causes the * code inside draw() to execute once, and loop() will cause the code * inside draw() to resume executing continuously. *

* The number of times draw() executes in each second may be controlled with * the frameRate() function. *

* There can only be one draw() function for each sketch, and draw() must * exist if you want the code to run continuously, or to process events such * as mousePressed(). Sometimes, you might have an empty call to draw() in * your program, as shown in the above example. *

* It is important to note that the drawing coordinate system will be reset * at the beginning of each draw() call. If any transformations are performed * within draw() (ex: scale, rotate, translate, their effects will be * undone at the beginning of draw(), so transformations will not accumulate * over time. On the other hand, styling applied (ex: fill, stroke, etc) will * remain in effect. * * @method draw * @example *
* var yPos = 0; * function setup() { // setup() runs once * frameRate(30); * } * function draw() { // draw() loops forever, until stopped * background(204); * yPos = yPos - 1; * if (yPos < 0) { * yPos = height; * } * line(0, yPos, width, yPos); * } *
* * @alt * nothing displayed * */ ////////////////////////////////////////////// // PRIVATE p5 PROPERTIES AND METHODS ////////////////////////////////////////////// this._setupDone = false; // for handling hidpi this._pixelDensity = Math.ceil(window.devicePixelRatio) || 1; this._userNode = node; this._curElement = null; this._elements = []; this._requestAnimId = 0; this._preloadCount = 0; this._isGlobal = false; this._loop = true; this._styles = []; this._defaultCanvasSize = { width: 100, height: 100 }; this._events = { // keep track of user-events for unregistering later 'mousemove': null, 'mousedown': null, 'mouseup': null, 'dragend': null, 'dragover': null, 'click': null, 'mouseover': null, 'mouseout': null, 'keydown': null, 'keyup': null, 'keypress': null, 'touchstart': null, 'touchmove': null, 'touchend': null, 'resize': null, 'blur': null }; this._events.wheel = null; this._loadingScreenId = 'p5_loading'; if (window.DeviceOrientationEvent) { this._events.deviceorientation = null; } if (window.DeviceMotionEvent && !window._isNodeWebkit) { this._events.devicemotion = null; } this._start = function () { // Find node if id given if (this._userNode) { if (typeof this._userNode === 'string') { this._userNode = document.getElementById(this._userNode); } } var userPreload = this.preload || window.preload; // look for "preload" if (userPreload) { // Setup loading screen // Set loading scfeen into dom if not present // Otherwise displays and removes user provided loading screen var loadingScreen = document.getElementById(this._loadingScreenId); if(!loadingScreen){ loadingScreen = document.createElement('div'); loadingScreen.innerHTML = 'Loading...'; loadingScreen.style.position = 'absolute'; loadingScreen.id = this._loadingScreenId; var node = this._userNode || document.body; node.appendChild(loadingScreen); } // var methods = this._preloadMethods; for (var method in this._preloadMethods){ // default to p5 if no object defined this._preloadMethods[method] = this._preloadMethods[method] || p5; var obj = this._preloadMethods[method]; //it's p5, check if it's global or instance if (obj === p5.prototype || obj === p5){ obj = this._isGlobal ? window : this; } this._registeredPreloadMethods[method] = obj[method]; obj[method] = this._wrapPreload(obj, method); } userPreload(); this._runIfPreloadsAreDone(); } else { this._setup(); this._runFrames(); this._draw(); } }.bind(this); this._runIfPreloadsAreDone = function(){ var context = this._isGlobal ? window : this; if (context._preloadCount === 0) { var loadingScreen = document.getElementById(context._loadingScreenId); if (loadingScreen) { loadingScreen.parentNode.removeChild(loadingScreen); } context._setup(); context._runFrames(); context._draw(); } }; this._decrementPreload = function(){ var context = this._isGlobal ? window : this; if(typeof context.preload === 'function'){ context._setProperty('_preloadCount', context._preloadCount - 1); context._runIfPreloadsAreDone(); } }; this._wrapPreload = function(obj, fnName){ return function(){ //increment counter this._incrementPreload(); //call original function var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } // args.push(this._decrementPreload.bind(this)); return this._registeredPreloadMethods[fnName].apply(obj, args); }.bind(this); }; this._incrementPreload = function(){ var context = this._isGlobal ? window : this; context._setProperty('_preloadCount', context._preloadCount + 1); }; this._setup = function() { // Always create a default canvas. // Later on if the user calls createCanvas, this default one // will be replaced this.createCanvas( this._defaultCanvasSize.width, this._defaultCanvasSize.height, 'p2d', true ); // return preload functions to their normal vals if switched by preload var context = this._isGlobal ? window : this; if (typeof context.preload === 'function') { for (var f in this._preloadMethods) { context[f] = this._preloadMethods[f][f]; if (context[f] && this) { context[f] = context[f].bind(this); } } } // Short-circuit on this, in case someone used the library in "global" // mode earlier if (typeof context.setup === 'function') { context.setup(); } // unhide any hidden canvases that were created var canvases = document.getElementsByTagName('canvas'); for (var i = 0; i < canvases.length; i++) { var k = canvases[i]; if (k.dataset.hidden === 'true') { k.style.visibility = ''; delete(k.dataset.hidden); } } this._setupDone = true; }.bind(this); this._draw = function () { var now = window.performance.now(); var time_since_last = now - this._lastFrameTime; var target_time_between_frames = 1000 / this._targetFrameRate; // only draw if we really need to; don't overextend the browser. // draw if we're within 5ms of when our next frame should paint // (this will prevent us from giving up opportunities to draw // again when it's really about time for us to do so). fixes an // issue where the frameRate is too low if our refresh loop isn't // in sync with the browser. note that we have to draw once even // if looping is off, so we bypass the time delay if that // is the case. var epsilon = 5; if (!this._loop || time_since_last >= target_time_between_frames - epsilon) { //mandatory update values(matrixs and stack) this._setProperty('frameCount', this.frameCount + 1); this.redraw(); this._frameRate = 1000.0/(now - this._lastFrameTime); this._lastFrameTime = now; // If the user is actually using mouse module, then update // coordinates, otherwise skip. We can test this by simply // checking if any of the mouse functions are available or not. // NOTE : This reflects only in complete build or modular build. if(typeof this._updateMouseCoords !== 'undefined') { this._updateMouseCoords(); } } // get notified the next time the browser gives us // an opportunity to draw. if (this._loop) { this._requestAnimId = window.requestAnimationFrame(this._draw); } }.bind(this); this._runFrames = function() { if (this._updateInterval) { clearInterval(this._updateInterval); } }.bind(this); this._setProperty = function(prop, value) { this[prop] = value; if (this._isGlobal) { window[prop] = value; } }.bind(this); /** * Removes the entire p5 sketch. This will remove the canvas and any * elements created by p5.js. It will also stop the draw loop and unbind * any properties or methods from the window global scope. It will * leave a variable p5 in case you wanted to create a new p5 sketch. * If you like, you can set p5 = null to erase it. * @method remove * @example *
* function draw() { * ellipse(50, 50, 10, 10); * } * * function mousePressed() { * remove(); // remove whole sketch on mouse press * } *
* * @alt * nothing displayed * */ this.remove = function() { if (this._curElement) { // stop draw this._loop = false; if (this._requestAnimId) { window.cancelAnimationFrame(this._requestAnimId); } // unregister events sketch-wide for (var ev in this._events) { window.removeEventListener(ev, this._events[ev]); } // remove DOM elements created by p5, and listeners for (var i=0; i
Bezier curves were developed by French * automotive engineer Pierre Bezier, and are commonly used in computer * graphics to define gently sloping curves. See also curve(). * * @method bezier * @param {Number} x1 x-coordinate for the first anchor point * @param {Number} y1 y-coordinate for the first anchor point * @param {Number} x2 x-coordinate for the first control point * @param {Number} y2 y-coordinate for the first control point * @param {Number} x3 x-coordinate for the second control point * @param {Number} y3 y-coordinate for the second control point * @param {Number} x4 x-coordinate for the second anchor point * @param {Number} y4 y-coordinate for the second anchor point * @return {p5} the p5 object * @example *
* * noFill(); * stroke(255, 102, 0); * line(85, 20, 10, 10); * line(90, 90, 15, 80); * stroke(0, 0, 0); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * *
* @alt * stretched black s-shape in center with orange lines extending from end points. * stretched black s-shape with 10 5x5 white ellipses along the shape. * stretched black s-shape with 7 5x5 ellipses and orange lines along the shape. * stretched black s-shape with 17 small orange lines extending from under shape. * horseshoe shape with orange ends facing left and black curved center. * horseshoe shape with orange ends facing left and black curved center. * Line shaped like right-facing arrow,points move with mouse-x and warp shape. * horizontal line that hooks downward on the right and 13 5x5 ellipses along it. * right curving line mid-right of canvas with 7 short lines radiating from it. */ /** * @method bezier * @param {Number} z1 z-coordinate for the first anchor point * @param {Number} z2 z-coordinate for the first control point * @param {Number} z3 z-coordinate for the first anchor point * @param {Number} z4 z-coordinate for the first control point * @chainable * @example *
* *background(0, 0, 0); *noFill(); *stroke(255); *bezier(250,250,0, 100,100,0, 100,0,0, 0,100,0); * *
*/ p5.prototype.bezier = function() { var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } if (!this._renderer._doStroke && !this._renderer._doFill) { return this; } if (this._renderer.isP3D){ args.push(bezierDetail);//adding value of bezier detail to the args array this._renderer.bezier(args); } else{ this._renderer.bezier(args[0],args[1], args[2],args[3], args[4],args[5], args[6],args[7]); } return this; }; /** * Sets the resolution at which Beziers display. * * The default value is 20. * * @param {Number} detail resolution of the curves * @chainable * @example *
* * background(204); * bezierDetail(50); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * *
* * @alt * stretched black s-shape with 7 5x5 ellipses and orange lines along the shape. * */ p5.prototype.bezierDetail = function(d) { bezierDetail = d; return this; }; /** * Evaluates the Bezier at position t for points a, b, c, d. * The parameters a and d are the first and last points * on the curve, and b and c are the control points. * The final parameter t varies between 0 and 1. * This can be done once with the x coordinates and a second time * with the y coordinates to get the location of a bezier curve at t. * * @method bezierPoint * @param {Number} a coordinate of first point on the curve * @param {Number} b coordinate of first control point * @param {Number} c coordinate of second control point * @param {Number} d coordinate of second point on the curve * @param {Number} t value between 0 and 1 * @return {Number} the value of the Bezier at position t * @example *
* * noFill(); * x1 = 85, x2 = 10, x3 = 90, x4 = 15; * y1 = 20, y2 = 10, y3 = 90, y4 = 80; * bezier(x1, y1, x2, y2, x3, y3, x4, y4); * fill(255); * steps = 10; * for (i = 0; i <= steps; i++) { * t = i / steps; * x = bezierPoint(x1, x2, x3, x4, t); * y = bezierPoint(y1, y2, y3, y4, t); * ellipse(x, y, 5, 5); * } * *
* * @alt * stretched black s-shape with 17 small orange lines extending from under shape. * */ p5.prototype.bezierPoint = function(a, b, c, d, t) { var adjustedT = 1-t; return Math.pow(adjustedT,3)*a + 3*(Math.pow(adjustedT,2))*t*b + 3*adjustedT*Math.pow(t,2)*c + Math.pow(t,3)*d; }; /** * Evaluates the tangent to the Bezier at position t for points a, b, c, d. * The parameters a and d are the first and last points * on the curve, and b and c are the control points. * The final parameter t varies between 0 and 1. * * @method bezierTangent * @param {Number} a coordinate of first point on the curve * @param {Number} b coordinate of first control point * @param {Number} c coordinate of second control point * @param {Number} d coordinate of second point on the curve * @param {Number} t value between 0 and 1 * @return {Number} the tangent at position t * @example *
* * noFill(); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * steps = 6; * fill(255); * for (i = 0; i <= steps; i++) { * t = i / steps; * // Get the location of the point * x = bezierPoint(85, 10, 90, 15, t); * y = bezierPoint(20, 10, 90, 80, t); * // Get the tangent points * tx = bezierTangent(85, 10, 90, 15, t); * ty = bezierTangent(20, 10, 90, 80, t); * // Calculate an angle from the tangent points * a = atan2(ty, tx); * a += PI; * stroke(255, 102, 0); * line(x, y, cos(a)*30 + x, sin(a)*30 + y); * // The following line of code makes a line * // inverse of the above line * //line(x, y, cos(a)*-30 + x, sin(a)*-30 + y); * stroke(0); * ellipse(x, y, 5, 5); * } * *
* *
* * noFill(); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * stroke(255, 102, 0); * steps = 16; * for (i = 0; i <= steps; i++) { * t = i / steps; * x = bezierPoint(85, 10, 90, 15, t); * y = bezierPoint(20, 10, 90, 80, t); * tx = bezierTangent(85, 10, 90, 15, t); * ty = bezierTangent(20, 10, 90, 80, t); * a = atan2(ty, tx); * a -= HALF_PI; * line(x, y, cos(a)*8 + x, sin(a)*8 + y); * } * *
* * @alt * s-shaped line with 17 short orange lines extending from underside of shape * */ p5.prototype.bezierTangent = function(a, b, c, d, t) { var adjustedT = 1-t; return 3*d*Math.pow(t,2) - 3*c*Math.pow(t,2) + 6*c*adjustedT*t - 6*b*adjustedT*t + 3*b*Math.pow(adjustedT,2) - 3*a*Math.pow(adjustedT,2); }; /** * Draws a curved line on the screen between two points, given as the * middle four parameters. The first two parameters are a control point, as * if the curve came from this point even though it's not drawn. The last * two parameters similarly describe the other control point.

* Longer curves can be created by putting a series of curve() functions * together or using curveVertex(). An additional function called * curveTightness() provides control for the visual quality of the curve. * The curve() function is an implementation of Catmull-Rom splines. * * @method curve * @param {Number} x1 x-coordinate for the beginning control point * @param {Number} y1 y-coordinate for the beginning control point * @param {Number} x2 x-coordinate for the first point * @param {Number} y2 y-coordinate for the first point * @param {Number} x3 x-coordinate for the second point * @param {Number} y3 y-coordinate for the second point * @param {Number} x4 x-coordinate for the ending control point * @param {Number} y4 y-coordinate for the ending control point * @return {p5} the p5 object * @example *
* * noFill(); * stroke(255, 102, 0); * curve(5, 26, 5, 26, 73, 24, 73, 61); * stroke(0); * curve(5, 26, 73, 24, 73, 61, 15, 65); * stroke(255, 102, 0); * curve(73, 24, 73, 61, 15, 65, 15, 65); * *
*
* * // Define the curve points as JavaScript objects * p1 = {x: 5, y: 26}, p2 = {x: 73, y: 24} * p3 = {x: 73, y: 61}, p4 = {x: 15, y: 65} * noFill(); * stroke(255, 102, 0); * curve(p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y) * stroke(0); * curve(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y) * stroke(255, 102, 0); * curve(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, p4.x, p4.y) * *
* * @alt * horseshoe shape with orange ends facing left and black curved center. * horseshoe shape with orange ends facing left and black curved center. * */ /** * @method curve * @param {Number} z1 z-coordinate for the beginning control point * @param {Number} z2 z-coordinate for the first point * @param {Number} z3 z-coordinate for the second point * @param {Number} z4 z-coordinate for the ending control point * @chainable * @example *
* * noFill(); * stroke(255, 102, 0); * curve(5,26,0, 5,26,0, 73,24,0, 73,61,0); * stroke(0); * curve(5,26,0, 73,24,0, 73,61,0, 15,65,0); * stroke(255, 102, 0); * curve(73,24,0, 73,61,0, 15,65,0, 15,65,0); * *
* * @alt * curving black and orange lines. */ p5.prototype.curve = function() { var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } if (!this._renderer._doStroke) { return this; } if (this._renderer.isP3D){ args.push(curveDetail); this._renderer.curve(args); } else{ this._renderer.curve(args[0],args[1], args[2],args[3], args[4],args[5], args[6],args[7]); } return this; }; /** * Sets the resolution at which curves display. * * The default value is 20. * * @param {Number} resolution of the curves * @chainable * @example *
* * background(204); * curveDetail(20); * curve(5, 26, 5, 26, 73, 24, 73, 61); * *
* * @alt * white arch shape in top-mid canvas. * */ p5.prototype.curveDetail = function(d) { curveDetail = d; return this; }; /** * Modifies the quality of forms created with curve() and curveVertex(). * The parameter tightness determines how the curve fits to the vertex * points. The value 0.0 is the default value for tightness (this value * defines the curves to be Catmull-Rom splines) and the value 1.0 connects * all the points with straight lines. Values within the range -5.0 and 5.0 * will deform the curves but will leave them recognizable and as values * increase in magnitude, they will continue to deform. * * @method curveTightness * @param {Number} amount of deformation from the original vertices * @chainable * @example *
* * // Move the mouse left and right to see the curve change * * function setup() { * createCanvas(100, 100); * noFill(); * } * * function draw() { * background(204); * var t = map(mouseX, 0, width, -5, 5); * curveTightness(t); * beginShape(); * curveVertex(10, 26); * curveVertex(10, 26); * curveVertex(83, 24); * curveVertex(83, 61); * curveVertex(25, 65); * curveVertex(25, 65); * endShape(); * } * *
* * @alt * Line shaped like right-facing arrow,points move with mouse-x and warp shape. */ p5.prototype.curveTightness = function (t) { this._renderer._curveTightness = t; }; /** * Evaluates the curve at position t for points a, b, c, d. * The parameter t varies between 0 and 1, a and d are points * on the curve, and b and c are the control points. * This can be done once with the x coordinates and a second time * with the y coordinates to get the location of a curve at t. * * @method curvePoint * @param {Number} a coordinate of first point on the curve * @param {Number} b coordinate of first control point * @param {Number} c coordinate of second control point * @param {Number} d coordinate of second point on the curve * @param {Number} t value between 0 and 1 * @return {Number} bezier value at position t * @example *
* * noFill(); * curve(5, 26, 5, 26, 73, 24, 73, 61); * curve(5, 26, 73, 24, 73, 61, 15, 65); * fill(255); * ellipseMode(CENTER); * steps = 6; * for (i = 0; i <= steps; i++) { * t = i / steps; * x = curvePoint(5, 5, 73, 73, t); * y = curvePoint(26, 26, 24, 61, t); * ellipse(x, y, 5, 5); * x = curvePoint(5, 73, 73, 15, t); * y = curvePoint(26, 24, 61, 65, t); * ellipse(x, y, 5, 5); * } * *
* *line hooking down to right-bottom with 13 5x5 white ellipse points */ p5.prototype.curvePoint = function(a, b, c, d, t) { var t3 = t*t*t, t2 = t*t, f1 = -0.5 * t3 + t2 - 0.5 * t, f2 = 1.5 * t3 - 2.5 * t2 + 1.0, f3 = -1.5 * t3 + 2.0 * t2 + 0.5 * t, f4 = 0.5 * t3 - 0.5 * t2; return a*f1 + b*f2 + c*f3 + d*f4; }; /** * Evaluates the tangent to the curve at position t for points a, b, c, d. * The parameter t varies between 0 and 1, a and d are points on the curve, * and b and c are the control points. * * @method curveTangent * @param {Number} a coordinate of first point on the curve * @param {Number} b coordinate of first control point * @param {Number} c coordinate of second control point * @param {Number} d coordinate of second point on the curve * @param {Number} t value between 0 and 1 * @return {Number} the tangent at position t * @example *
* * noFill(); * curve(5, 26, 73, 24, 73, 61, 15, 65); * steps = 6; * for (i = 0; i <= steps; i++) { * t = i / steps; * x = curvePoint(5, 73, 73, 15, t); * y = curvePoint(26, 24, 61, 65, t); * //ellipse(x, y, 5, 5); * tx = curveTangent(5, 73, 73, 15, t); * ty = curveTangent(26, 24, 61, 65, t); * a = atan2(ty, tx); * a -= PI/2.0; * line(x, y, cos(a)*8 + x, sin(a)*8 + y); * } * *
* * @alt *right curving line mid-right of canvas with 7 short lines radiating from it. */ p5.prototype.curveTangent = function(a, b,c, d, t) { var t2 = t*t, f1 = (-3*t2)/2 + 2*t - 0.5, f2 = (9*t2)/2 - 5*t, f3 = (-9*t2)/2 + 4*t + 0.5, f4 = (3*t2)/2 - t; return a*f1 + b*f2 + c*f3 + d*f4; }; module.exports = p5; },{"./core":45,"./error_helpers":48}],47:[function(_dereq_,module,exports){ /** * @module Environment * @submodule Environment * @for p5 * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('./core'); var C = _dereq_('./constants'); var standardCursors = [C.ARROW, C.CROSS, C.HAND, C.MOVE, C.TEXT, C.WAIT]; p5.prototype._frameRate = 0; p5.prototype._lastFrameTime = window.performance.now(); p5.prototype._targetFrameRate = 60; var _windowPrint = window.print; if (window.console && console.log) { /** * The print() function writes to the console area of your browser. * This function is often helpful for looking at the data a program is * producing. This function creates a new line of text for each call to * the function. Individual elements can be * separated with quotes ("") and joined with the addition operator (+). *

* While print() is similar to console.log(), it does not directly map to * it in order to simulate easier to understand behavior than * console.log(). Due to this, it is slower. For fastest results, use * console.log(). * * @method print * @param {Any} contents any combination of Number, String, Object, Boolean, * Array to print * @example *
* var x = 10; * print("The value of x is " + x); * // prints "The value of x is 10" *
* @alt * default grey canvas */ // Converts passed args into a string and then parses that string to // simulate synchronous behavior. This is a hack and is gross. // Since this will not work on all objects, particularly circular // structures, simply console.log() on error. p5.prototype.print = function(args) { try { if (arguments.length === 0) { _windowPrint(); } else if (arguments.length > 1) { console.log.apply(console, arguments); } else { var newArgs = JSON.parse(JSON.stringify(args)); if (JSON.stringify(newArgs)==='{}'){ console.log(args); } else { console.log(newArgs); } } } catch(err) { console.log(args); } }; } else { p5.prototype.print = function() {}; } /** * The system variable frameCount contains the number of frames that have * been displayed since the program started. Inside setup() the value is 0, * after the first iteration of draw it is 1, etc. * * @property {Number} frameCount * @readOnly * @example *
* function setup() { * frameRate(30); * textSize(20); * textSize(30); * textAlign(CENTER); * } * * function draw() { * background(200); * text(frameCount, width/2, height/2); * } *
* * @alt * numbers rapidly counting upward with frame count set to 30. * */ p5.prototype.frameCount = 0; /** * Confirms if the window a p5.js program is in is "focused," meaning that * the sketch will accept mouse or keyboard input. This variable is * "true" if the window is focused and "false" if not. * * @property {Boolean} focused * @readOnly * @example *
* // To demonstrate, put two windows side by side. * // Click on the window that the p5 sketch isn't in! * function draw() { * background(200); * noStroke(); * fill(0, 200, 0); * ellipse(25, 25, 50, 50); * * if (!focused) { // or "if (focused === false)" * stroke(200,0,0); * line(0, 0, 100, 100); * line(100, 0, 0, 100); * } * } *
* * @alt * green 50x50 ellipse at top left. Red X covers canvas when page focus changes * */ p5.prototype.focused = (document.hasFocus()); /** * Sets the cursor to a predefined symbol or an image, or makes it visible * if already hidden. If you are trying to set an image as the cursor, the * recommended size is 16x16 or 32x32 pixels. It is not possible to load an * image as the cursor if you are exporting your program for the Web, and not * all MODES work with all browsers. The values for parameters x and y must * be less than the dimensions of the image. * * @method cursor * @param {String|Constant} type either ARROW, CROSS, HAND, MOVE, TEXT, or * WAIT, or path for image * @param {Number} [x] the horizontal active spot of the cursor * @param {Number} [y] the vertical active spot of the cursor * @example *
* // Move the mouse left and right across the image * // to see the cursor change from a cross to a hand * function draw() { * line(width/2, 0, width/2, height); * if (mouseX < 50) { * cursor(CROSS); * } else { * cursor(HAND); * } * } *
* * @alt * horizontal line divides canvas. cursor on left is a cross, right is hand. * */ p5.prototype.cursor = function(type, x, y) { var cursor = 'auto'; var canvas = this._curElement.elt; if (standardCursors.indexOf(type) > -1) { // Standard css cursor cursor = type; } else if (typeof type === 'string') { var coords = ''; if (x && y && (typeof x === 'number' && typeof y === 'number')) { // Note that x and y values must be unit-less positive integers < 32 // https://developer.mozilla.org/en-US/docs/Web/CSS/cursor coords = x + ' ' + y; } if ((type.substring(0, 7) === 'http://') || (type.substring(0, 8) === 'https://')) { // Image (absolute url) cursor = 'url(' + type + ') ' + coords + ', auto'; } else if (/\.(cur|jpg|jpeg|gif|png|CUR|JPG|JPEG|GIF|PNG)$/.test(type)) { // Image file (relative path) - Separated for performance reasons cursor = 'url(' + type + ') ' + coords + ', auto'; } else { // Any valid string for the css cursor property cursor = type; } } canvas.style.cursor = cursor; }; /** * Specifies the number of frames to be displayed every second. For example, * the function call frameRate(30) will attempt to refresh 30 times a second. * If the processor is not fast enough to maintain the specified rate, the * frame rate will not be achieved. Setting the frame rate within setup() is * recommended. The default rate is 60 frames per second. This is the same as * setFrameRate(val). *

* Calling frameRate() with no arguments returns the current framerate. The * draw function must run at least once before it will return a value. This * is the same as getFrameRate(). *

* Calling frameRate() with arguments that are not of the type numbers * or are non positive also returns current framerate. * * @method frameRate * @param {Number} fps number of frames to be displayed every second * @chainable */ /** * @method frameRate * @return {Number} current frameRate * @example * *
* var rectX = 0; * var fr = 30; //starting FPS * var clr; * * function setup() { * background(200); * frameRate(fr); // Attempt to refresh at starting FPS * clr = color(255,0,0); * } * * function draw() { * background(200); * rectX = rectX += 1; // Move Rectangle * * if (rectX >= width) { // If you go off screen. * if (fr == 30) { * clr = color(0,0,255); * fr = 10; * frameRate(fr); // make frameRate 10 FPS * } else { * clr = color(255,0,0); * fr = 30; * frameRate(fr); // make frameRate 30 FPS * } * rectX = 0; * } * fill(clr); * rect(rectX, 40, 20,20); * } *
* * @alt * blue rect moves left to right, followed by red rect moving faster. Loops. * */ p5.prototype.frameRate = function(fps) { if (typeof fps !== 'number' || fps < 0) { return this._frameRate; } else { this._setProperty('_targetFrameRate', fps); this._runFrames(); return this; } }; /** * Returns the current framerate. * * @return {Number} current frameRate */ p5.prototype.getFrameRate = function() { return this.frameRate(); }; /** * Specifies the number of frames to be displayed every second. For example, * the function call frameRate(30) will attempt to refresh 30 times a second. * If the processor is not fast enough to maintain the specified rate, the * frame rate will not be achieved. Setting the frame rate within setup() is * recommended. The default rate is 60 frames per second. * * Calling frameRate() with no arguments returns the current framerate. * * @param {Number} [fps] number of frames to be displayed every second */ p5.prototype.setFrameRate = function(fps) { return this.frameRate(fps); }; /** * Hides the cursor from view. * * @method noCursor * @example *
* function setup() { * noCursor(); * } * * function draw() { * background(200); * ellipse(mouseX, mouseY, 10, 10); * } *
* * * @alt * cursor becomes 10x 10 white ellipse the moves with mouse x and y. * */ p5.prototype.noCursor = function() { this._curElement.elt.style.cursor = 'none'; }; /** * System variable that stores the width of the entire screen display. This * is used to run a full-screen program on any display size. * * @property {Number} displayWidth * @readOnly * @example *
* createCanvas(displayWidth, displayHeight); *
* * @alt * cursor becomes 10x 10 white ellipse the moves with mouse x and y. * */ p5.prototype.displayWidth = screen.width; /** * System variable that stores the height of the entire screen display. This * is used to run a full-screen program on any display size. * * @property {Number} displayHeight * @readOnly * @example *
* createCanvas(displayWidth, displayHeight); *
* * @alt * no display. * */ p5.prototype.displayHeight = screen.height; /** * System variable that stores the width of the inner window, it maps to * window.innerWidth. * * @property {Number} windowWidth * @readOnly * @example *
* createCanvas(windowWidth, windowHeight); *
* * @alt * no display. * */ p5.prototype.windowWidth = getWindowWidth(); /** * System variable that stores the height of the inner window, it maps to * window.innerHeight. * * @property {Number} windowHeight * @readOnly * @example *
* createCanvas(windowWidth, windowHeight); *
*@alt * no display. * */ p5.prototype.windowHeight = getWindowHeight(); /** * The windowResized() function is called once every time the browser window * is resized. This is a good place to resize the canvas or do any other * adjustments to accommodate the new window size. * * @method windowResized * @example *
* function setup() { * createCanvas(windowWidth, windowHeight); * } * * function draw() { * background(0, 100, 200); * } * * function windowResized() { * resizeCanvas(windowWidth, windowHeight); * } *
* @alt * no display. */ p5.prototype._onresize = function(e){ this._setProperty('windowWidth', getWindowWidth()); this._setProperty('windowHeight', getWindowHeight()); var context = this._isGlobal ? window : this; var executeDefault; if (typeof context.windowResized === 'function') { executeDefault = context.windowResized(e); if (executeDefault !== undefined && !executeDefault) { e.preventDefault(); } } }; function getWindowWidth() { return window.innerWidth || document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth || 0; } function getWindowHeight() { return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body && document.body.clientHeight || 0; } /** * System variable that stores the width of the drawing canvas. This value * is set by the first parameter of the createCanvas() function. * For example, the function call createCanvas(320, 240) sets the width * variable to the value 320. The value of width defaults to 100 if * createCanvas() is not used in a program. * * @property {Number} width * @readOnly */ p5.prototype.width = 0; /** * System variable that stores the height of the drawing canvas. This value * is set by the second parameter of the createCanvas() function. For * example, the function call createCanvas(320, 240) sets the height * variable to the value 240. The value of height defaults to 100 if * createCanvas() is not used in a program. * * @property {Number} height * @readOnly */ p5.prototype.height = 0; /** * If argument is given, sets the sketch to fullscreen or not based on the * value of the argument. If no argument is given, returns the current * fullscreen state. Note that due to browser restrictions this can only * be called on user input, for example, on mouse press like the example * below. * * @method fullscreen * @param {Boolean} [val] whether the sketch should be in fullscreen mode * or not * @return {Boolean} current fullscreen state * @example *
* * // Clicking in the box toggles fullscreen on and off. * function setup() { * background(200); * } * function mousePressed() { * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { * var fs = fullscreen(); * fullscreen(!fs); * } * } * *
* * @alt * no display. * */ p5.prototype.fullscreen = function(val) { // no arguments, return fullscreen or not if (typeof val === 'undefined') { return document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement; } else { // otherwise set to fullscreen or not if (val) { launchFullscreen(document.documentElement); } else { exitFullscreen(); } } }; /** * Sets the pixel scaling for high pixel density displays. By default * pixel density is set to match display density, call pixelDensity(1) * to turn this off. Calling pixelDensity() with no arguments returns * the current pixel density of the sketch. * * * @method pixelDensity * @param {Number} [val] whether or how much the sketch should scale * @returns {Number} current pixel density of the sketch * @example *
* * function setup() { * pixelDensity(1); * createCanvas(100, 100); * background(200); * ellipse(width/2, height/2, 50, 50); * } * *
*
* * function setup() { * pixelDensity(3.0); * createCanvas(100, 100); * background(200); * ellipse(width/2, height/2, 50, 50); * } * *
* * @alt * fuzzy 50x50 white ellipse with black outline in center of canvas. * sharp 50x50 white ellipse with black outline in center of canvas. */ p5.prototype.pixelDensity = function(val) { if (typeof val === 'number') { this._pixelDensity = val; } else { return this._pixelDensity; } this.resizeCanvas(this.width, this.height, true); }; /** * Returns the pixel density of the current display the sketch is running on. * * @method displayDensity * @returns {Number} current pixel density of the display * @example *
* * function setup() { * var density = displayDensity(); * pixelDensity(density); * createCanvas(100, 100); * background(200); * ellipse(width/2, height/2, 50, 50); * } * *
* * @alt * 50x50 white ellipse with black outline in center of canvas. */ p5.prototype.displayDensity = function() { return window.devicePixelRatio; }; function launchFullscreen(element) { var enabled = document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled; if (!enabled) { throw new Error('Fullscreen not enabled in this browser.'); } if(element.requestFullscreen) { element.requestFullscreen(); } else if(element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if(element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } else if(element.msRequestFullscreen) { element.msRequestFullscreen(); } } function exitFullscreen() { if(document.exitFullscreen) { document.exitFullscreen(); } else if(document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if(document.webkitExitFullscreen) { document.webkitExitFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } } /** * Gets the current URL. * @method getURL * @return {String} url * @example *
* * var url; * var x = 100; * * function setup() { * fill(0); * noStroke(); * url = getURL(); * } * * function draw() { * background(200); * text(url, x, height/2); * x--; * } * *
* * @alt * current url (http://p5js.org/reference/#/p5/getURL) moves right to left. * */ p5.prototype.getURL = function() { return location.href; }; /** * Gets the current URL path as an array. * @method getURLPath * @return {String[]} path components * @example *
* function setup() { * var urlPath = getURLPath(); * for (var i=0; i<urlPath.length; i++) { * text(urlPath[i], 10, i*20+20); * } * } *
* * @alt *no display * */ p5.prototype.getURLPath = function() { return location.pathname.split('/').filter(function(v){return v!=='';}); }; /** * Gets the current URL params as an Object. * @method getURLParams * @return {Object} URL params * @example *
* * // Example: http://p5js.org?year=2014&month=May&day=15 * * function setup() { * var params = getURLParams(); * text(params.day, 10, 20); * text(params.month, 10, 40); * text(params.year, 10, 60); * } * *
* @alt * no display. * */ p5.prototype.getURLParams = function() { var re = /[?&]([^&=]+)(?:[&=])([^&=]+)/gim; var m; var v={}; while ((m = re.exec(location.search)) != null) { if (m.index === re.lastIndex) { re.lastIndex++; } v[m[1]]=m[2]; } return v; }; module.exports = p5; },{"./constants":44,"./core":45}],48:[function(_dereq_,module,exports){ /** * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('./core'); var doFriendlyWelcome = false; // TEMP until we get it all working LM // -- Borrowed from jQuery 1.11.3 -- var class2type = {}; var toString = class2type.toString; var names = ['Boolean', 'Number', 'String', 'Function', 'Array', 'Date', 'RegExp', 'Object', 'Error']; for (var n=0; n p5.js says: '+message+'%c'+ // '[https://github.com/processing/p5.js/wiki/Local-server]', // 'background-color:' + color + ';color:#FFF;', // 'background-color:transparent;color:' + color +';', // 'background-color:' + color + ';color:#FFF;', // 'background-color:transparent;color:' + color +';' // ); // } // else{ // console.log( // '%c> p5.js says: '+message+'%c [http://p5js.org/reference/#p5/'+func+ // ']', 'background-color:' + color + ';color:#FFF;', // 'background-color:transparent;color:' + color +';' // ); // } } var errorCases = { '0': { fileType: 'image', method: 'loadImage', message: ' hosting the image online,' }, '1': { fileType: 'XML file', method: 'loadXML' }, '2': { fileType: 'table file', method: 'loadTable' }, '3': { fileType: 'text file', method: 'loadStrings' }, '4': { fileType: 'font', method: 'loadFont', message: ' hosting the font online,' }, }; p5._friendlyFileLoadError = function (errorType, filePath) { var errorInfo = errorCases[ errorType ]; var message = 'It looks like there was a problem' + ' loading your ' + errorInfo.fileType + '.' + ' Try checking if the file path%c [' + filePath + '] %cis correct,' + (errorInfo.message || '') + ' or running a local server.'; report(message, errorInfo.method, FILE_LOAD); }; function friendlyWelcome() { // p5.js brand - magenta: #ED225D var astrixBgColor = 'transparent'; var astrixTxtColor = '#ED225D'; var welcomeBgColor = '#ED225D'; var welcomeTextColor = 'white'; console.log( '%c _ \n'+ ' /\\| |/\\ \n'+ ' \\ ` \' / \n'+ ' / , . \\ \n'+ ' \\/|_|\\/ '+ '\n\n%c> p5.js says: Welcome! '+ 'This is your friendly debugger. ' + 'To turn me off switch to using “p5.min.js”.', 'background-color:'+astrixBgColor+';color:' + astrixTxtColor +';', 'background-color:'+welcomeBgColor+';color:' + welcomeTextColor +';' ); } /** * Prints out all the colors in the color pallete with white text. * For color blindness testing. */ /* function testColors() { var str = 'A box of biscuits, a box of mixed biscuits and a biscuit mixer'; report(str, 'print', '#ED225D'); // p5.js magenta report(str, 'print', '#2D7BB6'); // p5.js blue report(str, 'print', '#EE9900'); // p5.js orange report(str, 'print', '#A67F59'); // p5.js light brown report(str, 'print', '#704F21'); // p5.js gold report(str, 'print', '#1CC581'); // auto cyan report(str, 'print', '#FF6625'); // auto orange report(str, 'print', '#79EB22'); // auto green report(str, 'print', '#B40033'); // p5.js darkened magenta report(str, 'print', '#084B7F'); // p5.js darkened blue report(str, 'print', '#945F00'); // p5.js darkened orange report(str, 'print', '#6B441D'); // p5.js darkened brown report(str, 'print', '#2E1B00'); // p5.js darkened gold report(str, 'print', '#008851'); // auto dark cyan report(str, 'print', '#C83C00'); // auto dark orange report(str, 'print', '#4DB200'); // auto dark green } */ // This is a lazily-defined list of p5 symbols that may be // misused by beginners at top-level code, outside of setup/draw. We'd like // to detect these errors and help the user by suggesting they move them // into setup/draw. // // For more details, see https://github.com/processing/p5.js/issues/1121. var misusedAtTopLevelCode = null; var FAQ_URL = 'https://github.com/processing/p5.js/wiki/' + 'Frequently-Asked-Questions' + '#why-cant-i-assign-variables-using-p5-functions-and-' + 'variables-before-setup'; function defineMisusedAtTopLevelCode() { var uniqueNamesFound = {}; var getSymbols = function(obj) { return Object.getOwnPropertyNames(obj).filter(function(name) { if (name[0] === '_') { return false; } if (name in uniqueNamesFound) { return false; } uniqueNamesFound[name] = true; return true; }).map(function(name) { var type; if (typeof(obj[name]) === 'function') { type = 'function'; } else if (name === name.toUpperCase()) { type = 'constant'; } else { type = 'variable'; } return {name: name, type: type}; }); }; misusedAtTopLevelCode = [].concat( getSymbols(p5.prototype), // At present, p5 only adds its constants to p5.prototype during // construction, which may not have happened at the time a // ReferenceError is thrown, so we'll manually add them to our list. getSymbols(_dereq_('./constants')) ); // This will ultimately ensure that we report the most specific error // possible to the user, e.g. advising them about HALF_PI instead of PI // when their code misuses the former. misusedAtTopLevelCode.sort(function(a, b) { return b.name.length - a.name.length; }); } function helpForMisusedAtTopLevelCode(e, log) { if (!log) { log = console.log.bind(console); } if (!misusedAtTopLevelCode) { defineMisusedAtTopLevelCode(); } // If we find that we're logging lots of false positives, we can // uncomment the following code to avoid displaying anything if the // user's code isn't likely to be using p5's global mode. (Note that // setup/draw are more likely to be defined due to JS function hoisting.) // //if (!('setup' in window || 'draw' in window)) { // return; //} misusedAtTopLevelCode.some(function(symbol) { // Note that while just checking for the occurrence of the // symbol name in the error message could result in false positives, // a more rigorous test is difficult because different browsers // log different messages, and the format of those messages may // change over time. // // For example, if the user uses 'PI' in their code, it may result // in any one of the following messages: // // * 'PI' is undefined (Microsoft Edge) // * ReferenceError: PI is undefined (Firefox) // * Uncaught ReferenceError: PI is not defined (Chrome) if (e.message && e.message.match('\\W?'+symbol.name+'\\W') !== null) { log('%cDid you just try to use p5.js\'s ' + symbol.name + (symbol.type === 'function' ? '() ' : ' ') + symbol.type + '? If so, you may want to ' + 'move it into your sketch\'s setup() function.\n\n' + 'For more details, see: ' + FAQ_URL, 'color: #B40033' /* Dark magenta */); return true; } }); } // Exposing this primarily for unit testing. p5.prototype._helpForMisusedAtTopLevelCode = helpForMisusedAtTopLevelCode; if (document.readyState !== 'complete') { window.addEventListener('error', helpForMisusedAtTopLevelCode, false); // Our job is only to catch ReferenceErrors that are thrown when // global (non-instance mode) p5 APIs are used at the top-level // scope of a file, so we'll unbind our error listener now to make // sure we don't log false positives later. window.addEventListener('load', function() { window.removeEventListener('error', helpForMisusedAtTopLevelCode, false); }); } module.exports = p5; },{"./constants":44,"./core":45}],49:[function(_dereq_,module,exports){ var p5 = _dereq_('../core/core'); /** * _globalInit * * TODO: ??? * if sketch is on window * assume "global" mode * and instantiate p5 automatically * otherwise do nothing * * @return {Undefined} */ var _globalInit = function() { if (!window.PHANTOMJS && !window.mocha) { // If there is a setup or draw function on the window // then instantiate p5 in "global" mode if(((window.setup && typeof window.setup === 'function') || (window.draw && typeof window.draw === 'function')) && !p5.instance) { new p5(); } } }; // TODO: ??? if (document.readyState === 'complete') { _globalInit(); } else { window.addEventListener('load', _globalInit , false); } },{"../core/core":45}],50:[function(_dereq_,module,exports){ /** * @module DOM * @submodule DOM * @for p5.Element */ var p5 = _dereq_('./core'); /** * Base class for all elements added to a sketch, including canvas, * graphics buffers, and other HTML elements. Methods in blue are * included in the core functionality, methods in brown are added * with the p5.dom * library. * It is not called directly, but p5.Element * objects are created by calling createCanvas, createGraphics, * or in the p5.dom library, createDiv, createImg, createInput, etc. * * @class p5.Element * @constructor * @param {String} elt DOM node that is wrapped * @param {p5} [pInst] pointer to p5 instance */ p5.Element = function(elt, pInst) { /** * Underlying HTML element. All normal HTML methods can be called on this. * * @property elt * @readOnly */ this.elt = elt; this._pInst = pInst; this._events = {}; this.width = this.elt.offsetWidth; this.height = this.elt.offsetHeight; }; /** * * Attaches the element to the parent specified. A way of setting * the container for the element. Accepts either a string ID, DOM * node, or p5.Element. If no arguments given, parent node is returned. * For more ways to position the canvas, see the * * positioning the canvas wiki page. * * @method parent * @param {String|p5.Element|Object} parent the ID, DOM node, or p5.Element * of desired parent element * @chainable */ /** * @method parent * @return {p5.Element} * * @example *
* // in the html file: * <div id="myContainer"></div> * // in the js file: * var cnv = createCanvas(100, 100); * cnv.parent("myContainer"); *
*
* var div0 = createDiv('this is the parent'); * var div1 = createDiv('this is the child'); * div1.parent(div0); // use p5.Element *
*
* var div0 = createDiv('this is the parent'); * div0.id('apples'); * var div1 = createDiv('this is the child'); * div1.parent('apples'); // use id *
*
* var elt = document.getElementById('myParentDiv'); * var div1 = createDiv('this is the child'); * div1.parent(elt); // use element from page *
* * @alt * no display. * */ p5.Element.prototype.parent = function(p) { if (arguments.length === 0){ return this.elt.parentNode; } else { if (typeof p === 'string') { if (p[0] === '#') { p = p.substring(1); } p = document.getElementById(p); } else if (p instanceof p5.Element) { p = p.elt; } p.appendChild(this.elt); return this; } }; /** * * Sets the ID of the element. If no ID argument is passed in, it instead * returns the current ID of the element. * * @method id * @param {String} id ID of the element * @chainable */ /** * @method id * @return {String} the id of the element * * @example *
* function setup() { * var cnv = createCanvas(100, 100); * // Assigns a CSS selector ID to * // the canvas element. * cnv.id("mycanvas"); * } *
* * @alt * no display. * */ p5.Element.prototype.id = function(id) { if (arguments.length === 0) { return this.elt.id; } else { this.elt.id = id; this.width = this.elt.offsetWidth; this.height = this.elt.offsetHeight; return this; } }; /** * * Adds given class to the element. If no class argument is passed in, it * instead returns a string containing the current class(es) of the element. * * @method class * @param {String} class class to add * @chainable */ /** * @method class * @return {String} the class of the element */ p5.Element.prototype.class = function(c) { if (arguments.length === 0) { return this.elt.className; } else { this.elt.className = c; return this; } }; /** * The .mousePressed() function is called once after every time a * mouse button is pressed over the element. This can be used to * attach element specific event listeners. * * @method mousePressed * @param {function} fxn function to be fired when mouse is * pressed over the element. * @chainable * @example *
* var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mousePressed(changeGray); // attach listener for * // canvas click only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width/2, height/2, d, d); * } * * // this function fires with any click anywhere * function mousePressed() { * d = d + 10; * } * * // this function fires only when cnv is clicked * function changeGray() { * g = random(0, 255); * } *
* * @alt * no display. * */ p5.Element.prototype.mousePressed = function (fxn) { attachListener('mousedown', fxn, this); attachListener('touchstart', fxn, this); return this; }; /** * The .doubleClicked() function is called once after every time a * mouse button is pressed twice over the element. This can be used to * attach element and action specific event listeners. * * @method doubleClicked * @param {Function} fxn function to be fired when mouse is * pressed over the element. * @return {p5.Element} * @example *
* var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.doubleClicked(changeGray); // attach listener for * // canvas click only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width/2, height/2, d, d); * } * * // this function fires with any double click anywhere * function doubleClicked() { * d = d + 10; * } * * // this function fires only when cnv is clicked * function changeGray() { * g = random(0, 255); * } *
* * @alt * no display. * */ p5.Element.prototype.doubleClicked = function (fxn) { attachListener('doubleClicked', fxn, this); return this; }; /** * The .mouseWheel() function is called once after every time a * mouse wheel is scrolled over the element. This can be used to * attach element specific event listeners. *

* The function accepts a callback function as argument which will be executed * when the `wheel` event is triggered on the element, the callback function is * passed one argument `event`. The `event.deltaY` property returns negative * values if the mouse wheel is rotated up or away from the user and positive * in the other direction. The `event.deltaX` does the same as `event.deltaY` * except it reads the horizontal wheel scroll of the mouse wheel. *

* On OS X with "natural" scrolling enabled, the `event.deltaY` values are * reversed. * * @method mouseWheel * @param {function} fxn function to be fired when mouse wheel is * scrolled over the element. * @chainable * @example *
* var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseWheel(changeSize); // attach listener for * // activity on canvas only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width/2, height/2, d, d); * } * * // this function fires with mousewheel movement * // anywhere on screen * function mouseWheel() { * g = g + 10; * } * * // this function fires with mousewheel movement * // over canvas only * function changeSize(event) { * if (event.deltaY > 0) { * d = d + 10; * } else { * d = d - 10; * } * } *
* * * @alt * no display. * */ p5.Element.prototype.mouseWheel = function (fxn) { attachListener('wheel', fxn, this); return this; }; /** * The .mouseReleased() function is called once after every time a * mouse button is released over the element. This can be used to * attach element specific event listeners. * * @method mouseReleased * @param {function} fxn function to be fired when mouse is * released over the element. * @chainable * @example *
* var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseReleased(changeGray); // attach listener for * // activity on canvas only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width/2, height/2, d, d); * } * * // this function fires after the mouse has been * // released * function mouseReleased() { * d = d + 10; * } * * // this function fires after the mouse has been * // released while on canvas * function changeGray() { * g = random(0, 255); * } *
* * * @alt * no display. * */ p5.Element.prototype.mouseReleased = function (fxn) { attachListener('mouseup', fxn, this); attachListener('touchend', fxn, this); return this; }; /** * The .mouseClicked() function is called once after a mouse button is * pressed and released over the element. This can be used to * attach element specific event listeners. * * @method mouseClicked * @param {function} fxn function to be fired when mouse is * clicked over the element. * @chainable * @example *
* * var cnv; * var d; * var g; * * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseClicked(changeGray); // attach listener for * // activity on canvas only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width/2, height/2, d, d); * } * * // this function fires after the mouse has been * // clicked anywhere * function mouseClicked() { * d = d + 10; * } * * // this function fires after the mouse has been * // clicked on canvas * function changeGray() { * g = random(0, 255); * } * *
* * @alt * no display. * */ p5.Element.prototype.mouseClicked = function (fxn) { attachListener('click', fxn, this); return this; }; /** * The .mouseMoved() function is called once every time a * mouse moves over the element. This can be used to attach an * element specific event listener. * * @method mouseMoved * @param {function} fxn function to be fired when mouse is * moved over the element. * @chainable * @example *
* var cnv; * var d = 30; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseMoved(changeSize); // attach listener for * // activity on canvas only * d = 10; * g = 100; * } * * function draw() { * background(g); * fill(200); * ellipse(width/2, height/2, d, d); * } * * // this function fires when mouse moves anywhere on * // page * function mouseMoved() { * g = g + 5; * if (g > 255) { * g = 0; * } * } * * // this function fires when mouse moves over canvas * function changeSize() { * d = d + 2; * if (d > 100) { * d = 0; * } * } *
* * * @alt * no display. * */ p5.Element.prototype.mouseMoved = function (fxn) { attachListener('mousemove', fxn, this); attachListener('touchmove', fxn, this); return this; }; /** * The .mouseOver() function is called once after every time a * mouse moves onto the element. This can be used to attach an * element specific event listener. * * @method mouseOver * @param {function} fxn function to be fired when mouse is * moved over the element. * @chainable * @example *
* var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseOver(changeGray); * d = 10; * } * * function draw() { * ellipse(width/2, height/2, d, d); * } * * function changeGray() { * d = d + 10; * if (d > 100) { * d = 0; * } * } *
* * * @alt * no display. * */ p5.Element.prototype.mouseOver = function (fxn) { attachListener('mouseover', fxn, this); return this; }; /** * The .changed() function is called when the value of an * element is changed. * This can be used to attach an element specific event listener. * * @method changed * @param {function} fxn function to be fired when the value of an * element changes. * @chainable * @example *
* var sel; * * function setup() { * textAlign(CENTER); * background(200); * sel = createSelect(); * sel.position(10, 10); * sel.option('pear'); * sel.option('kiwi'); * sel.option('grape'); * sel.changed(mySelectEvent); * } * * function mySelectEvent() { * var item = sel.value(); * background(200); * text("it's a "+item+"!", 50, 50); * } *
*
* var checkbox; * var cnv; * * function setup() { * checkbox = createCheckbox(" fill"); * checkbox.changed(changeFill); * cnv = createCanvas(100, 100); * cnv.position(0, 30); * noFill(); * } * * function draw() { * background(200); * ellipse(50, 50, 50, 50); * } * * function changeFill() { * if (checkbox.checked()) { * fill(0); * } else { * noFill(); * } * } *
* * @alt * dropdown: pear, kiwi, grape. When selected text "its a" + selection shown. * */ p5.Element.prototype.changed = function (fxn) { attachListener('change', fxn, this); return this; }; /** * The .input() function is called when any user input is * detected with an element. The input event is often used * to detect keystrokes in a input element, or changes on a * slider element. This can be used to attach an element specific * event listener. * * @method input * @param {function} fxn function to be fired on user input. * @chainable * @example *
* // Open your console to see the output * function setup() { * var inp = createInput(''); * inp.input(myInputEvent); * } * * function myInputEvent() { * console.log('you are typing: ', this.value()); * } *
* * @alt * no display. * */ p5.Element.prototype.input = function (fxn) { attachListener('input', fxn, this); return this; }; /** * The .mouseOut() function is called once after every time a * mouse moves off the element. This can be used to attach an * element specific event listener. * * @method mouseOut * @param {function} fxn function to be fired when mouse is * moved off the element. * @chainable * @example *
* var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseOut(changeGray); * d = 10; * } * * function draw() { * ellipse(width/2, height/2, d, d); * } * * function changeGray() { * d = d + 10; * if (d > 100) { * d = 0; * } * } *
* * @alt * no display. * */ p5.Element.prototype.mouseOut = function (fxn) { attachListener('mouseout', fxn, this); return this; }; /** * The .touchStarted() function is called once after every time a touch is * registered. This can be used to attach element specific event listeners. * * @method touchStarted * @param {function} fxn function to be fired when touch is * started over the element. * @chainable * @example *
* var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.touchStarted(changeGray); // attach listener for * // canvas click only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width/2, height/2, d, d); * } * * // this function fires with any touch anywhere * function touchStarted() { * d = d + 10; * } * * // this function fires only when cnv is clicked * function changeGray() { * g = random(0, 255); * } *
* * @alt * no display. * */ p5.Element.prototype.touchStarted = function (fxn) { attachListener('touchstart', fxn, this); attachListener('mousedown', fxn, this); return this; }; /** * The .touchMoved() function is called once after every time a touch move is * registered. This can be used to attach element specific event listeners. * * @method touchMoved * @param {function} fxn function to be fired when touch is moved * over the element. * @chainable * @example *
* var cnv; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.touchMoved(changeGray); // attach listener for * // canvas click only * g = 100; * } * * function draw() { * background(g); * } * * // this function fires only when cnv is clicked * function changeGray() { * g = random(0, 255); * } *
* * @alt * no display. * */ p5.Element.prototype.touchMoved = function (fxn) { attachListener('touchmove', fxn, this); attachListener('mousemove', fxn, this); return this; }; /** * The .touchEnded() function is called once after every time a touch is * registered. This can be used to attach element specific event listeners. * * @method touchEnded * @param {function} fxn function to be fired when touch is * ended over the element. * @chainable * @example *
* var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.touchEnded(changeGray); // attach listener for * // canvas click only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width/2, height/2, d, d); * } * * // this function fires with any touch anywhere * function touchEnded() { * d = d + 10; * } * * // this function fires only when cnv is clicked * function changeGray() { * g = random(0, 255); * } *
* * * @alt * no display. * */ p5.Element.prototype.touchEnded = function (fxn) { attachListener('touchend', fxn, this); attachListener('mouseup', fxn, this); return this; }; /** * The .dragOver() function is called once after every time a * file is dragged over the element. This can be used to attach an * element specific event listener. * * @method dragOver * @param {function} fxn function to be fired when mouse is * dragged over the element. * @chainable * @example *
* // To test this sketch, simply drag a * // file over the canvas * function setup() { * var c = createCanvas(100, 100); * background(200); * textAlign(CENTER); * text('Drag file', width/2, height/2); * c.dragOver(dragOverCallback); * } * * // This function will be called whenever * // a file is dragged over the canvas * function dragOverCallback() { * background(240); * text('Dragged over', width/2, height/2); * } *
* @alt * nothing displayed */ p5.Element.prototype.dragOver = function (fxn) { attachListener('dragover', fxn, this); return this; }; /** * The .dragLeave() function is called once after every time a * dragged file leaves the element area. This can be used to attach an * element specific event listener. * * @method dragLeave * @param {function} fxn function to be fired when mouse is * dragged over the element. * @chainable * @example *
* // To test this sketch, simply drag a file * // over and then out of the canvas area * function setup() { * var c = createCanvas(100, 100); * background(200); * textAlign(CENTER); * text('Drag file', width/2, height/2); * c.dragLeave(dragLeaveCallback); * } * * // This function will be called whenever * // a file is dragged out of the canvas * function dragLeaveCallback() { * background(240); * text('Dragged off', width/2, height/2); * } *
* @alt * nothing displayed */ p5.Element.prototype.dragLeave = function (fxn) { attachListener('dragleave', fxn, this); return this; }; /** * The .drop() function is called for each file dropped on the element. * It requires a callback that is passed a p5.File object. You can * optionally pass two callbacks, the first one (required) is triggered * for each file dropped when the file is loaded. The second (optional) * is triggered just once when a file (or files) are dropped. * * @method drop * @param {function} callback callback triggered when files are dropped. * @param {function} fxn callback to receive loaded file. * @chainable * @example *
* function setup() { * var c = createCanvas(100, 100); * background(200); * textAlign(CENTER); * text('drop image', width/2, height/2); * c.drop(gotFile); * } * * function gotFile(file) { * var img = createImg(file.data).hide(); * // Draw the image onto the canvas * image(img, 0, 0, width, height); * } *
* * @alt * Canvas turns into whatever image is dragged/dropped onto it. * */ p5.Element.prototype.drop = function (callback, fxn) { // Make a file loader callback and trigger user's callback function makeLoader(theFile) { // Making a p5.File object var p5file = new p5.File(theFile); return function(e) { p5file.data = e.target.result; callback(p5file); }; } // Is the file stuff supported? if (window.File && window.FileReader && window.FileList && window.Blob) { // If you want to be able to drop you've got to turn off // a lot of default behavior attachListener('dragover',function(evt) { evt.stopPropagation(); evt.preventDefault(); },this); // If this is a drag area we need to turn off the default behavior attachListener('dragleave',function(evt) { evt.stopPropagation(); evt.preventDefault(); },this); // If just one argument it's the callback for the files if (arguments.length > 1) { attachListener('drop', fxn, this); } // Deal with the files attachListener('drop', function(evt) { evt.stopPropagation(); evt.preventDefault(); // A FileList var files = evt.dataTransfer.files; // Load each one and trigger the callback for (var i = 0; i < files.length; i++) { var f = files[i]; var reader = new FileReader(); reader.onload = makeLoader(f); // Text or data? // This should likely be improved if (f.type.indexOf('text') > -1) { reader.readAsText(f); } else { reader.readAsDataURL(f); } } }, this); } else { console.log('The File APIs are not fully supported in this browser.'); } return this; }; function attachListener(ev, fxn, ctx) { // LM removing, not sure why we had this? // var _this = ctx; // var f = function (e) { fxn(e, _this); }; var f = fxn.bind(ctx); ctx.elt.addEventListener(ev, f, false); ctx._events[ev] = f; } /** * Helper fxn for sharing pixel methods * */ p5.Element.prototype._setProperty = function (prop, value) { this[prop] = value; }; module.exports = p5.Element; },{"./core":45}],51:[function(_dereq_,module,exports){ /** * @module Rendering * @submodule Rendering * @for p5 */ var p5 = _dereq_('./core'); var constants = _dereq_('./constants'); /** * Thin wrapper around a renderer, to be used for creating a * graphics buffer object. Use this class if you need * to draw into an off-screen graphics buffer. The two parameters define the * width and height in pixels. The fields and methods for this class are * extensive, but mirror the normal drawing API for p5. * * @class p5.Graphics * @constructor * @extends p5.Element * @param {Number} w width * @param {Number} h height * @param {Constant} renderer the renderer to use, either P2D or WEBGL * @param {p5} [pInst] pointer to p5 instance */ p5.Graphics = function(w, h, renderer, pInst) { var r = renderer || constants.P2D; this.canvas = document.createElement('canvas'); var node = this._userNode || document.body; node.appendChild(this.canvas); p5.Element.call(this, this.canvas, pInst, false); this._styles = []; this.width = w; this.height = h; this._pixelDensity = pInst._pixelDensity; if (r === constants.WEBGL) { this._renderer = new p5.RendererGL(this.canvas, this, false); } else { this._renderer = new p5.Renderer2D(this.canvas, this, false); } this._renderer.resize(w, h); this._renderer._applyDefaults(); pInst._elements.push(this); // bind methods and props of p5 to the new object for (var p in p5.prototype) { if (!this[p]) { if (typeof p5.prototype[p] === 'function') { this[p] = p5.prototype[p].bind(this); } else { this[p] = p5.prototype[p]; } } } return this; }; p5.Graphics.prototype = Object.create(p5.Element.prototype); p5.Graphics.prototype.remove = function() { if (this.elt.parentNode) { this.elt.parentNode.removeChild(this.elt); } for (var elt_ev in this._events) { this.elt.removeEventListener(elt_ev, this._events[elt_ev]); } }; module.exports = p5.Graphics; },{"./constants":44,"./core":45}],52:[function(_dereq_,module,exports){ /** * @module Rendering * @submodule Rendering * @for p5 */ var p5 = _dereq_('./core'); var constants = _dereq_('../core/constants'); /** * Main graphics and rendering context, as well as the base API * implementation for p5.js "core". To be used as the superclass for * Renderer2D and Renderer3D classes, respecitvely. * * @class p5.Renderer * @constructor * @extends p5.Element * @param {String} elt DOM node that is wrapped * @param {p5} [pInst] pointer to p5 instance * @param {Boolean} [isMainCanvas] whether we're using it as main canvas */ p5.Renderer = function(elt, pInst, isMainCanvas) { p5.Element.call(this, elt, pInst); this.canvas = elt; this._pInst = pInst; if (isMainCanvas) { this._isMainCanvas = true; // for pixel method sharing with pimage this._pInst._setProperty('_curElement', this); this._pInst._setProperty('canvas', this.canvas); this._pInst._setProperty('width', this.width); this._pInst._setProperty('height', this.height); } else { // hide if offscreen buffer by default this.canvas.style.display = 'none'; this._styles = []; // non-main elt styles stored in p5.Renderer } this._textSize = 12; this._textLeading = 15; this._textFont = 'sans-serif'; this._textStyle = constants.NORMAL; this._textAscent = null; this._textDescent = null; this._rectMode = constants.CORNER; this._ellipseMode = constants.CENTER; this._curveTightness = 0; this._imageMode = constants.CORNER; this._tint = null; this._doStroke = true; this._doFill = true; this._strokeSet = false; this._fillSet = false; this._colorMode = constants.RGB; this._colorMaxes = { rgb: [255, 255, 255, 255], hsb: [360, 100, 100, 1], hsl: [360, 100, 100, 1] }; }; p5.Renderer.prototype = Object.create(p5.Element.prototype); /** * Resize our canvas element. */ p5.Renderer.prototype.resize = function(w, h) { this.width = w; this.height = h; this.elt.width = w * this._pInst._pixelDensity; this.elt.height = h * this._pInst._pixelDensity; this.elt.style.width = w +'px'; this.elt.style.height = h + 'px'; if (this._isMainCanvas) { this._pInst._setProperty('width', this.width); this._pInst._setProperty('height', this.height); } }; p5.Renderer.prototype.textLeading = function(l) { if (arguments.length && arguments[0]) { this._setProperty('_textLeading', l); return this; } return this._textLeading; }; p5.Renderer.prototype.textSize = function(s) { if (arguments.length && arguments[0]) { this._setProperty('_textSize', s); this._setProperty('_textLeading', s * constants._DEFAULT_LEADMULT); return this._applyTextProperties(); } return this._textSize; }; p5.Renderer.prototype.textStyle = function(s) { if (arguments.length && arguments[0]) { if (s === constants.NORMAL || s === constants.ITALIC || s === constants.BOLD) { this._setProperty('_textStyle', s); } return this._applyTextProperties(); } return this._textStyle; }; p5.Renderer.prototype.textAscent = function() { if (this._textAscent === null) { this._updateTextMetrics(); } return this._textAscent; }; p5.Renderer.prototype.textDescent = function() { if (this._textDescent === null) { this._updateTextMetrics(); } return this._textDescent; }; p5.Renderer.prototype._applyDefaults = function(){ return this; }; /** * Helper fxn to check font type (system or otf) */ p5.Renderer.prototype._isOpenType = function(f) { f = f || this._textFont; return (typeof f === 'object' && f.font && f.font.supported); }; p5.Renderer.prototype._updateTextMetrics = function() { if (this._isOpenType()) { this._setProperty('_textAscent', this._textFont._textAscent()); this._setProperty('_textDescent', this._textFont._textDescent()); return this; } // Adapted from http://stackoverflow.com/a/25355178 var text = document.createElement('span'); text.style.fontFamily = this._textFont; text.style.fontSize = this._textSize + 'px'; text.innerHTML = 'ABCjgq|'; var block = document.createElement('div'); block.style.display = 'inline-block'; block.style.width = '1px'; block.style.height = '0px'; var container = document.createElement('div'); container.appendChild(text); container.appendChild(block); container.style.height = '0px'; container.style.overflow = 'hidden'; document.body.appendChild(container); block.style.verticalAlign = 'baseline'; var blockOffset = calculateOffset(block); var textOffset = calculateOffset(text); var ascent = blockOffset[1] - textOffset[1]; block.style.verticalAlign = 'bottom'; blockOffset = calculateOffset(block); textOffset = calculateOffset(text); var height = blockOffset[1] - textOffset[1]; var descent = height - ascent; document.body.removeChild(container); this._setProperty('_textAscent', ascent); this._setProperty('_textDescent', descent); return this; }; /** * Helper fxn to measure ascent and descent. * Adapted from http://stackoverflow.com/a/25355178 */ function calculateOffset(object) { var currentLeft = 0, currentTop = 0; if (object.offsetParent) { do { currentLeft += object.offsetLeft; currentTop += object.offsetTop; } while (object = object.offsetParent); } else { currentLeft += object.offsetLeft; currentTop += object.offsetTop; } return [currentLeft, currentTop]; } module.exports = p5.Renderer; },{"../core/constants":44,"./core":45}],53:[function(_dereq_,module,exports){ var p5 = _dereq_('./core'); var canvas = _dereq_('./canvas'); var constants = _dereq_('./constants'); var filters = _dereq_('../image/filters'); _dereq_('./p5.Renderer'); /** * p5.Renderer2D * The 2D graphics canvas renderer class. * extends p5.Renderer */ var styleEmpty = 'rgba(0,0,0,0)'; // var alphaThreshold = 0.00125; // minimum visible p5.Renderer2D = function(elt, pInst, isMainCanvas){ p5.Renderer.call(this, elt, pInst, isMainCanvas); this.drawingContext = this.canvas.getContext('2d'); this._pInst._setProperty('drawingContext', this.drawingContext); return this; }; p5.Renderer2D.prototype = Object.create(p5.Renderer.prototype); p5.Renderer2D.prototype._applyDefaults = function() { this._setFill(constants._DEFAULT_FILL); this._setStroke(constants._DEFAULT_STROKE); this.drawingContext.lineCap = constants.ROUND; this.drawingContext.font = 'normal 12px sans-serif'; }; p5.Renderer2D.prototype.resize = function(w,h) { p5.Renderer.prototype.resize.call(this, w,h); this.drawingContext.scale(this._pInst._pixelDensity, this._pInst._pixelDensity); }; ////////////////////////////////////////////// // COLOR | Setting ////////////////////////////////////////////// p5.Renderer2D.prototype.background = function() { this.drawingContext.save(); this.drawingContext.setTransform(1, 0, 0, 1, 0, 0); this.drawingContext.scale(this._pInst._pixelDensity, this._pInst._pixelDensity); if (arguments[0] instanceof p5.Image) { this._pInst.image(arguments[0], 0, 0, this.width, this.height); } else { var curFill = this._getFill(); // create background rect var color = this._pInst.color.apply(this, arguments); var newFill = color.toString(); this._setFill(newFill); this.drawingContext.fillRect(0, 0, this.width, this.height); // reset fill this._setFill(curFill); } this.drawingContext.restore(); }; p5.Renderer2D.prototype.clear = function() { this.drawingContext.clearRect(0, 0, this.width, this.height); }; p5.Renderer2D.prototype.fill = function() { var color = this._pInst.color.apply(this, arguments); this._setFill(color.toString()); }; p5.Renderer2D.prototype.stroke = function() { var color = this._pInst.color.apply(this, arguments); this._setStroke(color.toString()); }; ////////////////////////////////////////////// // IMAGE | Loading & Displaying ////////////////////////////////////////////// p5.Renderer2D.prototype.image = function (img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) { var cnv; try { if (this._tint) { if (p5.MediaElement && img instanceof p5.MediaElement) { img.loadPixels(); } if (img.canvas) { cnv = this._getTintedImageCanvas(img); } } if (!cnv) { cnv = img.canvas || img.elt; } this.drawingContext.drawImage(cnv, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight); } catch (e) { if (e.name !== 'NS_ERROR_NOT_AVAILABLE') { throw e; } } }; p5.Renderer2D.prototype._getTintedImageCanvas = function (img) { if (!img.canvas) { return img; } var pixels = filters._toPixels(img.canvas); var tmpCanvas = document.createElement('canvas'); tmpCanvas.width = img.canvas.width; tmpCanvas.height = img.canvas.height; var tmpCtx = tmpCanvas.getContext('2d'); var id = tmpCtx.createImageData(img.canvas.width, img.canvas.height); var newPixels = id.data; for (var i = 0; i < pixels.length; i += 4) { var r = pixels[i]; var g = pixels[i + 1]; var b = pixels[i + 2]; var a = pixels[i + 3]; newPixels[i] = r * this._tint[0] / 255; newPixels[i + 1] = g * this._tint[1] / 255; newPixels[i + 2] = b * this._tint[2] / 255; newPixels[i + 3] = a * this._tint[3] / 255; } tmpCtx.putImageData(id, 0, 0); return tmpCanvas; }; ////////////////////////////////////////////// // IMAGE | Pixels ////////////////////////////////////////////// p5.Renderer2D.prototype.blendMode = function(mode) { this.drawingContext.globalCompositeOperation = mode; }; p5.Renderer2D.prototype.blend = function() { var currBlend = this.drawingContext.globalCompositeOperation; var blendMode = arguments[arguments.length - 1]; var copyArgs = Array.prototype.slice.call( arguments, 0, arguments.length - 1 ); this.drawingContext.globalCompositeOperation = blendMode; if (this._pInst) { this._pInst.copy.apply(this._pInst, copyArgs); } else { this.copy.apply(this, copyArgs); } this.drawingContext.globalCompositeOperation = currBlend; }; p5.Renderer2D.prototype.copy = function () { var srcImage, sx, sy, sw, sh, dx, dy, dw, dh; if (arguments.length === 9) { srcImage = arguments[0]; sx = arguments[1]; sy = arguments[2]; sw = arguments[3]; sh = arguments[4]; dx = arguments[5]; dy = arguments[6]; dw = arguments[7]; dh = arguments[8]; } else if (arguments.length === 8) { srcImage = this._pInst; sx = arguments[0]; sy = arguments[1]; sw = arguments[2]; sh = arguments[3]; dx = arguments[4]; dy = arguments[5]; dw = arguments[6]; dh = arguments[7]; } else { throw new Error('Signature not supported'); } p5.Renderer2D._copyHelper(srcImage, sx, sy, sw, sh, dx, dy, dw, dh); }; p5.Renderer2D._copyHelper = function (srcImage, sx, sy, sw, sh, dx, dy, dw, dh) { srcImage.loadPixels(); var s = srcImage.canvas.width / srcImage.width; this.drawingContext.drawImage(srcImage.canvas, s * sx, s * sy, s * sw, s * sh, dx, dy, dw, dh); }; p5.Renderer2D.prototype.get = function(x, y, w, h) { if (x === undefined && y === undefined && w === undefined && h === undefined){ x = 0; y = 0; w = this.width; h = this.height; } else if (w === undefined && h === undefined) { w = 1; h = 1; } // if the section does not overlap the canvas if(x + w < 0 || y + h < 0 || x > this.width || y > this.height){ return [0, 0, 0, 255]; } var ctx = this._pInst || this; ctx.loadPixels(); var pd = ctx._pixelDensity; // round down to get integer numbers x = Math.floor(x); y = Math.floor(y); w = Math.floor(w); h = Math.floor(h); var sx = x * pd; var sy = y * pd; if (w === 1 && h === 1){ var imageData = this.drawingContext.getImageData(sx, sy, 1, 1).data; //imageData = [0,0,0,0]; return [ imageData[0], imageData[1], imageData[2], imageData[3] ]; } else { //auto constrain the width and height to //dimensions of the source image var dw = Math.min(w, ctx.width); var dh = Math.min(h, ctx.height); var sw = dw * pd; var sh = dh * pd; var region = new p5.Image(dw, dh); region.canvas.getContext('2d').drawImage(this.canvas, sx, sy, sw, sh, 0, 0, dw, dh); return region; } }; p5.Renderer2D.prototype.loadPixels = function () { var pd = this._pixelDensity || this._pInst._pixelDensity; var w = this.width * pd; var h = this.height * pd; var imageData = this.drawingContext.getImageData(0, 0, w, h); // @todo this should actually set pixels per object, so diff buffers can // have diff pixel arrays. if (this._pInst) { this._pInst._setProperty('imageData', imageData); this._pInst._setProperty('pixels', imageData.data); } else { // if called by p5.Image this._setProperty('imageData', imageData); this._setProperty('pixels', imageData.data); } }; p5.Renderer2D.prototype.set = function (x, y, imgOrCol) { // round down to get integer numbers x = Math.floor(x); y = Math.floor(y); if (imgOrCol instanceof p5.Image) { this.drawingContext.save(); this.drawingContext.setTransform(1, 0, 0, 1, 0, 0); this.drawingContext.scale(this._pInst._pixelDensity, this._pInst._pixelDensity); this.drawingContext.drawImage(imgOrCol.canvas, x, y); this.loadPixels.call(this._pInst); this.drawingContext.restore(); } else { var ctx = this._pInst || this; var r = 0, g = 0, b = 0, a = 0; var idx = 4*((y * ctx._pixelDensity) * (this.width * ctx._pixelDensity) + (x * ctx._pixelDensity)); if (!ctx.imageData) { ctx.loadPixels.call(ctx); } if (typeof imgOrCol === 'number') { if (idx < ctx.pixels.length) { r = imgOrCol; g = imgOrCol; b = imgOrCol; a = 255; //this.updatePixels.call(this); } } else if (imgOrCol instanceof Array) { if (imgOrCol.length < 4) { throw new Error('pixel array must be of the form [R, G, B, A]'); } if (idx < ctx.pixels.length) { r = imgOrCol[0]; g = imgOrCol[1]; b = imgOrCol[2]; a = imgOrCol[3]; //this.updatePixels.call(this); } } else if (imgOrCol instanceof p5.Color) { if (idx < ctx.pixels.length) { r = imgOrCol.levels[0]; g = imgOrCol.levels[1]; b = imgOrCol.levels[2]; a = imgOrCol.levels[3]; //this.updatePixels.call(this); } } // loop over pixelDensity * pixelDensity for (var i = 0; i < ctx._pixelDensity; i++) { for (var j = 0; j < ctx._pixelDensity; j++) { // loop over idx = 4*((y * ctx._pixelDensity + j) * this.width * ctx._pixelDensity + (x * ctx._pixelDensity + i)); ctx.pixels[idx] = r; ctx.pixels[idx+1] = g; ctx.pixels[idx+2] = b; ctx.pixels[idx+3] = a; } } } }; p5.Renderer2D.prototype.updatePixels = function (x, y, w, h) { var pd = this._pixelDensity || this._pInst._pixelDensity; if (x === undefined && y === undefined && w === undefined && h === undefined) { x = 0; y = 0; w = this.width; h = this.height; } w *= pd; h *= pd; if (this._pInst) { this.drawingContext.putImageData(this._pInst.imageData, x, y, 0, 0, w, h); } else { this.drawingContext.putImageData(this.imageData, x, y, 0, 0, w, h); } }; ////////////////////////////////////////////// // SHAPE | 2D Primitives ////////////////////////////////////////////// /** * Generate a cubic Bezier representing an arc on the unit circle of total * angle `size` radians, beginning `start` radians above the x-axis. Up to * four of these curves are combined to make a full arc. * * See www.joecridge.me/bezier.pdf for an explanation of the method. */ p5.Renderer2D.prototype._acuteArcToBezier = function _acuteArcToBezier(start, size) { // Evauate constants. var alpha = size / 2.0, cos_alpha = Math.cos(alpha), sin_alpha = Math.sin(alpha), cot_alpha = 1.0 / Math.tan(alpha), phi = start + alpha, // This is how far the arc needs to be rotated. cos_phi = Math.cos(phi), sin_phi = Math.sin(phi), lambda = (4.0 - cos_alpha) / 3.0, mu = sin_alpha + (cos_alpha - lambda) * cot_alpha; // Return rotated waypoints. return { ax: Math.cos(start), ay: Math.sin(start), bx: lambda * cos_phi + mu * sin_phi, by: lambda * sin_phi - mu * cos_phi, cx: lambda * cos_phi - mu * sin_phi, cy: lambda * sin_phi + mu * cos_phi, dx: Math.cos(start + size), dy: Math.sin(start + size) }; }; p5.Renderer2D.prototype.arc = function(x, y, w, h, start, stop, mode) { var ctx = this.drawingContext; var vals = canvas.arcModeAdjust(x, y, w, h, this._ellipseMode); var rx = vals.w / 2.0; var ry = vals.h / 2.0; var epsilon = 0.00001; // Smallest visible angle on displays up to 4K. var arcToDraw = 0; var curves = []; // Create curves while(stop - start > epsilon) { arcToDraw = Math.min(stop - start, constants.HALF_PI); curves.push(this._acuteArcToBezier(start, arcToDraw)); start += arcToDraw; } // Fill curves if (this._doFill) { ctx.beginPath(); curves.forEach(function (curve, index) { if (index === 0) { ctx.moveTo(vals.x + curve.ax * rx, vals.y + curve.ay * ry); } ctx.bezierCurveTo(vals.x + curve.bx * rx, vals.y + curve.by * ry, vals.x + curve.cx * rx, vals.y + curve.cy * ry, vals.x + curve.dx * rx, vals.y + curve.dy * ry); }); if (mode === constants.PIE || mode == null) { ctx.lineTo(vals.x, vals.y); } ctx.closePath(); ctx.fill(); } // Stroke curves if (this._doStroke) { ctx.beginPath(); curves.forEach(function (curve, index) { if (index === 0) { ctx.moveTo(vals.x + curve.ax * rx, vals.y + curve.ay * ry); } ctx.bezierCurveTo(vals.x + curve.bx * rx, vals.y + curve.by * ry, vals.x + curve.cx * rx, vals.y + curve.cy * ry, vals.x + curve.dx * rx, vals.y + curve.dy * ry); }); if (mode === constants.PIE) { ctx.lineTo(vals.x, vals.y); ctx.closePath(); } else if (mode === constants.CHORD) { ctx.closePath(); } ctx.stroke(); } return this; }; p5.Renderer2D.prototype.ellipse = function(args) { var ctx = this.drawingContext; var doFill = this._doFill, doStroke = this._doStroke; var x = args[0], y = args[1], w = args[2], h = args[3]; if (doFill && !doStroke) { if(this._getFill() === styleEmpty) { return this; } } else if (!doFill && doStroke) { if(this._getStroke() === styleEmpty) { return this; } } var kappa = 0.5522847498, ox = (w / 2) * kappa, // control point offset horizontal oy = (h / 2) * kappa, // control point offset vertical xe = x + w, // x-end ye = y + h, // y-end xm = x + w / 2, // x-middle ym = y + h / 2; // y-middle ctx.beginPath(); ctx.moveTo(x, ym); ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); ctx.closePath(); if (doFill) { ctx.fill(); } if (doStroke) { ctx.stroke(); } }; p5.Renderer2D.prototype.line = function(x1, y1, x2, y2) { var ctx = this.drawingContext; if (!this._doStroke) { return this; } else if(this._getStroke() === styleEmpty){ return this; } // Translate the line by (0.5, 0.5) to draw it crisp if (ctx.lineWidth % 2 === 1) { ctx.translate(0.5, 0.5); } ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); if (ctx.lineWidth % 2 === 1) { ctx.translate(-0.5, -0.5); } return this; }; p5.Renderer2D.prototype.point = function(x, y) { var ctx = this.drawingContext; if (!this._doStroke) { return this; } else if(this._getStroke() === styleEmpty){ return this; } x = Math.round(x); y = Math.round(y); if (ctx.lineWidth > 1) { ctx.beginPath(); ctx.arc( x, y, ctx.lineWidth / 2, 0, constants.TWO_PI, false ); ctx.fill(); } else { ctx.fillRect(x, y, 1, 1); } }; p5.Renderer2D.prototype.quad = function(x1, y1, x2, y2, x3, y3, x4, y4) { var ctx = this.drawingContext; var doFill = this._doFill, doStroke = this._doStroke; if (doFill && !doStroke) { if(this._getFill() === styleEmpty) { return this; } } else if (!doFill && doStroke) { if(this._getStroke() === styleEmpty) { return this; } } ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.lineTo(x3, y3); ctx.lineTo(x4, y4); ctx.closePath(); if (doFill) { ctx.fill(); } if (doStroke) { ctx.stroke(); } return this; }; p5.Renderer2D.prototype.rect = function(args) { var x = args[0], y = args[1], w = args[2], h = args[3], tl = args[4], tr = args[5], br = args[6], bl = args[7]; var ctx = this.drawingContext; var doFill = this._doFill, doStroke = this._doStroke; if (doFill && !doStroke) { if(this._getFill() === styleEmpty) { return this; } } else if (!doFill && doStroke) { if(this._getStroke() === styleEmpty) { return this; } } // Translate the line by (0.5, 0.5) to draw a crisp rectangle border if (this._doStroke && ctx.lineWidth % 2 === 1) { ctx.translate(0.5, 0.5); } ctx.beginPath(); if (typeof tl === 'undefined') { // No rounded corners ctx.rect(x, y, w, h); } else { // At least one rounded corner // Set defaults when not specified if (typeof tr === 'undefined') { tr = tl; } if (typeof br === 'undefined') { br = tr; } if (typeof bl === 'undefined') { bl = br; } var hw = w / 2; var hh = h / 2; // Clip radii if (w < 2 * tl) { tl = hw; } if (h < 2 * tl) { tl = hh; } if (w < 2 * tr) { tr = hw; } if (h < 2 * tr) { tr = hh; } if (w < 2 * br) { br = hw; } if (h < 2 * br) { br = hh; } if (w < 2 * bl) { bl = hw; } if (h < 2 * bl) { bl = hh; } // Draw shape ctx.beginPath(); ctx.moveTo(x + tl, y); ctx.arcTo(x + w, y, x + w, y + h, tr); ctx.arcTo(x + w, y + h, x, y + h, br); ctx.arcTo(x, y + h, x, y, bl); ctx.arcTo(x, y, x + w, y, tl); ctx.closePath(); } if (this._doFill) { ctx.fill(); } if (this._doStroke) { ctx.stroke(); } if (this._doStroke && ctx.lineWidth % 2 === 1) { ctx.translate(-0.5, -0.5); } return this; }; p5.Renderer2D.prototype.triangle = function(args) { var ctx = this.drawingContext; var doFill = this._doFill, doStroke = this._doStroke; var x1=args[0], y1=args[1]; var x2=args[2], y2=args[3]; var x3=args[4], y3=args[5]; if (doFill && !doStroke) { if(this._getFill() === styleEmpty) { return this; } } else if (!doFill && doStroke) { if(this._getStroke() === styleEmpty) { return this; } } ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.lineTo(x3, y3); ctx.closePath(); if (doFill) { ctx.fill(); } if (doStroke) { ctx.stroke(); } }; p5.Renderer2D.prototype.endShape = function (mode, vertices, isCurve, isBezier, isQuadratic, isContour, shapeKind) { if (vertices.length === 0) { return this; } if (!this._doStroke && !this._doFill) { return this; } var closeShape = mode === constants.CLOSE; var v; if (closeShape && !isContour) { vertices.push(vertices[0]); } var i, j; var numVerts = vertices.length; if (isCurve && (shapeKind === constants.POLYGON || shapeKind === null)) { if (numVerts > 3) { var b = [], s = 1 - this._curveTightness; this.drawingContext.beginPath(); this.drawingContext.moveTo(vertices[1][0], vertices[1][1]); for (i = 1; i + 2 < numVerts; i++) { v = vertices[i]; b[0] = [ v[0], v[1] ]; b[1] = [ v[0] + (s * vertices[i + 1][0] - s * vertices[i - 1][0]) / 6, v[1] + (s * vertices[i + 1][1] - s * vertices[i - 1][1]) / 6 ]; b[2] = [ vertices[i + 1][0] + (s * vertices[i][0]-s * vertices[i + 2][0]) / 6, vertices[i + 1][1]+(s * vertices[i][1] - s*vertices[i + 2][1]) / 6 ]; b[3] = [ vertices[i + 1][0], vertices[i + 1][1] ]; this.drawingContext.bezierCurveTo(b[1][0],b[1][1], b[2][0],b[2][1],b[3][0],b[3][1]); } if (closeShape) { this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); } this._doFillStrokeClose(); } } else if (isBezier&&(shapeKind===constants.POLYGON ||shapeKind === null)) { this.drawingContext.beginPath(); for (i = 0; i < numVerts; i++) { if (vertices[i].isVert) { if (vertices[i].moveTo) { this.drawingContext.moveTo(vertices[i][0], vertices[i][1]); } else { this.drawingContext.lineTo(vertices[i][0], vertices[i][1]); } } else { this.drawingContext.bezierCurveTo(vertices[i][0], vertices[i][1], vertices[i][2], vertices[i][3], vertices[i][4], vertices[i][5]); } } this._doFillStrokeClose(); } else if (isQuadratic && (shapeKind === constants.POLYGON || shapeKind === null)) { this.drawingContext.beginPath(); for (i = 0; i < numVerts; i++) { if (vertices[i].isVert) { if (vertices[i].moveTo) { this.drawingContext.moveTo([0], vertices[i][1]); } else { this.drawingContext.lineTo(vertices[i][0], vertices[i][1]); } } else { this.drawingContext.quadraticCurveTo(vertices[i][0], vertices[i][1], vertices[i][2], vertices[i][3]); } } this._doFillStrokeClose(); } else { if (shapeKind === constants.POINTS) { for (i = 0; i < numVerts; i++) { v = vertices[i]; if (this._doStroke) { this._pInst.stroke(v[6]); } this._pInst.point(v[0], v[1]); } } else if (shapeKind === constants.LINES) { for (i = 0; i + 1 < numVerts; i += 2) { v = vertices[i]; if (this._doStroke) { this._pInst.stroke(vertices[i + 1][6]); } this._pInst.line(v[0], v[1], vertices[i + 1][0], vertices[i + 1][1]); } } else if (shapeKind === constants.TRIANGLES) { for (i = 0; i + 2 < numVerts; i += 3) { v = vertices[i]; this.drawingContext.beginPath(); this.drawingContext.moveTo(v[0], v[1]); this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); this.drawingContext.lineTo(vertices[i + 2][0], vertices[i + 2][1]); this.drawingContext.lineTo(v[0], v[1]); if (this._doFill) { this._pInst.fill(vertices[i + 2][5]); this.drawingContext.fill(); } if (this._doStroke) { this._pInst.stroke(vertices[i + 2][6]); this.drawingContext.stroke(); } this.drawingContext.closePath(); } } else if (shapeKind === constants.TRIANGLE_STRIP) { for (i = 0; i + 1 < numVerts; i++) { v = vertices[i]; this.drawingContext.beginPath(); this.drawingContext.moveTo(vertices[i + 1][0], vertices[i + 1][1]); this.drawingContext.lineTo(v[0], v[1]); if (this._doStroke) { this._pInst.stroke(vertices[i + 1][6]); } if (this._doFill) { this._pInst.fill(vertices[i + 1][5]); } if (i + 2 < numVerts) { this.drawingContext.lineTo(vertices[i + 2][0], vertices[i + 2][1]); if (this._doStroke) { this._pInst.stroke(vertices[i + 2][6]); } if (this._doFill) { this._pInst.fill(vertices[i + 2][5]); } } this._doFillStrokeClose(); } } else if (shapeKind === constants.TRIANGLE_FAN) { if (numVerts > 2) { // For performance reasons, try to batch as many of the // fill and stroke calls as possible. this.drawingContext.beginPath(); for (i = 2; i < numVerts; i++) { v = vertices[i]; this.drawingContext.moveTo(vertices[0][0], vertices[0][1]); this.drawingContext.lineTo(vertices[i - 1][0], vertices[i - 1][1]); this.drawingContext.lineTo(v[0], v[1]); this.drawingContext.lineTo(vertices[0][0], vertices[0][1]); // If the next colour is going to be different, stroke / fill now if (i < numVerts - 1) { if ( (this._doFill && v[5] !== vertices[i + 1][5]) || (this._doStroke && v[6] !== vertices[i + 1][6])) { if (this._doFill) { this._pInst.fill(v[5]); this.drawingContext.fill(); this._pInst.fill(vertices[i + 1][5]); } if (this._doStroke) { this._pInst.stroke(v[6]); this.drawingContext.stroke(); this._pInst.stroke(vertices[i + 1][6]); } this.drawingContext.closePath(); this.drawingContext.beginPath(); // Begin the next one } } } this._doFillStrokeClose(); } } else if (shapeKind === constants.QUADS) { for (i = 0; i + 3 < numVerts; i += 4) { v = vertices[i]; this.drawingContext.beginPath(); this.drawingContext.moveTo(v[0], v[1]); for (j = 1; j < 4; j++) { this.drawingContext.lineTo(vertices[i + j][0], vertices[i + j][1]); } this.drawingContext.lineTo(v[0], v[1]); if (this._doFill) { this._pInst.fill(vertices[i + 3][5]); } if (this._doStroke) { this._pInst.stroke(vertices[i + 3][6]); } this._doFillStrokeClose(); } } else if (shapeKind === constants.QUAD_STRIP) { if (numVerts > 3) { for (i = 0; i + 1 < numVerts; i += 2) { v = vertices[i]; this.drawingContext.beginPath(); if (i + 3 < numVerts) { this.drawingContext.moveTo(vertices[i + 2][0], vertices[i+2][1]); this.drawingContext.lineTo(v[0], v[1]); this.drawingContext.lineTo(vertices[i + 1][0], vertices[i+1][1]); this.drawingContext.lineTo(vertices[i + 3][0], vertices[i+3][1]); if (this._doFill) { this._pInst.fill(vertices[i + 3][5]); } if (this._doStroke) { this._pInst.stroke(vertices[i + 3][6]); } } else { this.drawingContext.moveTo(v[0], v[1]); this.drawingContext.lineTo(vertices[i + 1][0], vertices[i+1][1]); } this._doFillStrokeClose(); } } } else { this.drawingContext.beginPath(); this.drawingContext.moveTo(vertices[0][0], vertices[0][1]); for (i = 1; i < numVerts; i++) { v = vertices[i]; if (v.isVert) { if (v.moveTo) { this.drawingContext.moveTo(v[0], v[1]); } else { this.drawingContext.lineTo(v[0], v[1]); } } } this._doFillStrokeClose(); } } isCurve = false; isBezier = false; isQuadratic = false; isContour = false; if (closeShape) { vertices.pop(); } return this; }; ////////////////////////////////////////////// // SHAPE | Attributes ////////////////////////////////////////////// p5.Renderer2D.prototype.noSmooth = function() { if ('imageSmoothingEnabled' in this.drawingContext) { this.drawingContext.imageSmoothingEnabled = false; } else if ('mozImageSmoothingEnabled' in this.drawingContext) { this.drawingContext.mozImageSmoothingEnabled = false; } else if ('webkitImageSmoothingEnabled' in this.drawingContext) { this.drawingContext.webkitImageSmoothingEnabled = false; } else if ('msImageSmoothingEnabled' in this.drawingContext) { this.drawingContext.msImageSmoothingEnabled = false; } return this; }; p5.Renderer2D.prototype.smooth = function() { if ('imageSmoothingEnabled' in this.drawingContext) { this.drawingContext.imageSmoothingEnabled = true; } else if ('mozImageSmoothingEnabled' in this.drawingContext) { this.drawingContext.mozImageSmoothingEnabled = true; } else if ('webkitImageSmoothingEnabled' in this.drawingContext) { this.drawingContext.webkitImageSmoothingEnabled = true; } else if ('msImageSmoothingEnabled' in this.drawingContext) { this.drawingContext.msImageSmoothingEnabled = true; } return this; }; p5.Renderer2D.prototype.strokeCap = function(cap) { if (cap === constants.ROUND || cap === constants.SQUARE || cap === constants.PROJECT) { this.drawingContext.lineCap = cap; } return this; }; p5.Renderer2D.prototype.strokeJoin = function(join) { if (join === constants.ROUND || join === constants.BEVEL || join === constants.MITER) { this.drawingContext.lineJoin = join; } return this; }; p5.Renderer2D.prototype.strokeWeight = function(w) { if (typeof w === 'undefined' || w === 0) { // hack because lineWidth 0 doesn't work this.drawingContext.lineWidth = 0.0001; } else { this.drawingContext.lineWidth = w; } return this; }; p5.Renderer2D.prototype._getFill = function(){ return this._cachedFillStyle; }; p5.Renderer2D.prototype._setFill = function(fillStyle){ if (fillStyle !== this._cachedFillStyle) { this.drawingContext.fillStyle = fillStyle; this._cachedFillStyle = fillStyle; } }; p5.Renderer2D.prototype._getStroke = function(){ return this._cachedStrokeStyle; }; p5.Renderer2D.prototype._setStroke = function(strokeStyle){ if (strokeStyle !== this._cachedStrokeStyle) { this.drawingContext.strokeStyle = strokeStyle; this._cachedStrokeStyle = strokeStyle; } }; ////////////////////////////////////////////// // SHAPE | Curves ////////////////////////////////////////////// p5.Renderer2D.prototype.bezier = function (x1, y1, x2, y2, x3, y3, x4, y4) { this._pInst.beginShape(); this._pInst.vertex(x1, y1); this._pInst.bezierVertex(x2, y2, x3, y3, x4, y4); this._pInst.endShape(); return this; }; p5.Renderer2D.prototype.curve = function (x1, y1, x2, y2, x3, y3, x4, y4) { this._pInst.beginShape(); this._pInst.curveVertex(x1, y1); this._pInst.curveVertex(x2, y2); this._pInst.curveVertex(x3, y3); this._pInst.curveVertex(x4, y4); this._pInst.endShape(); return this; }; ////////////////////////////////////////////// // SHAPE | Vertex ////////////////////////////////////////////// p5.Renderer2D.prototype._doFillStrokeClose = function () { if (this._doFill) { this.drawingContext.fill(); } if (this._doStroke) { this.drawingContext.stroke(); } this.drawingContext.closePath(); }; ////////////////////////////////////////////// // TRANSFORM ////////////////////////////////////////////// p5.Renderer2D.prototype.applyMatrix = function(n00, n01, n02, n10, n11, n12) { this.drawingContext.transform(n00, n01, n02, n10, n11, n12); }; p5.Renderer2D.prototype.resetMatrix = function() { this.drawingContext.setTransform(1, 0, 0, 1, 0, 0); this.drawingContext.scale(this._pInst._pixelDensity, this._pInst._pixelDensity); return this; }; p5.Renderer2D.prototype.rotate = function(r) { this.drawingContext.rotate(r); }; p5.Renderer2D.prototype.scale = function(x,y) { this.drawingContext.scale(x, y); return this; }; p5.Renderer2D.prototype.shearX = function(angle) { if (this._pInst._angleMode === constants.DEGREES) { // undoing here, because it gets redone in tan() angle = this._pInst.degrees(angle); } this.drawingContext.transform(1, 0, this._pInst.tan(angle), 1, 0, 0); return this; }; p5.Renderer2D.prototype.shearY = function(angle) { if (this._pInst._angleMode === constants.DEGREES) { // undoing here, because it gets redone in tan() angle = this._pInst.degrees(angle); } this.drawingContext.transform(1, this._pInst.tan(angle), 0, 1, 0, 0); return this; }; p5.Renderer2D.prototype.translate = function(x, y) { this.drawingContext.translate(x, y); return this; }; ////////////////////////////////////////////// // TYPOGRAPHY // ////////////////////////////////////////////// p5.Renderer2D.prototype.text = function (str, x, y, maxWidth, maxHeight) { var p = this._pInst, cars, n, ii, jj, line, testLine, testWidth, words, totalHeight, baselineHacked, finalMaxHeight = Number.MAX_VALUE; // baselineHacked: (HACK) // A temporary fix to conform to Processing's implementation // of BASELINE vertical alignment in a bounding box if (!(this._doFill || this._doStroke)) { return; } if (typeof str !== 'string') { str = str.toString(); } str = str.replace(/(\t)/g, ' '); cars = str.split('\n'); if (typeof maxWidth !== 'undefined') { totalHeight = 0; for (ii = 0; ii < cars.length; ii++) { line = ''; words = cars[ii].split(' '); for (n = 0; n < words.length; n++) { testLine = line + words[n] + ' '; testWidth = this.textWidth(testLine); if (testWidth > maxWidth) { line = words[n] + ' '; totalHeight += p.textLeading(); } else { line = testLine; } } } if (this._rectMode === constants.CENTER) { x -= maxWidth / 2; y -= maxHeight / 2; } switch (this.drawingContext.textAlign) { case constants.CENTER: x += maxWidth / 2; break; case constants.RIGHT: x += maxWidth; break; } if (typeof maxHeight !== 'undefined') { switch (this.drawingContext.textBaseline) { case constants.BOTTOM: y += (maxHeight - totalHeight); break; case constants._CTX_MIDDLE: // CENTER? y += (maxHeight - totalHeight) / 2; break; case constants.BASELINE: baselineHacked = true; this.drawingContext.textBaseline = constants.TOP; break; } // remember the max-allowed y-position for any line (fix to #928) finalMaxHeight = (y + maxHeight) - p.textAscent(); } for (ii = 0; ii < cars.length; ii++) { line = ''; words = cars[ii].split(' '); for (n = 0; n < words.length; n++) { testLine = line + words[n] + ' '; testWidth = this.textWidth(testLine); if (testWidth > maxWidth && line.length > 0) { this._renderText(p, line, x, y, finalMaxHeight); line = words[n] + ' '; y += p.textLeading(); } else { line = testLine; } } this._renderText(p, line, x, y, finalMaxHeight); y += p.textLeading(); } } else { // Offset to account for vertically centering multiple lines of text - no // need to adjust anything for vertical align top or baseline var offset = 0, vAlign = p.textAlign().vertical; if (vAlign === constants.CENTER) { offset = ((cars.length - 1) * p.textLeading()) / 2; } else if (vAlign === constants.BOTTOM) { offset = (cars.length - 1) * p.textLeading(); } for (jj = 0; jj < cars.length; jj++) { this._renderText(p, cars[jj], x, y-offset, finalMaxHeight); y += p.textLeading(); } } if (baselineHacked) { this.drawingContext.textBaseline = constants.BASELINE; } return p; }; p5.Renderer2D.prototype._renderText = function(p, line, x, y, maxY) { if (y >= maxY) { return; // don't render lines beyond our maxY position } p.push(); // fix to #803 if (!this._isOpenType()) { // a system/browser font // no stroke unless specified by user if (this._doStroke && this._strokeSet) { this.drawingContext.strokeText(line, x, y); } if (this._doFill) { // if fill hasn't been set by user, use default text fill if (! this._fillSet) { this._setFill(constants._DEFAULT_TEXT_FILL); } this.drawingContext.fillText(line, x, y); } } else { // an opentype font, let it handle the rendering this._textFont._renderPath(line, x, y, { renderer: this }); } p.pop(); return p; }; p5.Renderer2D.prototype.textWidth = function(s) { if (this._isOpenType()) { return this._textFont._textWidth(s, this._textSize); } return this.drawingContext.measureText(s).width; }; p5.Renderer2D.prototype.textAlign = function(h, v) { if (arguments.length) { if (h === constants.LEFT || h === constants.RIGHT || h === constants.CENTER) { this.drawingContext.textAlign = h; } if (v === constants.TOP || v === constants.BOTTOM || v === constants.CENTER || v === constants.BASELINE) { if (v === constants.CENTER) { this.drawingContext.textBaseline = constants._CTX_MIDDLE; } else { this.drawingContext.textBaseline = v; } } return this._pInst; } else { var valign = this.drawingContext.textBaseline; if (valign === constants._CTX_MIDDLE) { valign = constants.CENTER; } return { horizontal: this.drawingContext.textAlign, vertical: valign }; } }; p5.Renderer2D.prototype._applyTextProperties = function() { var font, p = this._pInst; this._setProperty('_textAscent', null); this._setProperty('_textDescent', null); font = this._textFont; if (this._isOpenType()) { font = this._textFont.font.familyName; this._setProperty('_textStyle', this._textFont.font.styleName); } this.drawingContext.font = this._textStyle + ' ' + this._textSize + 'px ' + font; return p; }; ////////////////////////////////////////////// // STRUCTURE ////////////////////////////////////////////// p5.Renderer2D.prototype.push = function() { this.drawingContext.save(); }; p5.Renderer2D.prototype.pop = function() { this.drawingContext.restore(); // Re-cache the fill / stroke state this._cachedFillStyle = this.drawingContext.fillStyle; this._cachedStrokeStyle = this.drawingContext.strokeStyle; }; module.exports = p5.Renderer2D; },{"../image/filters":59,"./canvas":43,"./constants":44,"./core":45,"./p5.Renderer":52}],54:[function(_dereq_,module,exports){ /** * @module Rendering * @submodule Rendering * @for p5 */ var p5 = _dereq_('./core'); var constants = _dereq_('./constants'); _dereq_('./p5.Graphics'); _dereq_('./p5.Renderer2D'); _dereq_('../webgl/p5.RendererGL'); var defaultId = 'defaultCanvas0'; // this gets set again in createCanvas /** * Creates a canvas element in the document, and sets the dimensions of it * in pixels. This method should be called only once at the start of setup. * Calling createCanvas more than once in a sketch will result in very * unpredicable behavior. If you want more than one drawing canvas * you could use createGraphics (hidden by default but it can be shown). *

* The system variables width and height are set by the parameters passed * to this function. If createCanvas() is not used, the window will be * given a default size of 100x100 pixels. *

* For more ways to position the canvas, see the * * positioning the canvas wiki page. * * @method createCanvas * @param {Number} w width of the canvas * @param {Number} h height of the canvas * @param {Constant} [renderer] either P2D or WEBGL * @return {HTMLCanvasElement} canvas generated * @example *
* * function setup() { * createCanvas(100, 50); * background(153); * line(0, 0, width, height); * } * *
* * @alt * Black line extending from top-left of canvas to bottom right. * */ p5.prototype.createCanvas = function(w, h, renderer) { //optional: renderer, otherwise defaults to p2d var r = renderer || constants.P2D; var isDefault, c; //4th arg (isDefault) used when called onLoad, //otherwise hidden to the public api if(arguments[3]){ isDefault = (typeof arguments[3] === 'boolean') ? arguments[3] : false; } if(r === constants.WEBGL){ c = document.getElementById(defaultId); if(c){ //if defaultCanvas already exists c.parentNode.removeChild(c); //replace the existing defaultCanvas } c = document.createElement('canvas'); c.id = defaultId; } else { if (isDefault) { c = document.createElement('canvas'); var i = 0; while (document.getElementById('defaultCanvas'+i)) { i++; } defaultId = 'defaultCanvas'+i; c.id = defaultId; } else { // resize the default canvas if new one is created c = this.canvas; } } // set to invisible if still in setup (to prevent flashing with manipulate) if (!this._setupDone) { c.dataset.hidden = true; // tag to show later c.style.visibility='hidden'; } if (this._userNode) { // user input node case this._userNode.appendChild(c); } else { document.body.appendChild(c); } // Init our graphics renderer //webgl mode if (r === constants.WEBGL) { this._setProperty('_renderer', new p5.RendererGL(c, this, true)); this._isdefaultGraphics = true; } //P2D mode else { if (!this._isdefaultGraphics) { this._setProperty('_renderer', new p5.Renderer2D(c, this, true)); this._isdefaultGraphics = true; } } this._renderer.resize(w, h); this._renderer._applyDefaults(); if (isDefault) { // only push once this._elements.push(this._renderer); } return this._renderer; }; /** * Resizes the canvas to given width and height. The canvas will be cleared * and draw will be called immediately, allowing the sketch to re-render itself * in the resized canvas. * @method resizeCanvas * @param {Number} w width of the canvas * @param {Number} h height of the canvas * @param {Boolean} noRedraw don't redraw the canvas immediately * @example *
* function setup() { * createCanvas(windowWidth, windowHeight); * } * * function draw() { * background(0, 100, 200); * } * * function windowResized() { * resizeCanvas(windowWidth, windowHeight); * } *
* * @alt * No image displayed. * */ p5.prototype.resizeCanvas = function (w, h, noRedraw) { if (this._renderer) { // save canvas properties var props = {}; for (var key in this.drawingContext) { var val = this.drawingContext[key]; if (typeof val !== 'object' && typeof val !== 'function') { props[key] = val; } } this._renderer.resize(w, h); // reset canvas properties for (var savedKey in props) { this.drawingContext[savedKey] = props[savedKey]; } if (!noRedraw) { this.redraw(); } } }; /** * Removes the default canvas for a p5 sketch that doesn't * require a canvas * @method noCanvas * @example *
* * function setup() { * noCanvas(); * } * *
* * @alt * no image displayed * */ p5.prototype.noCanvas = function() { if (this.canvas) { this.canvas.parentNode.removeChild(this.canvas); } }; /** * Creates and returns a new p5.Renderer object. Use this class if you need * to draw into an off-screen graphics buffer. The two parameters define the * width and height in pixels. * * @method createGraphics * @param {Number} w width of the offscreen graphics buffer * @param {Number} h height of the offscreen graphics buffer * @param {Constant} [renderer] either P2D or WEBGL * undefined defaults to p2d * @return {p5.Graphics} offscreen graphics buffer * @example *
* * var pg; * function setup() { * createCanvas(100, 100); * pg = createGraphics(100, 100); * } * function draw() { * background(200); * pg.background(100); * pg.noStroke(); * pg.ellipse(pg.width/2, pg.height/2, 50, 50); * image(pg, 50, 50); * image(pg, 0, 0, 50, 50); * } * *
* * @alt * 4 grey squares alternating light and dark grey. White quarter circle mid-left. * */ p5.prototype.createGraphics = function(w, h, renderer){ return new p5.Graphics(w, h, renderer, this); }; /** * Blends the pixels in the display window according to the defined mode. * There is a choice of the following modes to blend the source pixels (A) * with the ones of pixels already in the display window (B): *
    *
  • BLEND - linear interpolation of colours: C = * A*factor + B. This is the default blending mode.
  • *
  • ADD - sum of A and B
  • *
  • DARKEST - only the darkest colour succeeds: C = * min(A*factor, B).
  • *
  • LIGHTEST - only the lightest colour succeeds: C = * max(A*factor, B).
  • *
  • DIFFERENCE - subtract colors from underlying image.
  • *
  • EXCLUSION - similar to DIFFERENCE, but less * extreme.
  • *
  • MULTIPLY - multiply the colors, result will always be * darker.
  • *
  • SCREEN - opposite multiply, uses inverse values of the * colors.
  • *
  • REPLACE - the pixels entirely replace the others and * don't utilize alpha (transparency) values.
  • *
  • OVERLAY - mix of MULTIPLY and SCREEN * . Multiplies dark values, and screens light values.
  • *
  • HARD_LIGHT - SCREEN when greater than 50% * gray, MULTIPLY when lower.
  • *
  • SOFT_LIGHT - mix of DARKEST and * LIGHTEST. Works like OVERLAY, but not as harsh. *
  • *
  • DODGE - lightens light tones and increases contrast, * ignores darks.
  • *
  • BURN - darker areas are applied, increasing contrast, * ignores lights.
  • *
* * @method blendMode * @param {Constant} mode blend mode to set for canvas. * either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY, * EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL * @example *
* * blendMode(LIGHTEST); * strokeWeight(30); * stroke(80, 150, 255); * line(25, 25, 75, 75); * stroke(255, 50, 50); * line(75, 25, 25, 75); * *
*
* * blendMode(MULTIPLY); * strokeWeight(30); * stroke(80, 150, 255); * line(25, 25, 75, 75); * stroke(255, 50, 50); * line(75, 25, 25, 75); * *
* @alt * translucent image thick red & blue diagonal rounded lines intersecting center * Thick red & blue diagonal rounded lines intersecting center. dark at overlap * */ p5.prototype.blendMode = function(mode) { if (mode === constants.BLEND || mode === constants.DARKEST || mode === constants.LIGHTEST || mode === constants.DIFFERENCE || mode === constants.MULTIPLY || mode === constants.EXCLUSION || mode === constants.SCREEN || mode === constants.REPLACE || mode === constants.OVERLAY || mode === constants.HARD_LIGHT || mode === constants.SOFT_LIGHT || mode === constants.DODGE || mode === constants.BURN || mode === constants.ADD || mode === constants.NORMAL) { this._renderer.blendMode(mode); } else { throw new Error('Mode '+mode+' not recognized.'); } }; module.exports = p5; },{"../webgl/p5.RendererGL":65,"./constants":44,"./core":45,"./p5.Graphics":51,"./p5.Renderer2D":53}],55:[function(_dereq_,module,exports){ // requestAnim shim layer by Paul Irish window.requestAnimationFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback, element){ // should '60' here be framerate? window.setTimeout(callback, 1000 / 60); }; })(); // use window.performance() to get max fast and accurate time in milliseconds window.performance = window.performance || {}; window.performance.now = (function(){ var load_date = Date.now(); return window.performance.now || window.performance.mozNow || window.performance.msNow || window.performance.oNow || window.performance.webkitNow || function () { return Date.now() - load_date; }; })(); /* // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ // http://my.opera.com/emoller/blog/2011/12/20/ // requestanimationframe-for-smart-er-animating // requestAnimationFrame polyfill by Erik Möller // fixes from Paul Irish and Tino Zijdel (function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) { window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } if (!window.cancelAnimationFrame) { window.cancelAnimationFrame = function(id) { clearTimeout(id); }; } }()); */ /** * shim for Uint8ClampedArray.slice * (allows arrayCopy to work with pixels[]) * with thanks to http://halfpapstudios.com/blog/tag/html5-canvas/ * Enumerable set to false to protect for...in from * Uint8ClampedArray.prototype pollution. */ (function () { 'use strict'; if (typeof Uint8ClampedArray !== 'undefined' && !Uint8ClampedArray.prototype.slice) { Object.defineProperty(Uint8ClampedArray.prototype, 'slice', { value: Array.prototype.slice, writable: true, configurable: true, enumerable: false }); } }()); },{}],56:[function(_dereq_,module,exports){ /** * @module Structure * @submodule Structure * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('./core'); p5.prototype.exit = function() { throw 'exit() not implemented, see remove()'; }; /** * Stops p5.js from continuously executing the code within draw(). * If loop() is called, the code in draw() begins to run continuously again. * If using noLoop() in setup(), it should be the last line inside the block. *

* When noLoop() is used, it's not possible to manipulate or access the * screen inside event handling functions such as mousePressed() or * keyPressed(). Instead, use those functions to call redraw() or loop(), * which will run draw(), which can update the screen properly. This means * that when noLoop() has been called, no drawing can happen, and functions * like saveFrame() or loadPixels() may not be used. *

* Note that if the sketch is resized, redraw() will be called to update * the sketch, even after noLoop() has been specified. Otherwise, the sketch * would enter an odd state until loop() was called. * * @method noLoop * @example *
* function setup() { * createCanvas(100, 100); * background(200); * noLoop(); * } * function draw() { * line(10, 10, 90, 90); * } *
* *
* var x = 0; * function setup() { * createCanvas(100, 100); * } * * function draw() { * background(204); * x = x + 0.1; * if (x > width) { * x = 0; * } * line(x, 0, x, height); * } * * function mousePressed() { * noLoop(); * } * * function mouseReleased() { * loop(); * } *
* * @alt * 113 pixel long line extending from top-left to bottom right of canvas. * horizontal line moves slowly from left. Loops but stops on mouse press. * */ p5.prototype.noLoop = function() { this._loop = false; }; /** * By default, p5.js loops through draw() continuously, executing the code * within it. However, the draw() loop may be stopped by calling noLoop(). * In that case, the draw() loop can be resumed with loop(). * * @method loop * @example *
* var x = 0; * function setup() { * createCanvas(100, 100); * noLoop(); * } * * function draw() { * background(204); * x = x + 0.1; * if (x > width) { * x = 0; * } * line(x, 0, x, height); * } * * function mousePressed() { * loop(); * } * * function mouseReleased() { * noLoop(); * } *
* * @alt * horizontal line moves slowly from left. Loops but stops on mouse press. * */ p5.prototype.loop = function() { this._loop = true; this._draw(); }; /** * The push() function saves the current drawing style settings and * transformations, while pop() restores these settings. Note that these * functions are always used together. They allow you to change the style * and transformation settings and later return to what you had. When a new * state is started with push(), it builds on the current style and transform * information. The push() and pop() functions can be embedded to provide * more control. (See the second example for a demonstration.) *

* push() stores information related to the current transformation state * and style settings controlled by the following functions: fill(), * stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(), * imageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(), * textFont(), textMode(), textSize(), textLeading(). * * @method push * @example *
* * ellipse(0, 50, 33, 33); // Left circle * * push(); // Start a new drawing state * strokeWeight(10); * fill(204, 153, 0); * translate(50, 0); * ellipse(0, 50, 33, 33); // Middle circle * pop(); // Restore original state * * ellipse(100, 50, 33, 33); // Right circle * *
*
* * ellipse(0, 50, 33, 33); // Left circle * * push(); // Start a new drawing state * strokeWeight(10); * fill(204, 153, 0); * ellipse(33, 50, 33, 33); // Left-middle circle * * push(); // Start another new drawing state * stroke(0, 102, 153); * ellipse(66, 50, 33, 33); // Right-middle circle * pop(); // Restore previous state * * pop(); // Restore original state * * ellipse(100, 50, 33, 33); // Right circle * *
* * @alt * Gold ellipse + thick black outline @center 2 white ellipses on left and right. * 2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right. * */ p5.prototype.push = function () { this._renderer.push(); this._styles.push({ _doStroke: this._renderer._doStroke, _strokeSet: this._renderer._strokeSet, _doFill: this._renderer._doFill, _fillSet: this._renderer._fillSet, _tint: this._renderer._tint, _imageMode: this._renderer._imageMode, _rectMode: this._renderer._rectMode, _ellipseMode: this._renderer._ellipseMode, _colorMode: this._renderer._colorMode, _textFont: this._renderer._textFont, _textLeading: this._renderer._textLeading, _textSize: this._renderer._textSize, _textStyle: this._renderer._textStyle }); }; /** * The push() function saves the current drawing style settings and * transformations, while pop() restores these settings. Note that these * functions are always used together. They allow you to change the style * and transformation settings and later return to what you had. When a new * state is started with push(), it builds on the current style and transform * information. The push() and pop() functions can be embedded to provide * more control. (See the second example for a demonstration.) *

* push() stores information related to the current transformation state * and style settings controlled by the following functions: fill(), * stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(), * imageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(), * textFont(), textMode(), textSize(), textLeading(). * * @method pop * @example *
* * ellipse(0, 50, 33, 33); // Left circle * * push(); // Start a new drawing state * translate(50, 0); * strokeWeight(10); * fill(204, 153, 0); * ellipse(0, 50, 33, 33); // Middle circle * pop(); // Restore original state * * ellipse(100, 50, 33, 33); // Right circle * *
*
* * ellipse(0, 50, 33, 33); // Left circle * * push(); // Start a new drawing state * strokeWeight(10); * fill(204, 153, 0); * ellipse(33, 50, 33, 33); // Left-middle circle * * push(); // Start another new drawing state * stroke(0, 102, 153); * ellipse(66, 50, 33, 33); // Right-middle circle * pop(); // Restore previous state * * pop(); // Restore original state * * ellipse(100, 50, 33, 33); // Right circle * *
* * @alt * Gold ellipse + thick black outline @center 2 white ellipses on left and right. * 2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right. * */ p5.prototype.pop = function () { this._renderer.pop(); var lastS = this._styles.pop(); for(var prop in lastS){ this._renderer[prop] = lastS[prop]; } }; p5.prototype.pushStyle = function() { throw new Error('pushStyle() not used, see push()'); }; p5.prototype.popStyle = function() { throw new Error('popStyle() not used, see pop()'); }; /** * * Executes the code within draw() one time. This functions allows the * program to update the display window only when necessary, for example * when an event registered by mousePressed() or keyPressed() occurs. *

* In structuring a program, it only makes sense to call redraw() within * events such as mousePressed(). This is because redraw() does not run * draw() immediately (it only sets a flag that indicates an update is * needed). *

* The redraw() function does not work properly when called inside draw(). * To enable/disable animations, use loop() and noLoop(). *

* In addition you can set the number of redraws per method call. Just * add an integer as single parameter for the number of redraws. * * @method redraw * @param {Integer} [n] Redraw for n-times. The default value is 1. * @example *
* var x = 0; * * function setup() { * createCanvas(100, 100); * noLoop(); * } * * function draw() { * background(204); * line(x, 0, x, height); * } * * function mousePressed() { * x += 1; * redraw(); * } *
* *
* var x = 0; * * function setup() { * createCanvas(100, 100); * noLoop(); * } * * function draw() { * background(204); * x += 1; * line(x, 0, x, height); * } * * function mousePressed() { * redraw(5); * } *
* * @alt * black line on far left of canvas * black line on far left of canvas * */ p5.prototype.redraw = function () { this.resetMatrix(); if(this._renderer.isP3D){ this._renderer._update(); } var numberOfRedraws = 1; if (arguments.length === 1) { try { if (parseInt(arguments[0]) > 1) { numberOfRedraws = parseInt(arguments[0]); } } catch (error) { // Do nothing, because the default value didn't be changed. } } var userSetup = this.setup || window.setup; var userDraw = this.draw || window.draw; if (typeof userDraw === 'function') { if (typeof userSetup === 'undefined') { this.scale(this._pixelDensity, this._pixelDensity); } var self = this; var callMethod = function (f) { f.call(self); }; for (var idxRedraw = 0; idxRedraw < numberOfRedraws; idxRedraw++) { this._registeredMethods.pre.forEach(callMethod); userDraw(); this._registeredMethods.post.forEach(callMethod); } } }; p5.prototype.size = function() { var s = 'size() is not a valid p5 function, to set the size of the '; s += 'drawing canvas, please use createCanvas() instead'; throw s; }; module.exports = p5; },{"./core":45}],57:[function(_dereq_,module,exports){ /** * @module Transform * @submodule Transform * @for p5 * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('./core'); var constants = _dereq_('./constants'); /** * Multiplies the current matrix by the one specified through the parameters. * This is very slow because it will try to calculate the inverse of the * transform, so avoid it whenever possible. * * @method applyMatrix * @param {Number} n00 numbers which define the 3x2 matrix to be multiplied * @param {Number} n01 numbers which define the 3x2 matrix to be multiplied * @param {Number} n02 numbers which define the 3x2 matrix to be multiplied * @param {Number} n10 numbers which define the 3x2 matrix to be multiplied * @param {Number} n11 numbers which define the 3x2 matrix to be multiplied * @param {Number} n12 numbers which define the 3x2 matrix to be multiplied * @chainable * @example *
* * // Example in the works. * *
* * @alt * no image diplayed * */ p5.prototype.applyMatrix = function(n00, n01, n02, n10, n11, n12) { this._renderer.applyMatrix(n00, n01, n02, n10, n11, n12); return this; }; p5.prototype.popMatrix = function() { throw new Error('popMatrix() not used, see pop()'); }; p5.prototype.printMatrix = function() { throw new Error('printMatrix() not implemented'); }; p5.prototype.pushMatrix = function() { throw new Error('pushMatrix() not used, see push()'); }; /** * Replaces the current matrix with the identity matrix. * * @method resetMatrix * @chainable * @example *
* * // Example in the works. * *
* * @alt * no image diplayed * */ p5.prototype.resetMatrix = function() { this._renderer.resetMatrix(); return this; }; /** * Rotates a shape the amount specified by the angle parameter. This * function accounts for angleMode, so angles can be entered in either * RADIANS or DEGREES. *

* Objects are always rotated around their relative position to the * origin and positive numbers rotate objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * rotate(HALF_PI) and then rotate(HALF_PI) is the same as rotate(PI). * All tranformations are reset when draw() begins again. *

* Technically, rotate() multiplies the current transformation matrix * by a rotation matrix. This function can be further controlled by * the push() and pop(). * * @method rotate * @param {Number} angle the angle of rotation, specified in radians * or degrees, depending on current angleMode * @param {p5.Vector|Array} [axis] (in 3d) the axis to rotate around * @chainable * @example *
* * translate(width/2, height/2); * rotate(PI/3.0); * rect(-26, -26, 52, 52); * *
* * @alt * white 52x52 rect with black outline at center rotated counter 45 degrees * */ p5.prototype.rotate = function(angle, axis) { var args = new Array(arguments.length); var r; for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } if (this._angleMode === constants.DEGREES) { r = this.radians(args[0]); } else if (this._angleMode === constants.RADIANS){ r = args[0]; } //in webgl mode if(args.length > 1){ this._renderer.rotate(r, args[1]); } else { this._renderer.rotate(r); } return this; }; /** * Rotates around X axis. * @method rotateX * @param {Number} rad angles in radians * @chainable */ p5.prototype.rotateX = function(rad) { if (this._renderer.isP3D) { this._renderer.rotateX(rad); } else { throw 'not supported in p2d. Please use webgl mode'; } return this; }; /** * Rotates around Y axis. * @method rotateY * @param {Number} rad angles in radians * @chainable */ p5.prototype.rotateY = function(rad) { if (this._renderer.isP3D) { this._renderer.rotateY(rad); } else { throw 'not supported in p2d. Please use webgl mode'; } return this; }; /** * Rotates around Z axis. Webgl mode only. * @method rotateZ * @param {Number} rad angles in radians * @chainable */ p5.prototype.rotateZ = function(rad) { if (this._renderer.isP3D) { this._renderer.rotateZ(rad); } else { throw 'not supported in p2d. Please use webgl mode'; } return this; }; /** * Increases or decreases the size of a shape by expanding and contracting * vertices. Objects always scale from their relative origin to the * coordinate system. Scale values are specified as decimal percentages. * For example, the function call scale(2.0) increases the dimension of a * shape by 200%. *

* Transformations apply to everything that happens after and subsequent * calls to the function multiply the effect. For example, calling scale(2.0) * and then scale(1.5) is the same as scale(3.0). If scale() is called * within draw(), the transformation is reset when the loop begins again. *

* Using this function with the z parameter is only available in WEBGL mode. * This function can be further controlled with push() and pop(). * * @method scale * @param {Number|p5.Vector|Array} s * percent to scale the object, or percentage to * scale the object in the x-axis if multiple arguments * are given * @param {Number} [y] percent to scale the object in the y-axis * @param {Number} [z] percent to scale the object in the z-axis (webgl only) * @chainable * @example *
* * translate(width/2, height/2); * rotate(PI/3.0); * rect(-26, -26, 52, 52); * *
* *
* * rect(30, 20, 50, 50); * scale(0.5, 1.3); * rect(30, 20, 50, 50); * *
* * @alt * white 52x52 rect with black outline at center rotated counter 45 degrees * 2 white rects with black outline- 1 50x50 at center. other 25x65 bottom left * */ p5.prototype.scale = function() { var x,y,z; var args = new Array(arguments.length); for(var i = 0; i < args.length; i++) { args[i] = arguments[i]; } // Only check for Vector argument type if Vector is available if (typeof p5.Vector !== 'undefined') { if(args[0] instanceof p5.Vector){ x = args[0].x; y = args[0].y; z = args[0].z; } } else if(args[0] instanceof Array){ x = args[0][0]; y = args[0][1]; z = args[0][2] || 1; } else { if(args.length === 1){ x = y = z = args[0]; } else { x = args[0]; y = args[1]; z = args[2] || 1; } } if(this._renderer.isP3D){ this._renderer.scale.call(this._renderer, x,y,z); } else { this._renderer.scale.call(this._renderer, x,y); } return this; }; /** * Shears a shape around the x-axis the amount specified by the angle * parameter. Angles should be specified in the current angleMode. * Objects are always sheared around their relative position to the origin * and positive numbers shear objects in a clockwise direction. *

* Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * shearX(PI/2) and then shearX(PI/2) is the same as shearX(PI). * If shearX() is called within the draw(), the transformation is reset when * the loop begins again. *

* Technically, shearX() multiplies the current transformation matrix by a * rotation matrix. This function can be further controlled by the * push() and pop() functions. * * @method shearX * @param {Number} angle angle of shear specified in radians or degrees, * depending on current angleMode * @chainable * @example *
* * translate(width/4, height/4); * shearX(PI/4.0); * rect(0, 0, 30, 30); * *
* * @alt * white irregular quadrilateral with black outline at top middle. * */ p5.prototype.shearX = function(angle) { if (this._angleMode === constants.DEGREES) { angle = this.radians(angle); } this._renderer.shearX(angle); return this; }; /** * Shears a shape around the y-axis the amount specified by the angle * parameter. Angles should be specified in the current angleMode. Objects * are always sheared around their relative position to the origin and * positive numbers shear objects in a clockwise direction. *

* Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * shearY(PI/2) and then shearY(PI/2) is the same as shearY(PI). If * shearY() is called within the draw(), the transformation is reset when * the loop begins again. *

* Technically, shearY() multiplies the current transformation matrix by a * rotation matrix. This function can be further controlled by the * push() and pop() functions. * * @method shearY * @param {Number} angle angle of shear specified in radians or degrees, * depending on current angleMode * @chainable * @example *
* * translate(width/4, height/4); * shearY(PI/4.0); * rect(0, 0, 30, 30); * *
* * @alt * white irregular quadrilateral with black outline at middle bottom. * */ p5.prototype.shearY = function(angle) { if (this._angleMode === constants.DEGREES) { angle = this.radians(angle); } this._renderer.shearY(angle); return this; }; /** * Specifies an amount to displace objects within the display window. * The x parameter specifies left/right translation, the y parameter * specifies up/down translation. *

* Transformations are cumulative and apply to everything that happens after * and subsequent calls to the function accumulates the effect. For example, * calling translate(50, 0) and then translate(20, 0) is the same as * translate(70, 0). If translate() is called within draw(), the * transformation is reset when the loop begins again. This function can be * further controlled by using push() and pop(). * * @method translate * @param {Number} x left/right translation * @param {Number} y up/down translation * @param {Number} [z] forward/backward translation (webgl only) * @chainable * @example *
* * translate(30, 20); * rect(0, 0, 55, 55); * *
* *
* * rect(0, 0, 55, 55); // Draw rect at original 0,0 * translate(30, 20); * rect(0, 0, 55, 55); // Draw rect at new 0,0 * translate(14, 14); * rect(0, 0, 55, 55); // Draw rect at new 0,0 * *
* * @alt * white 55x55 rect with black outline at center right. * 3 white 55x55 rects with black outlines at top-l, center-r and bottom-r. * */ p5.prototype.translate = function(x, y, z) { if (this._renderer.isP3D) { this._renderer.translate(x, y, z); } else { this._renderer.translate(x, y); } return this; }; module.exports = p5; },{"./constants":44,"./core":45}],58:[function(_dereq_,module,exports){ /** * @module Shape * @submodule Vertex * @for p5 * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('./core'); var constants = _dereq_('./constants'); var shapeKind = null; var vertices = []; var contourVertices = []; var isBezier = false; var isCurve = false; var isQuadratic = false; var isContour = false; var isFirstContour = true; /** * Use the beginContour() and endContour() functions to create negative * shapes within shapes such as the center of the letter 'O'. beginContour() * begins recording vertices for the shape and endContour() stops recording. * The vertices that define a negative shape must "wind" in the opposite * direction from the exterior shape. First draw vertices for the exterior * clockwise order, then for internal shapes, draw vertices * shape in counter-clockwise. *

* These functions can only be used within a beginShape()/endShape() pair and * transformations such as translate(), rotate(), and scale() do not work * within a beginContour()/endContour() pair. It is also not possible to use * other shapes, such as ellipse() or rect() within. * * @method beginContour * @chainable * @example *
* * translate(50, 50); * stroke(255, 0, 0); * beginShape(); * // Exterior part of shape, clockwise winding * vertex(-40, -40); * vertex(40, -40); * vertex(40, 40); * vertex(-40, 40); * // Interior part of shape, counter-clockwise winding * beginContour(); * vertex(-20, -20); * vertex(-20, 20); * vertex(20, 20); * vertex(20, -20); * endContour(); * endShape(CLOSE); * *
* * @alt * white rect and smaller grey rect with red outlines in center of canvas. * */ p5.prototype.beginContour = function() { contourVertices = []; isContour = true; return this; }; /** * Using the beginShape() and endShape() functions allow creating more * complex forms. beginShape() begins recording vertices for a shape and * endShape() stops recording. The value of the kind parameter tells it which * types of shapes to create from the provided vertices. With no mode * specified, the shape can be any irregular polygon. *

* The parameters available for beginShape() are POINTS, LINES, TRIANGLES, * TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. After calling the * beginShape() function, a series of vertex() commands must follow. To stop * drawing the shape, call endShape(). Each shape will be outlined with the * current stroke color and filled with the fill color. *

* Transformations such as translate(), rotate(), and scale() do not work * within beginShape(). It is also not possible to use other shapes, such as * ellipse() or rect() within beginShape(). * * @method beginShape * @param {Constant} [kind] either POINTS, LINES, TRIANGLES, TRIANGLE_FAN * TRIANGLE_STRIP, QUADS, or QUAD_STRIP * @chainable * @example *
* * beginShape(); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(CLOSE); * *
* *
* * // currently not working * beginShape(POINTS); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(); * *
* *
* * beginShape(LINES); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(); * *
* *
* * noFill(); * beginShape(); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(); * *
* *
* * noFill(); * beginShape(); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(CLOSE); * *
* *
* * beginShape(TRIANGLES); * vertex(30, 75); * vertex(40, 20); * vertex(50, 75); * vertex(60, 20); * vertex(70, 75); * vertex(80, 20); * endShape(); * *
* *
* * beginShape(TRIANGLE_STRIP); * vertex(30, 75); * vertex(40, 20); * vertex(50, 75); * vertex(60, 20); * vertex(70, 75); * vertex(80, 20); * vertex(90, 75); * endShape(); * *
* *
* * beginShape(TRIANGLE_FAN); * vertex(57.5, 50); * vertex(57.5, 15); * vertex(92, 50); * vertex(57.5, 85); * vertex(22, 50); * vertex(57.5, 15); * endShape(); * *
* *
* * beginShape(QUADS); * vertex(30, 20); * vertex(30, 75); * vertex(50, 75); * vertex(50, 20); * vertex(65, 20); * vertex(65, 75); * vertex(85, 75); * vertex(85, 20); * endShape(); * *
* *
* * beginShape(QUAD_STRIP); * vertex(30, 20); * vertex(30, 75); * vertex(50, 20); * vertex(50, 75); * vertex(65, 20); * vertex(65, 75); * vertex(85, 20); * vertex(85, 75); * endShape(); * *
* *
* * beginShape(); * vertex(20, 20); * vertex(40, 20); * vertex(40, 40); * vertex(60, 40); * vertex(60, 60); * vertex(20, 60); * endShape(CLOSE); * *
* @alt * white square-shape with black outline in middle-right of canvas. * 4 black points in a square shape in middle-right of canvas. * 2 horizontal black lines. In the top-right and bottom-right of canvas. * 3 line shape with horizontal on top, vertical in middle and horizontal bottom. * square line shape in middle-right of canvas. * 2 white triangle shapes mid-right canvas. left one pointing up and right down. * 5 horizontal interlocking and alternating white triangles in mid-right canvas. * 4 interlocking white triangles in 45 degree rotated square-shape. * 2 white rectangle shapes in mid-right canvas. Both 20x55. * 3 side-by-side white rectangles center rect is smaller in mid-right canvas. * Thick white l-shape with black outline mid-top-left of canvas. * */ p5.prototype.beginShape = function(kind) { if (kind === constants.POINTS || kind === constants.LINES || kind === constants.TRIANGLES || kind === constants.TRIANGLE_FAN || kind === constants.TRIANGLE_STRIP || kind === constants.QUADS || kind === constants.QUAD_STRIP) { shapeKind = kind; } else { shapeKind = null; } if(this._renderer.isP3D){ this._renderer.beginShape(kind); } else { vertices = []; contourVertices = []; } return this; }; /** * Specifies vertex coordinates for Bezier curves. Each call to * bezierVertex() defines the position of two control points and * one anchor point of a Bezier curve, adding a new segment to a * line or shape. *

* The first time bezierVertex() is used within a * beginShape() call, it must be prefaced with a call to vertex() * to set the first anchor point. This function must be used between * beginShape() and endShape() and only when there is no MODE * parameter specified to beginShape(). * * @method bezierVertex * @param {Number} x2 x-coordinate for the first control point * @param {Number} y2 y-coordinate for the first control point * @param {Number} x3 x-coordinate for the second control point * @param {Number} y3 y-coordinate for the second control point * @param {Number} x4 x-coordinate for the anchor point * @param {Number} y4 y-coordinate for the anchor point * @chainable * @example *
* * noFill(); * beginShape(); * vertex(30, 20); * bezierVertex(80, 0, 80, 75, 30, 75); * endShape(); * *
* *
* * beginShape(); * vertex(30, 20); * bezierVertex(80, 0, 80, 75, 30, 75); * bezierVertex(50, 80, 60, 25, 30, 20); * endShape(); * *
* * @alt * crescent-shaped line in middle of canvas. Points facing left. * white crescent shape in middle of canvas. Points facing left. * */ p5.prototype.bezierVertex = function(x2, y2, x3, y3, x4, y4) { if (vertices.length === 0) { throw 'vertex() must be used once before calling bezierVertex()'; } else { isBezier = true; var vert = []; for (var i = 0; i < arguments.length; i++) { vert[i] = arguments[i]; } vert.isVert = false; if (isContour) { contourVertices.push(vert); } else { vertices.push(vert); } } return this; }; /** * Specifies vertex coordinates for curves. This function may only * be used between beginShape() and endShape() and only when there * is no MODE parameter specified to beginShape(). *

* The first and last points in a series of curveVertex() lines will be used to * guide the beginning and end of a the curve. A minimum of four * points is required to draw a tiny curve between the second and * third points. Adding a fifth point with curveVertex() will draw * the curve between the second, third, and fourth points. The * curveVertex() function is an implementation of Catmull-Rom * splines. * * @method curveVertex * @param {Number} x x-coordinate of the vertex * @param {Number} y y-coordinate of the vertex * @chainable * @example *
* * noFill(); * beginShape(); * curveVertex(84, 91); * curveVertex(84, 91); * curveVertex(68, 19); * curveVertex(21, 17); * curveVertex(32, 100); * curveVertex(32, 100); * endShape(); * *
* * @alt * Upside-down u-shape line, mid canvas. left point extends beyond canvas view. * */ p5.prototype.curveVertex = function(x,y) { isCurve = true; this.vertex(x, y); return this; }; /** * Use the beginContour() and endContour() functions to create negative * shapes within shapes such as the center of the letter 'O'. beginContour() * begins recording vertices for the shape and endContour() stops recording. * The vertices that define a negative shape must "wind" in the opposite * direction from the exterior shape. First draw vertices for the exterior * clockwise order, then for internal shapes, draw vertices * shape in counter-clockwise. *

* These functions can only be used within a beginShape()/endShape() pair and * transformations such as translate(), rotate(), and scale() do not work * within a beginContour()/endContour() pair. It is also not possible to use * other shapes, such as ellipse() or rect() within. * * @method endContour * @chainable * @example *
* * translate(50, 50); * stroke(255, 0, 0); * beginShape(); * // Exterior part of shape, clockwise winding * vertex(-40, -40); * vertex(40, -40); * vertex(40, 40); * vertex(-40, 40); * // Interior part of shape, counter-clockwise winding * beginContour(); * vertex(-20, -20); * vertex(-20, 20); * vertex(20, 20); * vertex(20, -20); * endContour(); * endShape(CLOSE); * *
* * @alt * white rect and smaller grey rect with red outlines in center of canvas. * */ p5.prototype.endContour = function() { var vert = contourVertices[0].slice(); // copy all data vert.isVert = contourVertices[0].isVert; vert.moveTo = false; contourVertices.push(vert); // prevent stray lines with multiple contours if (isFirstContour) { vertices.push(vertices[0]); isFirstContour = false; } for (var i = 0; i < contourVertices.length; i++) { vertices.push(contourVertices[i]); } return this; }; /** * The endShape() function is the companion to beginShape() and may only be * called after beginShape(). When endshape() is called, all of image data * defined since the previous call to beginShape() is written into the image * buffer. The constant CLOSE as the value for the MODE parameter to close * the shape (to connect the beginning and the end). * * @method endShape * @param {Constant} [mode] use CLOSE to close the shape * @chainable * @example *
* * noFill(); * * beginShape(); * vertex(20, 20); * vertex(45, 20); * vertex(45, 80); * endShape(CLOSE); * * beginShape(); * vertex(50, 20); * vertex(75, 20); * vertex(75, 80); * endShape(); * *
* * @alt * Triangle line shape with smallest interior angle on bottom and upside-down L. * */ p5.prototype.endShape = function(mode) { if(this._renderer.isP3D){ this._renderer.endShape(mode, isCurve, isBezier, isQuadratic, isContour, shapeKind); }else{ if (vertices.length === 0) { return this; } if (!this._renderer._doStroke && !this._renderer._doFill) { return this; } var closeShape = mode === constants.CLOSE; // if the shape is closed, the first element is also the last element if (closeShape && !isContour) { vertices.push(vertices[0]); } this._renderer.endShape(mode, vertices, isCurve, isBezier, isQuadratic, isContour, shapeKind); // Reset some settings isCurve = false; isBezier = false; isQuadratic = false; isContour = false; isFirstContour = true; // If the shape is closed, the first element was added as last element. // We must remove it again to prevent the list of vertices from growing // over successive calls to endShape(CLOSE) if (closeShape) { vertices.pop(); } } return this; }; /** * Specifies vertex coordinates for quadratic Bezier curves. Each call to * quadraticVertex() defines the position of one control points and one * anchor point of a Bezier curve, adding a new segment to a line or shape. * The first time quadraticVertex() is used within a beginShape() call, it * must be prefaced with a call to vertex() to set the first anchor point. * This function must be used between beginShape() and endShape() and only * when there is no MODE parameter specified to beginShape(). * * @method quadraticVertex * @param {Number} cx x-coordinate for the control point * @param {Number} cy y-coordinate for the control point * @param {Number} x3 x-coordinate for the anchor point * @param {Number} y3 y-coordinate for the anchor point * @chainable * @example *
* * noFill(); * strokeWeight(4); * beginShape(); * vertex(20, 20); * quadraticVertex(80, 20, 50, 50); * endShape(); * *
* *
* * noFill(); * strokeWeight(4); * beginShape(); * vertex(20, 20); * quadraticVertex(80, 20, 50, 50); * quadraticVertex(20, 80, 80, 80); * vertex(80, 60); * endShape(); * *
* * @alt * arched-shaped black line with 4 pixel thick stroke weight. * backwards s-shaped black line with 4 pixel thick stroke weight. * */ p5.prototype.quadraticVertex = function(cx, cy, x3, y3) { //if we're drawing a contour, put the points into an // array for inside drawing if(this._contourInited) { var pt = {}; pt.x = cx; pt.y = cy; pt.x3 = x3; pt.y3 = y3; pt.type = constants.QUADRATIC; this._contourVertices.push(pt); return this; } if (vertices.length > 0) { isQuadratic = true; var vert = []; for (var i = 0; i < arguments.length; i++) { vert[i] = arguments[i]; } vert.isVert = false; if (isContour) { contourVertices.push(vert); } else { vertices.push(vert); } } else { throw 'vertex() must be used once before calling quadraticVertex()'; } return this; }; /** * All shapes are constructed by connecting a series of vertices. vertex() * is used to specify the vertex coordinates for points, lines, triangles, * quads, and polygons. It is used exclusively within the beginShape() and * endShape() functions. * * @method vertex * @param {Number} x x-coordinate of the vertex * @param {Number} y y-coordinate of the vertex * @param {Number|Boolean} [z] z-coordinate of the vertex * @chainable * @example *
* * beginShape(POINTS); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(); * *
* * @alt * 4 black points in a square shape in middle-right of canvas. * */ p5.prototype.vertex = function(x, y, moveTo) { if(this._renderer.isP3D){ this._renderer.vertex(x, y, moveTo); }else{ var vert = []; vert.isVert = true; vert[0] = x; vert[1] = y; vert[2] = 0; vert[3] = 0; vert[4] = 0; vert[5] = this._renderer._getFill(); vert[6] = this._renderer._getStroke(); if (moveTo) { vert.moveTo = moveTo; } if (isContour) { if (contourVertices.length === 0) { vert.moveTo = true; } contourVertices.push(vert); } else { vertices.push(vert); } } return this; }; module.exports = p5; },{"./constants":44,"./core":45}],59:[function(_dereq_,module,exports){ /*global ImageData:false */ /** * This module defines the filters for use with image buffers. * * This module is basically a collection of functions stored in an object * as opposed to modules. The functions are destructive, modifying * the passed in canvas rather than creating a copy. * * Generally speaking users of this module will use the Filters.apply method * on a canvas to create an effect. * * A number of functions are borrowed/adapted from * http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ * or the java processing implementation. */ 'use strict'; var Filters = {}; /* * Helper functions */ /** * Returns the pixel buffer for a canvas * * @private * * @param {Canvas|ImageData} canvas the canvas to get pixels from * @return {Uint8ClampedArray} a one-dimensional array containing * the data in thc RGBA order, with integer * values between 0 and 255 */ Filters._toPixels = function (canvas) { if (canvas instanceof ImageData) { return canvas.data; } else { return canvas.getContext('2d').getImageData( 0, 0, canvas.width, canvas.height ).data; } }; /** * Returns a 32 bit number containing ARGB data at ith pixel in the * 1D array containing pixels data. * * @private * * @param {Uint8ClampedArray} data array returned by _toPixels() * @param {Integer} i index of a 1D Image Array * @return {Integer} 32 bit integer value representing * ARGB value. */ Filters._getARGB = function (data, i) { var offset = i * 4; return (data[offset+3] << 24) & 0xff000000 | (data[offset] << 16) & 0x00ff0000 | (data[offset+1] << 8) & 0x0000ff00 | data[offset+2] & 0x000000ff; }; /** * Modifies pixels RGBA values to values contained in the data object. * * @private * * @param {Uint8ClampedArray} pixels array returned by _toPixels() * @param {Int32Array} data source 1D array where each value * represents ARGB values */ Filters._setPixels = function (pixels, data) { var offset = 0; for( var i = 0, al = pixels.length; i < al; i++) { offset = i*4; pixels[offset + 0] = (data[i] & 0x00ff0000)>>>16; pixels[offset + 1] = (data[i] & 0x0000ff00)>>>8; pixels[offset + 2] = (data[i] & 0x000000ff); pixels[offset + 3] = (data[i] & 0xff000000)>>>24; } }; /** * Returns the ImageData object for a canvas * https://developer.mozilla.org/en-US/docs/Web/API/ImageData * * @private * * @param {Canvas|ImageData} canvas canvas to get image data from * @return {ImageData} Holder of pixel data (and width and * height) for a canvas */ Filters._toImageData = function (canvas) { if (canvas instanceof ImageData) { return canvas; } else { return canvas.getContext('2d').getImageData( 0, 0, canvas.width, canvas.height ); } }; /** * Returns a blank ImageData object. * * @private * * @param {Integer} width * @param {Integer} height * @return {ImageData} */ Filters._createImageData = function (width, height) { Filters._tmpCanvas = document.createElement('canvas'); Filters._tmpCtx = Filters._tmpCanvas.getContext('2d'); return this._tmpCtx.createImageData(width, height); }; /** * Applys a filter function to a canvas. * * The difference between this and the actual filter functions defined below * is that the filter functions generally modify the pixel buffer but do * not actually put that data back to the canvas (where it would actually * update what is visible). By contrast this method does make the changes * actually visible in the canvas. * * The apply method is the method that callers of this module would generally * use. It has been separated from the actual filters to support an advanced * use case of creating a filter chain that executes without actually updating * the canvas in between everystep. * * @param {HTMLCanvasElement} canvas [description] * @param {function(ImageData,Object)} func [description] * @param {Object} filterParam [description] */ Filters.apply = function (canvas, func, filterParam) { var ctx = canvas.getContext('2d'); var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); //Filters can either return a new ImageData object, or just modify //the one they received. var newImageData = func(imageData, filterParam); if (newImageData instanceof ImageData) { ctx.putImageData(newImageData, 0, 0, 0, 0, canvas.width, canvas.height); } else { ctx.putImageData(imageData, 0, 0, 0, 0, canvas.width, canvas.height); } }; /* * Filters */ /** * Converts the image to black and white pixels depending if they are above or * below the threshold defined by the level parameter. The parameter must be * between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used. * * Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ * * @param {Canvas} canvas * @param {Float} level */ Filters.threshold = function (canvas, level) { var pixels = Filters._toPixels(canvas); if (level === undefined) { level = 0.5; } var thresh = Math.floor(level * 255); for (var i = 0; i < pixels.length; i += 4) { var r = pixels[i]; var g = pixels[i + 1]; var b = pixels[i + 2]; var gray = (0.2126 * r + 0.7152 * g + 0.0722 * b); var val; if (gray >= thresh) { val = 255; } else { val = 0; } pixels[i] = pixels[i + 1] = pixels[i + 2] = val; } }; /** * Converts any colors in the image to grayscale equivalents. * No parameter is used. * * Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ * * @param {Canvas} canvas */ Filters.gray = function (canvas) { var pixels = Filters._toPixels(canvas); for (var i = 0; i < pixels.length; i += 4) { var r = pixels[i]; var g = pixels[i + 1]; var b = pixels[i + 2]; // CIE luminance for RGB var gray = (0.2126 * r + 0.7152 * g + 0.0722 * b); pixels[i] = pixels[i + 1] = pixels[i + 2] = gray; } }; /** * Sets the alpha channel to entirely opaque. No parameter is used. * * @param {Canvas} canvas */ Filters.opaque = function (canvas) { var pixels = Filters._toPixels(canvas); for (var i = 0; i < pixels.length; i += 4) { pixels[i + 3] = 255; } return pixels; }; /** * Sets each pixel to its inverse value. No parameter is used. * @param {Canvas} canvas */ Filters.invert = function (canvas) { var pixels = Filters._toPixels(canvas); for (var i = 0; i < pixels.length; i += 4) { pixels[i] = 255 - pixels[i]; pixels[i + 1] = 255 - pixels[i + 1]; pixels[i + 2] = 255 - pixels[i + 2]; } }; /** * Limits each channel of the image to the number of colors specified as * the parameter. The parameter can be set to values between 2 and 255, but * results are most noticeable in the lower ranges. * * Adapted from java based processing implementation * * @param {Canvas} canvas * @param {Integer} level */ Filters.posterize = function (canvas, level) { var pixels = Filters._toPixels(canvas); if ((level < 2) || (level > 255)) { throw new Error( 'Level must be greater than 2 and less than 255 for posterize' ); } var levels1 = level - 1; for (var i = 0; i < pixels.length; i+=4) { var rlevel = pixels[i]; var glevel = pixels[i + 1]; var blevel = pixels[i + 2]; pixels[i] = (((rlevel * level) >> 8) * 255) / levels1; pixels[i + 1] = (((glevel * level) >> 8) * 255) / levels1; pixels[i + 2] = (((blevel * level) >> 8) * 255) / levels1; } }; /** * reduces the bright areas in an image * @param {Canvas} canvas * */ Filters.dilate = function (canvas) { var pixels = Filters._toPixels(canvas); var currIdx = 0; var maxIdx = pixels.length ? pixels.length/4 : 0; var out = new Int32Array(maxIdx); var currRowIdx, maxRowIdx, colOrig, colOut, currLum; var idxRight, idxLeft, idxUp, idxDown, colRight, colLeft, colUp, colDown, lumRight, lumLeft, lumUp, lumDown; while(currIdx < maxIdx) { currRowIdx = currIdx; maxRowIdx = currIdx + canvas.width; while (currIdx < maxRowIdx) { colOrig = colOut = Filters._getARGB(pixels, currIdx); idxLeft = currIdx - 1; idxRight = currIdx + 1; idxUp = currIdx - canvas.width; idxDown = currIdx + canvas.width; if (idxLeft < currRowIdx) { idxLeft = currIdx; } if (idxRight >= maxRowIdx) { idxRight = currIdx; } if (idxUp < 0){ idxUp = 0; } if (idxDown >= maxIdx) { idxDown = currIdx; } colUp = Filters._getARGB(pixels, idxUp); colLeft = Filters._getARGB(pixels, idxLeft); colDown = Filters._getARGB(pixels, idxDown); colRight = Filters._getARGB(pixels, idxRight); //compute luminance currLum = 77*(colOrig>>16&0xff) + 151*(colOrig>>8&0xff) + 28*(colOrig&0xff); lumLeft = 77*(colLeft>>16&0xff) + 151*(colLeft>>8&0xff) + 28*(colLeft&0xff); lumRight = 77*(colRight>>16&0xff) + 151*(colRight>>8&0xff) + 28*(colRight&0xff); lumUp = 77*(colUp>>16&0xff) + 151*(colUp>>8&0xff) + 28*(colUp&0xff); lumDown = 77*(colDown>>16&0xff) + 151*(colDown>>8&0xff) + 28*(colDown&0xff); if (lumLeft > currLum) { colOut = colLeft; currLum = lumLeft; } if (lumRight > currLum) { colOut = colRight; currLum = lumRight; } if (lumUp > currLum) { colOut = colUp; currLum = lumUp; } if (lumDown > currLum) { colOut = colDown; currLum = lumDown; } out[currIdx++]=colOut; } } Filters._setPixels(pixels, out); }; /** * increases the bright areas in an image * @param {Canvas} canvas * */ Filters.erode = function(canvas) { var pixels = Filters._toPixels(canvas); var currIdx = 0; var maxIdx = pixels.length ? pixels.length/4 : 0; var out = new Int32Array(maxIdx); var currRowIdx, maxRowIdx, colOrig, colOut, currLum; var idxRight, idxLeft, idxUp, idxDown, colRight, colLeft, colUp, colDown, lumRight, lumLeft, lumUp, lumDown; while(currIdx < maxIdx) { currRowIdx = currIdx; maxRowIdx = currIdx + canvas.width; while (currIdx < maxRowIdx) { colOrig = colOut = Filters._getARGB(pixels, currIdx); idxLeft = currIdx - 1; idxRight = currIdx + 1; idxUp = currIdx - canvas.width; idxDown = currIdx + canvas.width; if (idxLeft < currRowIdx) { idxLeft = currIdx; } if (idxRight >= maxRowIdx) { idxRight = currIdx; } if (idxUp < 0) { idxUp = 0; } if (idxDown >= maxIdx) { idxDown = currIdx; } colUp = Filters._getARGB(pixels, idxUp); colLeft = Filters._getARGB(pixels, idxLeft); colDown = Filters._getARGB(pixels, idxDown); colRight = Filters._getARGB(pixels, idxRight); //compute luminance currLum = 77*(colOrig>>16&0xff) + 151*(colOrig>>8&0xff) + 28*(colOrig&0xff); lumLeft = 77*(colLeft>>16&0xff) + 151*(colLeft>>8&0xff) + 28*(colLeft&0xff); lumRight = 77*(colRight>>16&0xff) + 151*(colRight>>8&0xff) + 28*(colRight&0xff); lumUp = 77*(colUp>>16&0xff) + 151*(colUp>>8&0xff) + 28*(colUp&0xff); lumDown = 77*(colDown>>16&0xff) + 151*(colDown>>8&0xff) + 28*(colDown&0xff); if (lumLeft < currLum) { colOut = colLeft; currLum = lumLeft; } if (lumRight < currLum) { colOut = colRight; currLum = lumRight; } if (lumUp < currLum) { colOut = colUp; currLum = lumUp; } if (lumDown < currLum) { colOut = colDown; currLum = lumDown; } out[currIdx++]=colOut; } } Filters._setPixels(pixels, out); }; // BLUR // internal kernel stuff for the gaussian blur filter var blurRadius; var blurKernelSize; var blurKernel; var blurMult; /* * Port of https://github.com/processing/processing/blob/ * master/core/src/processing/core/PImage.java#L1250 * * Optimized code for building the blur kernel. * further optimized blur code (approx. 15% for radius=20) * bigger speed gains for larger radii (~30%) * added support for various image types (ALPHA, RGB, ARGB) * [toxi 050728] */ function buildBlurKernel(r) { var radius = (r * 3.5)|0; radius = (radius < 1) ? 1 : ((radius < 248) ? radius : 248); if (blurRadius !== radius) { blurRadius = radius; blurKernelSize = 1 + blurRadius<<1; blurKernel = new Int32Array(blurKernelSize); blurMult = new Array(blurKernelSize); for(var l = 0; l < blurKernelSize; l++){ blurMult[l] = new Int32Array(256); } var bk,bki; var bm,bmi; for (var i = 1, radiusi = radius - 1; i < radius; i++) { blurKernel[radius+i] = blurKernel[radiusi] = bki = radiusi * radiusi; bm = blurMult[radius+i]; bmi = blurMult[radiusi--]; for (var j = 0; j < 256; j++){ bm[j] = bmi[j] = bki * j; } } bk = blurKernel[radius] = radius * radius; bm = blurMult[radius]; for (var k = 0; k < 256; k++){ bm[k] = bk * k; } } } // Port of https://github.com/processing/processing/blob/ // master/core/src/processing/core/PImage.java#L1433 function blurARGB(canvas, radius) { var pixels = Filters._toPixels(canvas); var width = canvas.width; var height = canvas.height; var numPackedPixels = width * height; var argb = new Int32Array(numPackedPixels); for (var j = 0; j < numPackedPixels; j++) { argb[j] = Filters._getARGB(pixels, j); } var sum, cr, cg, cb, ca; var read, ri, ym, ymi, bk0; var a2 = new Int32Array(numPackedPixels); var r2 = new Int32Array(numPackedPixels); var g2 = new Int32Array(numPackedPixels); var b2 = new Int32Array(numPackedPixels); var yi = 0; buildBlurKernel(radius); var x, y, i; var bm; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { cb = cg = cr = ca = sum = 0; read = x - blurRadius; if (read < 0) { bk0 = -read; read = 0; } else { if (read >= width) { break; } bk0 = 0; } for (i = bk0; i < blurKernelSize; i++) { if (read >= width) { break; } var c = argb[read + yi]; bm = blurMult[i]; ca += bm[(c & -16777216) >>> 24]; cr += bm[(c & 16711680) >> 16]; cg += bm[(c & 65280) >> 8]; cb += bm[c & 255]; sum += blurKernel[i]; read++; } ri = yi + x; a2[ri] = ca / sum; r2[ri] = cr / sum; g2[ri] = cg / sum; b2[ri] = cb / sum; } yi += width; } yi = 0; ym = -blurRadius; ymi = ym * width; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { cb = cg = cr = ca = sum = 0; if (ym < 0) { bk0 = ri = -ym; read = x; } else { if (ym >= height) { break; } bk0 = 0; ri = ym; read = x + ymi; } for (i = bk0; i < blurKernelSize; i++) { if (ri >= height) { break; } bm = blurMult[i]; ca += bm[a2[read]]; cr += bm[r2[read]]; cg += bm[g2[read]]; cb += bm[b2[read]]; sum += blurKernel[i]; ri++; read += width; } argb[x + yi] = (ca/sum)<<24 | (cr/sum)<<16 | (cg/sum)<<8 | (cb/sum); } yi += width; ymi += width; ym++; } Filters._setPixels(pixels, argb); } Filters.blur = function(canvas, radius){ blurARGB(canvas, radius); }; module.exports = Filters; },{}],60:[function(_dereq_,module,exports){ module.exports = { degreesToRadians: function(x) { return 2 * Math.PI * x / 360; }, radiansToDegrees: function(x) { return 360 * x / (2 * Math.PI); } }; },{}],61:[function(_dereq_,module,exports){ /** * @module Typography * @submodule Attributes * @for p5 * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('../core/core'); /** * Sets the current alignment for drawing text. Accepts two * arguments: horizAlign (LEFT, CENTER, or RIGHT) and * vertAlign (TOP, BOTTOM, CENTER, or BASELINE). * * The horizAlign parameter is in reference to the x value * of the text() function, while the vertAlign parameter is * in reference to the y value. * * So if you write textAlign(LEFT), you are aligning the left * edge of your text to the x value you give in text(). If you * write textAlign(RIGHT, TOP), you are aligning the right edge * of your text to the x value and the top of edge of the text * to the y value. * * @method textAlign * @param {Constant} horizAlign horizontal alignment, either LEFT, * CENTER, or RIGHT * @param {Constant} [vertAlign] vertical alignment, either TOP, * BOTTOM, CENTER, or BASELINE * @return {Number} * @example *
* * textSize(16); * textAlign(RIGHT); * text("ABCD", 50, 30); * textAlign(CENTER); * text("EFGH", 50, 50); * textAlign(LEFT); * text("IJKL", 50, 70); * *
* * @alt *Letters ABCD displayed at top right, EFGH at center and IJKL at bottom left. * */ p5.prototype.textAlign = function(horizAlign, vertAlign) { return this._renderer.textAlign.apply(this._renderer, arguments); }; /** * Sets/gets the spacing, in pixels, between lines of text. This * setting will be used in all subsequent calls to the text() function. * * @method textLeading * @param {Number} leading the size in pixels for spacing between lines * @chainable */ /** * @method textLeading * @return {Number} * @example *
* * // Text to display. The "\n" is a "new line" character * lines = "L1\nL2\nL3"; * textSize(12); * * textLeading(10); // Set leading to 10 * text(lines, 10, 25); * * textLeading(20); // Set leading to 20 * text(lines, 40, 25); * * textLeading(30); // Set leading to 30 * text(lines, 70, 25); * *
* * @alt *set L1 L2 & L3 displayed vertically 3 times. spacing increases for each set * */ p5.prototype.textLeading = function(theLeading) { return this._renderer.textLeading.apply(this._renderer, arguments); }; /** * Sets/gets the current font size. This size will be used in all subsequent * calls to the text() function. Font size is measured in pixels. * * @method textSize * @param {Number} theSize the size of the letters in units of pixels * @chainable */ /** * @method textSize * @return {Number} * @example *
* * textSize(12); * text("Font Size 12", 10, 30); * textSize(14); * text("Font Size 14", 10, 60); * textSize(16); * text("Font Size 16", 10, 90); * *
* * @alt *Font Size 12 displayed small, Font Size 14 medium & Font Size 16 large * */ p5.prototype.textSize = function(theSize) { return this._renderer.textSize.apply(this._renderer, arguments); }; /** * Sets/gets the style of the text for system fonts to NORMAL, ITALIC, or BOLD. * Note: this may be is overridden by CSS styling. For non-system fonts * (opentype, truetype, etc.) please load styled fonts instead. * * @method textStyle * @param {Constant} theStyle styling for text, either NORMAL, * ITALIC, or BOLD * @chainable */ /** * @method textStyle * @return {String} * @example *
* * strokeWeight(0); * textSize(12); * textStyle(NORMAL); * text("Font Style Normal", 10, 30); * textStyle(ITALIC); * text("Font Style Italic", 10, 60); * textStyle(BOLD); * text("Font Style Bold", 10, 90); * *
* * @alt *words Font Style Normal displayed normally, Italic in italic and bold in bold * */ p5.prototype.textStyle = function(theStyle) { return this._renderer.textStyle.apply(this._renderer, arguments); }; /** * Calculates and returns the width of any character or text string. * * @method textWidth * @param {String} theText the String of characters to measure * @return {Number} * @example *
* * textSize(28); * * var aChar = 'P'; * var cWidth = textWidth(aChar); * text(aChar, 0, 40); * line(cWidth, 0, cWidth, 50); * * var aString = "p5.js"; * var sWidth = textWidth(aString); * text(aString, 0, 85); * line(sWidth, 50, sWidth, 100); * *
* * @alt *Letter P and p5.js are displayed with vertical lines at end. P is wide * */ p5.prototype.textWidth = function(theText) { if (theText.length === 0) { return 0; } return this._renderer.textWidth.apply(this._renderer, arguments); }; /** * Returns the ascent of the current font at its current size. The ascent * represents the distance, in pixels, of the tallest character above * the baseline. * @method textAscent * @return {Number} * @example *
* * var base = height * 0.75; * var scalar = 0.8; // Different for each font * * textSize(32); // Set initial text size * var asc = textAscent() * scalar; // Calc ascent * line(0, base - asc, width, base - asc); * text("dp", 0, base); // Draw text on baseline * * textSize(64); // Increase text size * asc = textAscent() * scalar; // Recalc ascent * line(40, base - asc, width, base - asc); * text("dp", 40, base); // Draw text on baseline * *
*/ p5.prototype.textAscent = function() { return this._renderer.textAscent(); }; /** * Returns the descent of the current font at its current size. The descent * represents the distance, in pixels, of the character with the longest * descender below the baseline. * @method textDescent * @return {Number} * @example *
* * var base = height * 0.75; * var scalar = 0.8; // Different for each font * * textSize(32); // Set initial text size * var desc = textDescent() * scalar; // Calc ascent * line(0, base+desc, width, base+desc); * text("dp", 0, base); // Draw text on baseline * * textSize(64); // Increase text size * desc = textDescent() * scalar; // Recalc ascent * line(40, base + desc, width, base + desc); * text("dp", 40, base); // Draw text on baseline * *
*/ p5.prototype.textDescent = function() { return this._renderer.textDescent(); }; /** * Helper function to measure ascent and descent. */ p5.prototype._updateTextMetrics = function() { return this._renderer._updateTextMetrics(); }; module.exports = p5; },{"../core/core":45}],62:[function(_dereq_,module,exports){ /** * @module Typography * @submodule Loading & Displaying * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); var constants = _dereq_('../core/constants'); var opentype = _dereq_('opentype.js'); _dereq_('../core/error_helpers'); /** * Loads an opentype font file (.otf, .ttf) from a file or a URL, * and returns a PFont Object. This method is asynchronous, * meaning it may not finish before the next line in your sketch * is executed. *

* The path to the font should be relative to the HTML file * that links in your sketch. Loading an from a URL or other * remote location may be blocked due to your browser's built-in * security. * * @method loadFont * @param {String} path name of the file or url to load * @param {Function} [callback] function to be executed after * loadFont() * completes * @return {p5.Font} p5.Font object * @example * *

Calling loadFont() inside preload() guarantees that the load * operation will have completed before setup() and draw() are called.

* *
* var myFont; * function preload() { * myFont = loadFont('assets/AvenirNextLTPro-Demi.otf'); * } * * function setup() { * fill('#ED225D'); * textFont(myFont); * textSize(36); * text('p5*js', 10, 50); * } *
* * Outside of preload(), you may supply a callback function to handle the * object: * *
* function setup() { * loadFont('assets/AvenirNextLTPro-Demi.otf', drawText); * } * * function drawText(font) { * fill('#ED225D'); * textFont(font, 36); * text('p5*js', 10, 50); * } * *
* *

You can also use the string name of the font to style other HTML * elements.

* *
* var myFont; * * function preload() { * myFont = loadFont('assets/Avenir.otf'); * } * * function setup() { * var myDiv = createDiv('hello there'); * myDiv.style('font-family', 'Avenir'); * } *
* * @alt * p5*js in p5's theme dark pink * p5*js in p5's theme dark pink * */ p5.prototype.loadFont = function (path, onSuccess, onError) { var p5Font = new p5.Font(this); var self = this; opentype.load(path, function (err, font) { if (err) { if (typeof onError !== 'undefined') { return onError(err); } p5._friendlyFileLoadError(4, path); console.error(err, path); return; } p5Font.font = font; if (typeof onSuccess !== 'undefined') { onSuccess(p5Font); } self._decrementPreload(); // check that we have an acceptable font type var validFontTypes = [ 'ttf', 'otf', 'woff', 'woff2' ], fileNoPath = path.split('\\').pop().split('/').pop(), lastDotIdx = fileNoPath.lastIndexOf('.'), fontFamily, newStyle, fileExt = lastDotIdx < 1 ? null : fileNoPath.substr(lastDotIdx + 1); // if so, add it to the DOM (name-only) for use with p5.dom if (validFontTypes.indexOf(fileExt) > -1) { fontFamily = fileNoPath.substr(0, lastDotIdx); newStyle = document.createElement('style'); newStyle.appendChild(document.createTextNode('\n@font-face {' + '\nfont-family: ' + fontFamily + ';\nsrc: url(' + path + ');\n}\n')); document.head.appendChild(newStyle); } }); return p5Font; }; /** * Draws text to the screen. Displays the information specified in the first * parameter on the screen in the position specified by the additional * parameters. A default font will be used unless a font is set with the * textFont() function and a default size will be used unless a font is set * with textSize(). Change the color of the text with the fill() function. * Change the outline of the text with the stroke() and strokeWeight() * functions. *

* The text displays in relation to the textAlign() function, which gives the * option to draw to the left, right, and center of the coordinates. *

* The x2 and y2 parameters define a rectangular area to display within and * may only be used with string data. When these parameters are specified, * they are interpreted based on the current rectMode() setting. Text that * does not fit completely within the rectangle specified will not be drawn * to the screen. * * @method text * @param {String} str the alphanumeric symbols to be displayed * @param {Number} x x-coordinate of text * @param {Number} y y-coordinate of text * @param {Number} [x2] by default, the width of the text box, * see rectMode() for more info * @param {Number} [y2] by default, the height of the text box, * see rectMode() for more info * @return {p5} this * @example *
* * textSize(32); * text("word", 10, 30); * fill(0, 102, 153); * text("word", 10, 60); * fill(0, 102, 153, 51); * text("word", 10, 90); * *
*
* * s = "The quick brown fox jumped over the lazy dog."; * fill(50); * text(s, 10, 10, 70, 80); // Text wraps within text box * *
* * @alt *'word' displayed 3 times going from black, blue to translucent blue * The quick brown fox jumped over the lazy dog. * */ p5.prototype.text = function(str, x, y, maxWidth, maxHeight) { return (!(this._renderer._doFill || this._renderer._doStroke)) ? this : this._renderer.text.apply(this._renderer, arguments); }; /** * Sets the current font that will be drawn with the text() function. * * @method textFont * @return {Object} the current font */ /** * @method textFont * @param {Object|String} font a font loaded via loadFont(), or a String * representing a web safe font (a font * that is generally available across all systems) * @param {Number} [size] the font size to use * @chainable * @example *
* * fill(0); * textSize(12); * textFont("Georgia"); * text("Georgia", 12, 30); * textFont("Helvetica"); * text("Helvetica", 12, 60); * *
*
* * var fontRegular, fontItalic, fontBold; * function preload() { * fontRegular = loadFont("assets/Regular.otf"); * fontItalic = loadFont("assets/Italic.ttf"); * fontBold = loadFont("assets/Bold.ttf"); * } * function setup() { * background(210); * fill(0).strokeWeight(0).textSize(10); * textFont(fontRegular); * text("Font Style Normal", 10, 30); * textFont(fontItalic); * text("Font Style Italic", 10, 50); * textFont(fontBold); * text("Font Style Bold", 10, 70); * } * *
* * @alt *words Font Style Normal displayed normally, Italic in italic and bold in bold * */ p5.prototype.textFont = function(theFont, theSize) { if (arguments.length) { if (!theFont) { throw Error('null font passed to textFont'); } this._renderer._setProperty('_textFont', theFont); if (theSize) { this._renderer._setProperty('_textSize', theSize); this._renderer._setProperty('_textLeading', theSize * constants._DEFAULT_LEADMULT); } return this._renderer._applyTextProperties(); } return this._renderer._textFont; }; module.exports = p5; },{"../core/constants":44,"../core/core":45,"../core/error_helpers":48,"opentype.js":15}],63:[function(_dereq_,module,exports){ /** * This module defines the p5.Font class and functions for * drawing text to the display canvas. * @module Typography * @submodule Font * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('../core/core'); var constants = _dereq_('../core/constants'); /* * TODO: * -- kerning * -- alignment: justified? */ /** * Base class for font handling * @class p5.Font * @constructor * @param {p5} [pInst] pointer to p5 instance */ p5.Font = function(p) { this.parent = p; this.cache = {}; /** * Underlying opentype font implementation * @property font */ this.font = undefined; }; p5.Font.prototype.list = function() { // TODO throw 'not yet implemented'; }; /** * Returns a tight bounding box for the given text string using this * font (currently only supports single lines) * * @method textBounds * @param {String} line a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Number} fontSize font size to use (optional) * @param {Object} options opentype options (optional) * * @return {Object} a rectangle object with properties: x, y, w, h * * @example *
* * var font; * var textString = 'Lorem ipsum dolor sit amet.'; * function preload() { * font = loadFont('./assets/Regular.otf'); * }; * function setup() { * background(210); * * var bbox = font.textBounds(textString, 10, 30, 12); * fill(255); * stroke(0); * rect(bbox.x, bbox.y, bbox.w, bbox.h); * fill(0); * noStroke(); * * textFont(font); * textSize(12); * text(textString, 10, 30); * }; * *
* * @alt *words Lorem ipsum dol go off canvas and contained by white bounding box * */ p5.Font.prototype.textBounds = function(str, x, y, fontSize, options) { x = x !== undefined ? x : 0; y = y !== undefined ? y : 0; fontSize = fontSize || this.parent._renderer._textSize; // Check cache for existing bounds. Take into consideration the text alignment // settings. Default alignment should match opentype's origin: left-aligned & // alphabetic baseline. var p = (options && options.renderer && options.renderer._pInst) || this.parent, ctx = p._renderer.drawingContext, alignment = ctx.textAlign || constants.LEFT, baseline = ctx.textBaseline || constants.BASELINE, key = cacheKey('textBounds', str, x, y, fontSize, alignment, baseline), result = this.cache[key]; if (!result) { var minX, minY, maxX, maxY, pos, xCoords = [], yCoords = [], scale = this._scale(fontSize); this.font.forEachGlyph(str, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { var gm = glyph.getMetrics(); xCoords.push(gX + (gm.xMin * scale)); xCoords.push(gX + (gm.xMax * scale)); yCoords.push(gY + (-gm.yMin * scale)); yCoords.push(gY + (-gm.yMax * scale)); }); minX = Math.min.apply(null, xCoords); minY = Math.min.apply(null, yCoords); maxX = Math.max.apply(null, xCoords); maxY = Math.max.apply(null, yCoords); result = { x: minX, y: minY, h: maxY - minY, w: maxX - minX, advance: minX - x }; // Bounds are now calculated, so shift the x & y to match alignment settings pos = this._handleAlignment(p, ctx, str, result.x, result.y, result.w + result.advance); result.x = pos.x; result.y = pos.y; this.cache[cacheKey('textBounds', str, x, y, fontSize, alignment, baseline)] = result; } return result; }; /** * Computes an array of points following the path for specified text * * @param {String} txt a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Number} fontSize font size to use (optional) * @param {Object} options an (optional) object that can contain: * *
sampleFactor - the ratio of path-length to number of samples * (default=.25); higher values yield more points and are therefore * more precise * *
simplifyThreshold - if set to a non-zero value, collinear points will be * be removed from the polygon; the value represents the threshold angle to use * when determining whether two edges are collinear * * @return {Array} an array of points, each with x, y, alpha (the path angle) */ p5.Font.prototype.textToPoints = function(txt, x, y, fontSize, options) { var xoff = 0, result = [], glyphs = this._getGlyphs(txt); fontSize = fontSize || this.parent._renderer._textSize; for (var i = 0; i < glyphs.length; i++) { if (glyphs[i].name !== 'space') { // fix to #1817 var gpath = glyphs[i].getPath(x, y, fontSize), paths = splitPaths(gpath.commands); for (var j = 0; j < paths.length; j++) { var pts = pathToPoints(paths[j], options); for (var k = 0; k < pts.length; k++) { pts[k].x += xoff; result.push(pts[k]); } } } xoff += glyphs[i].advanceWidth * this._scale(fontSize); } return result; }; // ----------------------------- End API ------------------------------ /** * Returns the set of opentype glyphs for the supplied string. * * Note that there is not a strict one-to-one mapping between characters * and glyphs, so the list of returned glyphs can be larger or smaller * than the length of the given string. * * @param {String} str the string to be converted * @return {Array} the opentype glyphs */ p5.Font.prototype._getGlyphs = function(str) { return this.font.stringToGlyphs(str); }; /** * Returns an opentype path for the supplied string and position. * * @param {String} line a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Object} options opentype options (optional) * @return {Object} the opentype path */ p5.Font.prototype._getPath = function(line, x, y, options) { var p = (options && options.renderer && options.renderer._pInst) || this.parent, ctx = p._renderer.drawingContext, pos = this._handleAlignment(p, ctx, line, x, y); return this.font.getPath(line, pos.x, pos.y, p._renderer._textSize, options); }; /* * Creates an SVG-formatted path-data string * (See http://www.w3.org/TR/SVG/paths.html#PathData) * from the given opentype path or string/position * * @param {Object} path an opentype path, OR the following: * * @param {String} line a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Object} options opentype options (optional), set options.decimals * to set the decimal precision of the path-data * * @return {Object} this p5.Font object */ p5.Font.prototype._getPathData = function(line, x, y, options) { var decimals = 3; // create path from string/position if (typeof line === 'string' && arguments.length > 2) { line = this._getPath(line, x, y, options); } // handle options specified in 2nd arg else if (typeof x === 'object') { options = x; } // handle svg arguments if (options && typeof options.decimals === 'number') { decimals = options.decimals; } return line.toPathData(decimals); }; /* * Creates an SVG element, as a string, * from the given opentype path or string/position * * @param {Object} path an opentype path, OR the following: * * @param {String} line a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Object} options opentype options (optional), set options.decimals * to set the decimal precision of the path-data in the element, * options.fill to set the fill color for the element, * options.stroke to set the stroke color for the element, * options.strokeWidth to set the strokeWidth for the element. * * @return {Object} this p5.Font object */ p5.Font.prototype._getSVG = function(line, x, y, options) { var decimals = 3; // create path from string/position if (typeof line === 'string' && arguments.length > 2) { line = this._getPath(line, x, y, options); } // handle options specified in 2nd arg else if (typeof x === 'object') { options = x; } // handle svg arguments if (options) { if (typeof options.decimals === 'number') { decimals = options.decimals; } if (typeof options.strokeWidth === 'number') { line.strokeWidth = options.strokeWidth; } if (typeof options.fill !== 'undefined') { line.fill = options.fill; } if (typeof options.stroke !== 'undefined') { line.stroke = options.stroke; } } return line.toSVG(decimals); }; /* * Renders an opentype path or string/position * to the current graphics context * * @param {Object} path an opentype path, OR the following: * * @param {String} line a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Object} options opentype options (optional) * * @return {p5.Font} this p5.Font object */ p5.Font.prototype._renderPath = function(line, x, y, options) { var pdata, pg = (options && options.renderer) || this.parent._renderer, ctx = pg.drawingContext; if (typeof line === 'object' && line.commands) { pdata = line.commands; } else { //pos = handleAlignment(p, ctx, line, x, y); pdata = this._getPath(line, x, y, options).commands; } ctx.beginPath(); for (var i = 0; i < pdata.length; i += 1) { var cmd = pdata[i]; if (cmd.type === 'M') { ctx.moveTo(cmd.x, cmd.y); } else if (cmd.type === 'L') { ctx.lineTo(cmd.x, cmd.y); } else if (cmd.type === 'C') { ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); } else if (cmd.type === 'Q') { ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y); } else if (cmd.type === 'Z') { ctx.closePath(); } } // only draw stroke if manually set by user if (pg._doStroke && pg._strokeSet) { ctx.stroke(); } if (pg._doFill) { // if fill hasn't been set by user, use default-text-fill if (!pg._fillSet) { pg._setFill(constants._DEFAULT_TEXT_FILL); } ctx.fill(); } return this; }; p5.Font.prototype._textWidth = function(str, fontSize) { return this.font.getAdvanceWidth(str, fontSize); }; p5.Font.prototype._textAscent = function(fontSize) { return this.font.ascender * this._scale(fontSize); }; p5.Font.prototype._textDescent = function(fontSize) { return -this.font.descender * this._scale(fontSize); }; p5.Font.prototype._scale = function(fontSize) { return (1 / this.font.unitsPerEm) * (fontSize || this.parent._renderer._textSize); }; p5.Font.prototype._handleAlignment = function(p, ctx, line, x, y, textWidth) { var fontSize = p._renderer._textSize, textAscent = this._textAscent(fontSize), textDescent = this._textDescent(fontSize); textWidth = textWidth !== undefined ? textWidth : this._textWidth(line, fontSize); if (ctx.textAlign === constants.CENTER) { x -= textWidth / 2; } else if (ctx.textAlign === constants.RIGHT) { x -= textWidth; } if (ctx.textBaseline === constants.TOP) { y += textAscent; } else if (ctx.textBaseline === constants._CTX_MIDDLE) { y += textAscent / 2; } else if (ctx.textBaseline === constants.BOTTOM) { y -= textDescent; } return { x: x, y: y }; }; // path-utils function pathToPoints(cmds, options) { var opts = parseOpts(options, { sampleFactor: 0.1, simplifyThreshold: 0, }); var len = pointAtLength(cmds,0,1), // total-length t = len / (len * opts.sampleFactor), pts = []; for (var i = 0; i < len; i += t) { pts.push(pointAtLength(cmds, i)); } if (opts.simplifyThreshold) { /*var count = */simplify(pts, opts.simplifyThreshold); //console.log('Simplify: removed ' + count + ' pts'); } return pts; } function simplify(pts, angle) { angle = (typeof angle === 'undefined') ? 0 : angle; var num = 0; for (var i = pts.length - 1; pts.length > 3 && i >= 0; --i) { if (collinear(at(pts, i - 1), at(pts, i), at(pts, i + 1), angle)) { // Remove the middle point pts.splice(i % pts.length, 1); num++; } } return num; } function splitPaths(cmds) { var paths = [], current; for (var i = 0; i < cmds.length; i++) { if (cmds[i].type === 'M') { if (current) { paths.push(current); } current = []; } current.push(cmdToArr(cmds[i])); } paths.push(current); return paths; } function cmdToArr(cmd) { var arr = [ cmd.type ]; if (cmd.type === 'M' || cmd.type === 'L') { // moveto or lineto arr.push(cmd.x, cmd.y); } else if (cmd.type === 'C') { arr.push(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); } else if (cmd.type === 'Q') { arr.push(cmd.x1, cmd.y1, cmd.x, cmd.y); } // else if (cmd.type === 'Z') { /* no-op */ } return arr; } function parseOpts(options, defaults) { if (typeof options !== 'object') { options = defaults; } else { for (var key in defaults) { if (typeof options[key] === 'undefined') { options[key] = defaults[key]; } } } return options; } //////////////////////// Helpers //////////////////////////// function at(v, i) { var s = v.length; return v[i < 0 ? i % s + s : i % s]; } function collinear(a, b, c, thresholdAngle) { if (!thresholdAngle) { return areaTriangle(a, b, c) === 0; } if (typeof collinear.tmpPoint1 === 'undefined') { collinear.tmpPoint1 = []; collinear.tmpPoint2 = []; } var ab = collinear.tmpPoint1, bc = collinear.tmpPoint2; ab.x = b.x - a.x; ab.y = b.y - a.y; bc.x = c.x - b.x; bc.y = c.y - b.y; var dot = ab.x * bc.x + ab.y * bc.y, magA = Math.sqrt(ab.x * ab.x + ab.y * ab.y), magB = Math.sqrt(bc.x * bc.x + bc.y * bc.y), angle = Math.acos(dot / (magA * magB)); return angle < thresholdAngle; } function areaTriangle(a, b, c) { return (((b[0] - a[0]) * (c[1] - a[1])) - ((c[0] - a[0]) * (b[1] - a[1]))); } // Portions of below code copyright 2008 Dmitry Baranovskiy (via MIT license) function findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { var t1 = 1 - t, t13 = Math.pow(t1, 3), t12 = Math.pow(t1, 2), t2 = t * t, t3 = t2 * t, x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x, y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y, mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x), my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y), nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x), ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y), ax = t1 * p1x + t * c1x, ay = t1 * p1y + t * c1y, cx = t1 * c2x + t * p2x, cy = t1 * c2y + t * p2y, alpha = (90 - Math.atan2(mx - nx, my - ny) * 180 / Math.PI); if (mx > nx || my < ny) { alpha += 180; } return { x: x, y: y, m: { x: mx, y: my }, n: { x: nx, y: ny }, start: { x: ax, y: ay }, end: { x: cx, y: cy }, alpha: alpha }; } function getPointAtSegmentLength(p1x,p1y,c1x,c1y,c2x,c2y,p2x,p2y,length) { return (length == null) ? bezlen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) : findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, getTatLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length)); } function pointAtLength(path, length, istotal) { path = path2curve(path); var x, y, p, l, sp = '', subpaths = {}, point, len = 0; for (var i = 0, ii = path.length; i < ii; i++) { p = path[i]; if (p[0] === 'M') { x = +p[1]; y = +p[2]; } else { l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]); if (len + l > length) { if (!istotal) { point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len); return { x: point.x, y: point.y, alpha: point.alpha }; } } len += l; x = +p[5]; y = +p[6]; } sp += p.shift() + p; } subpaths.end = sp; point = istotal ? len : findDotsAtSegment (x, y, p[0], p[1], p[2], p[3], p[4], p[5], 1); if (point.alpha) { point = { x: point.x, y: point.y, alpha: point.alpha }; } return point; } function pathToAbsolute(pathArray) { var res = [], x = 0, y = 0, mx = 0, my = 0, start = 0; if (pathArray[0][0] === 'M') { x = +pathArray[0][1]; y = +pathArray[0][2]; mx = x; my = y; start++; res[0] = ['M', x, y]; } var dots,crz = pathArray.length===3 && pathArray[0][0]==='M' && pathArray[1][0].toUpperCase()==='R' && pathArray[2][0].toUpperCase()==='Z'; for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) { res.push(r = []); pa = pathArray[i]; if (pa[0] !== String.prototype.toUpperCase.call(pa[0])) { r[0] = String.prototype.toUpperCase.call(pa[0]); switch (r[0]) { case 'A': r[1] = pa[1]; r[2] = pa[2]; r[3] = pa[3]; r[4] = pa[4]; r[5] = pa[5]; r[6] = +(pa[6] + x); r[7] = +(pa[7] + y); break; case 'V': r[1] = +pa[1] + y; break; case 'H': r[1] = +pa[1] + x; break; case 'R': dots = [x, y].concat(pa.slice(1)); for (var j = 2, jj = dots.length; j < jj; j++) { dots[j] = +dots[j] + x; dots[++j] = +dots[j] + y; } res.pop(); res = res.concat(catmullRom2bezier(dots, crz)); break; case 'M': mx = +pa[1] + x; my = +pa[2] + y; break; default: for (j = 1, jj = pa.length; j < jj; j++) { r[j] = +pa[j] + ((j % 2) ? x : y); } } } else if (pa[0] === 'R') { dots = [x, y].concat(pa.slice(1)); res.pop(); res = res.concat(catmullRom2bezier(dots, crz)); r = ['R'].concat(pa.slice(-2)); } else { for (var k = 0, kk = pa.length; k < kk; k++) { r[k] = pa[k]; } } switch (r[0]) { case 'Z': x = mx; y = my; break; case 'H': x = r[1]; break; case 'V': y = r[1]; break; case 'M': mx = r[r.length - 2]; my = r[r.length - 1]; break; default: x = r[r.length - 2]; y = r[r.length - 1]; } } return res; } function path2curve(path, path2) { var p = pathToAbsolute(path), p2 = path2 && pathToAbsolute(path2), attrs = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }, attrs2 = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }, processPath = function(path, d, pcom) { var nx, ny, tq = { T: 1, Q: 1 }; if (!path) { return ['C', d.x, d.y, d.x, d.y, d.x, d.y]; } if (!(path[0] in tq)) { d.qx = d.qy = null; } switch (path[0]) { case 'M': d.X = path[1]; d.Y = path[2]; break; case 'A': path = ['C'].concat(a2c.apply(0, [d.x, d.y].concat(path.slice(1)))); break; case 'S': if (pcom === 'C' || pcom === 'S') { nx = d.x * 2 - d.bx; ny = d.y * 2 - d.by; } else { nx = d.x; ny = d.y; } path = ['C', nx, ny].concat(path.slice(1)); break; case 'T': if (pcom === 'Q' || pcom === 'T') { d.qx = d.x * 2 - d.qx; d.qy = d.y * 2 - d.qy; } else { d.qx = d.x; d.qy = d.y; } path = ['C'].concat(q2c(d.x, d.y, d.qx, d.qy, path[1], path[2])); break; case 'Q': d.qx = path[1]; d.qy = path[2]; path = ['C'].concat(q2c(d.x,d.y,path[1],path[2],path[3],path[4])); break; case 'L': path = ['C'].concat(l2c(d.x, d.y, path[1], path[2])); break; case 'H': path = ['C'].concat(l2c(d.x, d.y, path[1], d.y)); break; case 'V': path = ['C'].concat(l2c(d.x, d.y, d.x, path[1])); break; case 'Z': path = ['C'].concat(l2c(d.x, d.y, d.X, d.Y)); break; } return path; }, fixArc = function(pp, i) { if (pp[i].length > 7) { pp[i].shift(); var pi = pp[i]; while (pi.length) { pcoms1[i] = 'A'; if (p2) { pcoms2[i] = 'A'; } pp.splice(i++, 0, ['C'].concat(pi.splice(0, 6))); } pp.splice(i, 1); ii = Math.max(p.length, p2 && p2.length || 0); } }, fixM = function(path1, path2, a1, a2, i) { if (path1 && path2 && path1[i][0] === 'M' && path2[i][0] !== 'M') { path2.splice(i, 0, ['M', a2.x, a2.y]); a1.bx = 0; a1.by = 0; a1.x = path1[i][1]; a1.y = path1[i][2]; ii = Math.max(p.length, p2 && p2.length || 0); } }, pcoms1 = [], // path commands of original path p pcoms2 = [], // path commands of original path p2 pfirst = '', // temporary holder for original path command pcom = ''; // holder for previous path command of original path for (var i = 0, ii = Math.max(p.length, p2 && p2.length || 0); i < ii; i++) { if (p[i]) { pfirst = p[i][0]; } // save current path command if (pfirst !== 'C') { pcoms1[i] = pfirst; // Save current path command if (i) { pcom = pcoms1[i - 1]; } // Get previous path command pcom } p[i] = processPath(p[i], attrs, pcom); if (pcoms1[i] !== 'A' && pfirst === 'C') { pcoms1[i] = 'C'; } fixArc(p, i); // fixArc adds also the right amount of A:s to pcoms1 if (p2) { // the same procedures is done to p2 if (p2[i]) { pfirst = p2[i][0]; } if (pfirst !== 'C') { pcoms2[i] = pfirst; if (i) { pcom = pcoms2[i - 1]; } } p2[i] = processPath(p2[i], attrs2, pcom); if (pcoms2[i] !== 'A' && pfirst === 'C') { pcoms2[i] = 'C'; } fixArc(p2, i); } fixM(p, p2, attrs, attrs2, i); fixM(p2, p, attrs2, attrs, i); var seg = p[i], seg2 = p2 && p2[i], seglen = seg.length, seg2len = p2 && seg2.length; attrs.x = seg[seglen - 2]; attrs.y = seg[seglen - 1]; attrs.bx = parseFloat(seg[seglen - 4]) || attrs.x; attrs.by = parseFloat(seg[seglen - 3]) || attrs.y; attrs2.bx = p2 && (parseFloat(seg2[seg2len - 4]) || attrs2.x); attrs2.by = p2 && (parseFloat(seg2[seg2len - 3]) || attrs2.y); attrs2.x = p2 && seg2[seg2len - 2]; attrs2.y = p2 && seg2[seg2len - 1]; } return p2 ? [p, p2] : p; } function a2c(x1, y1, rx, ry, angle, lac, sweep_flag, x2, y2, recursive) { // for more information of where this Math came from visit: // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes var PI = Math.PI, _120 = PI * 120 / 180, f1, f2, cx, cy, rad = PI / 180 * (+angle || 0), res = [], xy, rotate = function (x, y, rad) { var X = x * Math.cos(rad) - y * Math.sin(rad), Y = x * Math.sin(rad) + y * Math.cos(rad); return { x: X, y: Y }; }; if (!recursive) { xy = rotate(x1, y1, -rad); x1 = xy.x; y1 = xy.y; xy = rotate(x2, y2, -rad); x2 = xy.x; y2 = xy.y; var x = (x1 - x2) / 2, y = (y1 - y2) / 2, h = (x * x) / (rx * rx) + (y * y) / (ry * ry); if (h > 1) { h = Math.sqrt(h); rx = h * rx; ry = h * ry; } var rx2 = rx * rx, ry2 = ry * ry, k = (lac === sweep_flag ? -1 : 1) * Math.sqrt(Math.abs ((rx2 * ry2 - rx2 * y * y - ry2 * x * x)/(rx2 * y * y + ry2 * x * x))); cx = k * rx * y / ry + (x1 + x2) / 2; cy = k * -ry * x / rx + (y1 + y2) / 2; f1 = Math.asin(((y1 - cy) / ry).toFixed(9)); f2 = Math.asin(((y2 - cy) / ry).toFixed(9)); f1 = x1 < cx ? PI - f1 : f1; f2 = x2 < cx ? PI - f2 : f2; if (f1 < 0) { f1 = PI * 2 + f1; } if (f2 < 0) { f2 = PI * 2 + f2; } if (sweep_flag && f1 > f2) { f1 = f1 - PI * 2; } if (!sweep_flag && f2 > f1) { f2 = f2 - PI * 2; } } else { f1 = recursive[0]; f2 = recursive[1]; cx = recursive[2]; cy = recursive[3]; } var df = f2 - f1; if (Math.abs(df) > _120) { var f2old = f2, x2old = x2, y2old = y2; f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1); x2 = cx + rx * Math.cos(f2); y2 = cy + ry * Math.sin(f2); res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]); } df = f2 - f1; var c1 = Math.cos(f1), s1 = Math.sin(f1), c2 = Math.cos(f2), s2 = Math.sin(f2), t = Math.tan(df / 4), hx = 4 / 3 * rx * t, hy = 4 / 3 * ry * t, m1 = [x1, y1], m2 = [x1 + hx * s1, y1 - hy * c1], m3 = [x2 + hx * s2, y2 - hy * c2], m4 = [x2, y2]; m2[0] = 2 * m1[0] - m2[0]; m2[1] = 2 * m1[1] - m2[1]; if (recursive) { return [m2, m3, m4].concat(res); } else { res = [m2, m3, m4].concat(res).join().split(','); var newres = []; for (var i = 0, ii = res.length; i < ii; i++) { newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; } return newres; } } // http://schepers.cc/getting-to-the-point function catmullRom2bezier(crp, z) { var d = []; for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { var p = [{ x: +crp[i - 2], y: +crp[i - 1] }, { x: +crp[i], y: +crp[i + 1] }, { x: +crp[i + 2], y: +crp[i + 3] }, { x: +crp[i + 4], y: +crp[i + 5] }]; if (z) { if (!i) { p[0] = { x: +crp[iLen - 2], y: +crp[iLen - 1] }; } else if (iLen - 4 === i) { p[3] = { x: +crp[0], y: +crp[1] }; } else if (iLen - 2 === i) { p[2] = { x: +crp[0], y: +crp[1] }; p[3] = { x: +crp[2], y: +crp[3] }; } } else { if (iLen - 4 === i) { p[3] = p[2]; } else if (!i) { p[0] = { x: +crp[i], y: +crp[i + 1] }; } } d.push(['C', (-p[0].x + 6 * p[1].x + p[2].x) / 6, (-p[0].y + 6 * p[1].y + p[2].y) / 6, (p[1].x + 6 * p[2].x - p[3].x) / 6, (p[1].y + 6 * p[2].y - p[3].y) / 6, p[2].x, p[2].y ]); } return d; } function l2c(x1, y1, x2, y2) { return [x1, y1, x2, y2, x2, y2]; } function q2c(x1, y1, ax, ay, x2, y2) { var _13 = 1 / 3, _23 = 2 / 3; return [ _13 * x1 + _23 * ax, _13 * y1 + _23 * ay, _13 * x2 + _23 * ax, _13 * y2 + _23 * ay, x2, y2 ]; } function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { if (z == null) { z = 1; } z = z > 1 ? 1 : z < 0 ? 0 : z; var z2 = z / 2, n = 12, Tvalues = [-0.1252, 0.1252, -0.3678, 0.3678, -0.5873, 0.5873, -0.7699, 0.7699, -0.9041, 0.9041, -0.9816, 0.9816], sum = 0, Cvalues = [0.2491, 0.2491, 0.2335, 0.2335, 0.2032, 0.2032, 0.1601, 0.1601, 0.1069, 0.1069, 0.0472, 0.0472 ]; for (var i = 0; i < n; i++) { var ct = z2 * Tvalues[i] + z2, xbase = base3(ct, x1, x2, x3, x4), ybase = base3(ct, y1, y2, y3, y4), comb = xbase * xbase + ybase * ybase; sum += Cvalues[i] * Math.sqrt(comb); } return z2 * sum; } function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) { if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) { return; } var t = 1, step = t / 2, t2 = t - step, l, e = 0.01; l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2); while (Math.abs(l - ll) > e) { step /= 2; t2 += (l < ll ? 1 : -1) * step; l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2); } return t2; } function base3(t, p1, p2, p3, p4) { var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4, t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; return t * t2 - 3 * p1 + 3 * p2; } function cacheKey() { var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } i = args.length; var hash = ''; while (i--) { hash += (args[i] === Object(args[i])) ? JSON.stringify(args[i]) : args[i]; } return hash; } module.exports = p5; },{"../core/constants":44,"../core/core":45}],64:[function(_dereq_,module,exports){ /** * @requires constants * @todo see methods below needing further implementation. * future consideration: implement SIMD optimizations * when browser compatibility becomes available * https://developer.mozilla.org/en-US/docs/Web/JavaScript/ * Reference/Global_Objects/SIMD */ 'use strict'; var p5 = _dereq_('../core/core'); var polarGeometry = _dereq_('../math/polargeometry'); var constants = _dereq_('../core/constants'); var GLMAT_ARRAY_TYPE = ( typeof Float32Array !== 'undefined') ? Float32Array : Array; /** * A class to describe a 4x4 matrix * for model and view matrix manipulation in the p5js webgl renderer. * class p5.Matrix * @constructor * @param {Array} [mat4] array literal of our 4x4 matrix */ p5.Matrix = function() { var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } // This is default behavior when object // instantiated using createMatrix() // @todo implement createMatrix() in core/math.js if(args[0] instanceof p5) { // save reference to p5 if passed in this.p5 = args[0]; if(args[1] === 'mat3'){ this.mat3 = args[2] || new GLMAT_ARRAY_TYPE([ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]); } else { this.mat4 = args[1] || new GLMAT_ARRAY_TYPE([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]); } // default behavior when object // instantiated using new p5.Matrix() } else { if(args[0] === 'mat3'){ this.mat3 = args[1] || new GLMAT_ARRAY_TYPE([ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]); } else { this.mat4 = args[0] || new GLMAT_ARRAY_TYPE([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]); } } return this; }; /** * Sets the x, y, and z component of the vector using two or three separate * variables, the data from a p5.Matrix, or the values from a float array. * * @param {p5.Matrix|Float32Array|Array} [inMatrix] the input p5.Matrix or * an Array of length 16 * @chainable */ p5.Matrix.prototype.set = function (inMatrix) { if (inMatrix instanceof p5.Matrix) { this.mat4 = inMatrix.mat4; return this; } else if (inMatrix instanceof GLMAT_ARRAY_TYPE) { this.mat4 = inMatrix; return this; } return this; }; /** * Gets a copy of the vector, returns a p5.Matrix object. * * @return {p5.Matrix} the copy of the p5.Matrix object */ p5.Matrix.prototype.get = function () { return new p5.Matrix(this.mat4); }; /** * return a copy of a matrix * @return {p5.Matrix} the result matrix */ p5.Matrix.prototype.copy = function(){ var copied = new p5.Matrix(); copied.mat4[0] = this.mat4[0]; copied.mat4[1] = this.mat4[1]; copied.mat4[2] = this.mat4[2]; copied.mat4[3] = this.mat4[3]; copied.mat4[4] = this.mat4[4]; copied.mat4[5] = this.mat4[5]; copied.mat4[6] = this.mat4[6]; copied.mat4[7] = this.mat4[7]; copied.mat4[8] = this.mat4[8]; copied.mat4[9] = this.mat4[9]; copied.mat4[10] = this.mat4[10]; copied.mat4[11] = this.mat4[11]; copied.mat4[12] = this.mat4[12]; copied.mat4[13] = this.mat4[13]; copied.mat4[14] = this.mat4[14]; copied.mat4[15] = this.mat4[15]; return copied; }; /** * return an identity matrix * @return {p5.Matrix} the result matrix */ p5.Matrix.identity = function(){ return new p5.Matrix(); }; /** * transpose according to a given matrix * @param {p5.Matrix|Float32Array|Array} a the matrix to be based on to transpose * @chainable */ p5.Matrix.prototype.transpose = function(a){ var a01, a02, a03, a12, a13, a23; if(a instanceof p5.Matrix){ a01 = a.mat4[1]; a02 = a.mat4[2]; a03 = a.mat4[3]; a12 = a.mat4[6]; a13 = a.mat4[7]; a23 = a.mat4[11]; this.mat4[0] = a.mat4[0]; this.mat4[1] = a.mat4[4]; this.mat4[2] = a.mat4[8]; this.mat4[3] = a.mat4[12]; this.mat4[4] = a01; this.mat4[5] = a.mat4[5]; this.mat4[6] = a.mat4[9]; this.mat4[7] = a.mat4[13]; this.mat4[8] = a02; this.mat4[9] = a12; this.mat4[10] = a.mat4[10]; this.mat4[11] = a.mat4[14]; this.mat4[12] = a03; this.mat4[13] = a13; this.mat4[14] = a23; this.mat4[15] = a.mat4[15]; }else if(a instanceof GLMAT_ARRAY_TYPE){ a01 = a[1]; a02 = a[2]; a03 = a[3]; a12 = a[6]; a13 = a[7]; a23 = a[11]; this.mat4[0] = a[0]; this.mat4[1] = a[4]; this.mat4[2] = a[8]; this.mat4[3] = a[12]; this.mat4[4] = a01; this.mat4[5] = a[5]; this.mat4[6] = a[9]; this.mat4[7] = a[13]; this.mat4[8] = a02; this.mat4[9] = a12; this.mat4[10] = a[10]; this.mat4[11] = a[14]; this.mat4[12] = a03; this.mat4[13] = a13; this.mat4[14] = a23; this.mat4[15] = a[15]; } return this; }; /** * invert matrix according to a give matrix * @param {p5.Matrix|Float32Array|Array} a the matrix to be based on to invert * @chainable */ p5.Matrix.prototype.invert = function(a){ var a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23, a30, a31, a32, a33; if(a instanceof p5.Matrix){ a00 = a.mat4[0]; a01 = a.mat4[1]; a02 = a.mat4[2]; a03 = a.mat4[3]; a10 = a.mat4[4]; a11 = a.mat4[5]; a12 = a.mat4[6]; a13 = a.mat4[7]; a20 = a.mat4[8]; a21 = a.mat4[9]; a22 = a.mat4[10]; a23 = a.mat4[11]; a30 = a.mat4[12]; a31 = a.mat4[13]; a32 = a.mat4[14]; a33 = a.mat4[15]; }else if(a instanceof GLMAT_ARRAY_TYPE){ a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3]; a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7]; a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11]; a30 = a[12]; a31 = a[13]; a32 = a[14]; a33 = a[15]; } var b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32, // Calculate the determinant det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (!det) { return null; } det = 1.0 / det; this.mat4[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; this.mat4[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; this.mat4[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; this.mat4[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; this.mat4[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; this.mat4[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; this.mat4[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; this.mat4[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; this.mat4[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; this.mat4[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; this.mat4[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; this.mat4[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; this.mat4[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; this.mat4[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; this.mat4[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; this.mat4[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; return this; }; /** * Inverts a 3x3 matrix * @chainable */ p5.Matrix.prototype.invert3x3 = function (){ var a00 = this.mat3[0], a01 = this.mat3[1], a02 = this.mat3[2], a10 = this.mat3[3], a11 = this.mat3[4], a12 = this.mat3[5], a20 = this.mat3[6], a21 = this.mat3[7], a22 = this.mat3[8], b01 = a22 * a11 - a12 * a21, b11 = -a22 * a10 + a12 * a20, b21 = a21 * a10 - a11 * a20, // Calculate the determinant det = a00 * b01 + a01 * b11 + a02 * b21; if (!det) { return null; } det = 1.0 / det; this.mat3[0] = b01 * det; this.mat3[1] = (-a22 * a01 + a02 * a21) * det; this.mat3[2] = (a12 * a01 - a02 * a11) * det; this.mat3[3] = b11 * det; this.mat3[4] = (a22 * a00 - a02 * a20) * det; this.mat3[5] = (-a12 * a00 + a02 * a10) * det; this.mat3[6] = b21 * det; this.mat3[7] = (-a21 * a00 + a01 * a20) * det; this.mat3[8] = (a11 * a00 - a01 * a10) * det; return this; }; /** * transposes a 3x3 p5.Matrix by a mat3 * @param {[Number]} mat3 1-dimensional array * @chainable */ p5.Matrix.prototype.transpose3x3 = function (mat3){ var a01 = mat3[1], a02 = mat3[2], a12 = mat3[5]; this.mat3[1] = mat3[3]; this.mat3[2] = mat3[6]; this.mat3[3] = a01; this.mat3[5] = mat3[7]; this.mat3[6] = a02; this.mat3[7] = a12; return this; }; /** * converts a 4x4 matrix to its 3x3 inverse tranform * commonly used in MVMatrix to NMatrix conversions. * @param {p5.Matrix} mat4 the matrix to be based on to invert * @chainable * @todo finish implementation */ p5.Matrix.prototype.inverseTranspose = function (matrix){ if(this.mat3 === undefined){ console.error('sorry, this function only works with mat3'); } else { //convert mat4 -> mat3 this.mat3[0] = matrix.mat4[0]; this.mat3[1] = matrix.mat4[1]; this.mat3[2] = matrix.mat4[2]; this.mat3[3] = matrix.mat4[4]; this.mat3[4] = matrix.mat4[5]; this.mat3[5] = matrix.mat4[6]; this.mat3[6] = matrix.mat4[8]; this.mat3[7] = matrix.mat4[9]; this.mat3[8] = matrix.mat4[10]; } this.invert3x3().transpose3x3(this.mat3); return this; }; /** * inspired by Toji's mat4 determinant * @return {Number} Determinant of our 4x4 matrix */ p5.Matrix.prototype.determinant = function(){ var d00 = (this.mat4[0] * this.mat4[5]) - (this.mat4[1] * this.mat4[4]), d01 = (this.mat4[0] * this.mat4[6]) - (this.mat4[2] * this.mat4[4]), d02 = (this.mat4[0] * this.mat4[7]) - (this.mat4[3] * this.mat4[4]), d03 = (this.mat4[1] * this.mat4[6]) - (this.mat4[2] * this.mat4[5]), d04 = (this.mat4[1] * this.mat4[7]) - (this.mat4[3] * this.mat4[5]), d05 = (this.mat4[2] * this.mat4[7]) - (this.mat4[3] * this.mat4[6]), d06 = (this.mat4[8] * this.mat4[13]) - (this.mat4[9] * this.mat4[12]), d07 = (this.mat4[8] * this.mat4[14]) - (this.mat4[10] * this.mat4[12]), d08 = (this.mat4[8] * this.mat4[15]) - (this.mat4[11] * this.mat4[12]), d09 = (this.mat4[9] * this.mat4[14]) - (this.mat4[10] * this.mat4[13]), d10 = (this.mat4[9] * this.mat4[15]) - (this.mat4[11] * this.mat4[13]), d11 = (this.mat4[10] * this.mat4[15]) - (this.mat4[11] * this.mat4[14]); // Calculate the determinant return d00 * d11 - d01 * d10 + d02 * d09 + d03 * d08 - d04 * d07 + d05 * d06; }; /** * multiply two mat4s * @param {p5.Matrix|Float32Array|Array} multMatrix The matrix * we want to multiply by * @chainable */ p5.Matrix.prototype.mult = function(multMatrix){ var _dest = new GLMAT_ARRAY_TYPE(16); var _src = new GLMAT_ARRAY_TYPE(16); if(multMatrix instanceof p5.Matrix) { _src = multMatrix.mat4; } else if(multMatrix instanceof GLMAT_ARRAY_TYPE){ _src = multMatrix; } // each row is used for the multiplier var b0 = this.mat4[0], b1 = this.mat4[1], b2 = this.mat4[2], b3 = this.mat4[3]; _dest[0] = b0*_src[0] + b1*_src[4] + b2*_src[8] + b3*_src[12]; _dest[1] = b0*_src[1] + b1*_src[5] + b2*_src[9] + b3*_src[13]; _dest[2] = b0*_src[2] + b1*_src[6] + b2*_src[10] + b3*_src[14]; _dest[3] = b0*_src[3] + b1*_src[7] + b2*_src[11] + b3*_src[15]; b0 = this.mat4[4]; b1 = this.mat4[5]; b2 = this.mat4[6]; b3 = this.mat4[7]; _dest[4] = b0*_src[0] + b1*_src[4] + b2*_src[8] + b3*_src[12]; _dest[5] = b0*_src[1] + b1*_src[5] + b2*_src[9] + b3*_src[13]; _dest[6] = b0*_src[2] + b1*_src[6] + b2*_src[10] + b3*_src[14]; _dest[7] = b0*_src[3] + b1*_src[7] + b2*_src[11] + b3*_src[15]; b0 = this.mat4[8]; b1 = this.mat4[9]; b2 = this.mat4[10]; b3 = this.mat4[11]; _dest[8] = b0*_src[0] + b1*_src[4] + b2*_src[8] + b3*_src[12]; _dest[9] = b0*_src[1] + b1*_src[5] + b2*_src[9] + b3*_src[13]; _dest[10] = b0*_src[2] + b1*_src[6] + b2*_src[10] + b3*_src[14]; _dest[11] = b0*_src[3] + b1*_src[7] + b2*_src[11] + b3*_src[15]; b0 = this.mat4[12]; b1 = this.mat4[13]; b2 = this.mat4[14]; b3 = this.mat4[15]; _dest[12] = b0*_src[0] + b1*_src[4] + b2*_src[8] + b3*_src[12]; _dest[13] = b0*_src[1] + b1*_src[5] + b2*_src[9] + b3*_src[13]; _dest[14] = b0*_src[2] + b1*_src[6] + b2*_src[10] + b3*_src[14]; _dest[15] = b0*_src[3] + b1*_src[7] + b2*_src[11] + b3*_src[15]; this.mat4 = _dest; return this; }; /** * scales a p5.Matrix by scalars or a vector * @param {p5.Vector|Float32Array|Array} s vector to scale by * @chainable */ p5.Matrix.prototype.scale = function() { var x,y,z; var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } //if our 1st arg is a type p5.Vector if (args[0] instanceof p5.Vector){ x = args[0].x; y = args[0].y; z = args[0].z; } //otherwise if it's an array else if (args[0] instanceof Array){ x = args[0][0]; y = args[0][1]; z = args[0][2]; } var _dest = new GLMAT_ARRAY_TYPE(16); _dest[0] = this.mat4[0] * x; _dest[1] = this.mat4[1] * x; _dest[2] = this.mat4[2] * x; _dest[3] = this.mat4[3] * x; _dest[4] = this.mat4[4] * y; _dest[5] = this.mat4[5] * y; _dest[6] = this.mat4[6] * y; _dest[7] = this.mat4[7] * y; _dest[8] = this.mat4[8] * z; _dest[9] = this.mat4[9] * z; _dest[10] = this.mat4[10] * z; _dest[11] = this.mat4[11] * z; _dest[12] = this.mat4[12]; _dest[13] = this.mat4[13]; _dest[14] = this.mat4[14]; _dest[15] = this.mat4[15]; this.mat4 = _dest; return this; }; /** * rotate our Matrix around an axis by the given angle. * @param {Number} a The angle of rotation in radians * @param {p5.Vector|Array} axis the axis(es) to rotate around * @chainable * inspired by Toji's gl-matrix lib, mat4 rotation */ p5.Matrix.prototype.rotate = function(a, axis){ var x, y, z, _a, len; if (this.p5) { if (this.p5._angleMode === constants.DEGREES) { _a = polarGeometry.degreesToRadians(a); } } else { _a = a; } if (axis instanceof p5.Vector) { x = axis.x; y = axis.y; z = axis.z; } else if (axis instanceof Array) { x = axis[0]; y = axis[1]; z = axis[2]; } len = Math.sqrt(x * x + y * y + z * z); x *= (1/len); y *= (1/len); z *= (1/len); var a00 = this.mat4[0]; var a01 = this.mat4[1]; var a02 = this.mat4[2]; var a03 = this.mat4[3]; var a10 = this.mat4[4]; var a11 = this.mat4[5]; var a12 = this.mat4[6]; var a13 = this.mat4[7]; var a20 = this.mat4[8]; var a21 = this.mat4[9]; var a22 = this.mat4[10]; var a23 = this.mat4[11]; //sin,cos, and tan of respective angle var sA = Math.sin(_a); var cA = Math.cos(_a); var tA = 1 - cA; // Construct the elements of the rotation matrix var b00 = x * x * tA + cA; var b01 = y * x * tA + z * sA; var b02 = z * x * tA - y * sA; var b10 = x * y * tA - z * sA; var b11 = y * y * tA + cA; var b12 = z * y * tA + x * sA; var b20 = x * z * tA + y * sA; var b21 = y * z * tA - x * sA; var b22 = z * z * tA + cA; // rotation-specific matrix multiplication this.mat4[0] = a00 * b00 + a10 * b01 + a20 * b02; this.mat4[1] = a01 * b00 + a11 * b01 + a21 * b02; this.mat4[2] = a02 * b00 + a12 * b01 + a22 * b02; this.mat4[3] = a03 * b00 + a13 * b01 + a23 * b02; this.mat4[4] = a00 * b10 + a10 * b11 + a20 * b12; this.mat4[5] = a01 * b10 + a11 * b11 + a21 * b12; this.mat4[6] = a02 * b10 + a12 * b11 + a22 * b12; this.mat4[7] = a03 * b10 + a13 * b11 + a23 * b12; this.mat4[8] = a00 * b20 + a10 * b21 + a20 * b22; this.mat4[9] = a01 * b20 + a11 * b21 + a21 * b22; this.mat4[10] = a02 * b20 + a12 * b21 + a22 * b22; this.mat4[11] = a03 * b20 + a13 * b21 + a23 * b22; return this; }; /** * @todo finish implementing this method! * translates * @param {Number[]} v vector to translate by * @chainable */ p5.Matrix.prototype.translate = function(v){ var x = v[0], y = v[1], z = v[2] || 0; this.mat4[12] = this.mat4[0] * x +this.mat4[4] * y +this.mat4[8] * z +this.mat4[12]; this.mat4[13] = this.mat4[1] * x +this.mat4[5] * y +this.mat4[9] * z +this.mat4[13]; this.mat4[14] = this.mat4[2] * x +this.mat4[6] * y +this.mat4[10] * z +this.mat4[14]; this.mat4[15] = this.mat4[3] * x +this.mat4[7] * y +this.mat4[11] * z +this.mat4[15]; }; p5.Matrix.prototype.rotateX = function(a){ this.rotate(a, [1,0,0]); }; p5.Matrix.prototype.rotateY = function(a){ this.rotate(a, [0,1,0]); }; p5.Matrix.prototype.rotateZ = function(a){ this.rotate(a, [0,0,1]); }; /** * sets the perspective matrix * @param {Number} fovy [description] * @param {Number} aspect [description] * @param {Number} near near clipping plane * @param {Number} far far clipping plane * @chainable */ p5.Matrix.prototype.perspective = function(fovy,aspect,near,far){ var f = 1.0 / Math.tan(fovy / 2), nf = 1 / (near - far); this.mat4[0] = f / aspect; this.mat4[1] = 0; this.mat4[2] = 0; this.mat4[3] = 0; this.mat4[4] = 0; this.mat4[5] = f; this.mat4[6] = 0; this.mat4[7] = 0; this.mat4[8] = 0; this.mat4[9] = 0; this.mat4[10] = (far + near) * nf; this.mat4[11] = -1; this.mat4[12] = 0; this.mat4[13] = 0; this.mat4[14] = (2 * far * near) * nf; this.mat4[15] = 0; return this; }; /** * sets the ortho matrix * @param {Number} left [description] * @param {Number} right [description] * @param {Number} bottom [description] * @param {Number} top [description] * @param {Number} near near clipping plane * @param {Number} far far clipping plane * @chainable */ p5.Matrix.prototype.ortho = function(left,right,bottom,top,near,far){ var lr = 1 / (left - right), bt = 1 / (bottom - top), nf = 1 / (near - far); this.mat4[0] = -2 * lr; this.mat4[1] = 0; this.mat4[2] = 0; this.mat4[3] = 0; this.mat4[4] = 0; this.mat4[5] = -2 * bt; this.mat4[6] = 0; this.mat4[7] = 0; this.mat4[8] = 0; this.mat4[9] = 0; this.mat4[10] = 2 * nf; this.mat4[11] = 0; this.mat4[12] = (left + right) * lr; this.mat4[13] = (top + bottom) * bt; this.mat4[14] = (far + near) * nf; this.mat4[15] = 1; return this; }; /** * PRIVATE */ // matrix methods adapted from: // https://developer.mozilla.org/en-US/docs/Web/WebGL/ // gluPerspective // // function _makePerspective(fovy, aspect, znear, zfar){ // var ymax = znear * Math.tan(fovy * Math.PI / 360.0); // var ymin = -ymax; // var xmin = ymin * aspect; // var xmax = ymax * aspect; // return _makeFrustum(xmin, xmax, ymin, ymax, znear, zfar); // } //// //// glFrustum //// //function _makeFrustum(left, right, bottom, top, znear, zfar){ // var X = 2*znear/(right-left); // var Y = 2*znear/(top-bottom); // var A = (right+left)/(right-left); // var B = (top+bottom)/(top-bottom); // var C = -(zfar+znear)/(zfar-znear); // var D = -2*zfar*znear/(zfar-znear); // var frustrumMatrix =[ // X, 0, A, 0, // 0, Y, B, 0, // 0, 0, C, D, // 0, 0, -1, 0 //]; //return frustrumMatrix; // } // function _setMVPMatrices(){ ////an identity matrix ////@TODO use the p5.Matrix class to abstract away our MV matrices and ///other math //var _mvMatrix = //[ // 1.0,0.0,0.0,0.0, // 0.0,1.0,0.0,0.0, // 0.0,0.0,1.0,0.0, // 0.0,0.0,0.0,1.0 //]; module.exports = p5.Matrix; },{"../core/constants":44,"../core/core":45,"../math/polargeometry":60}],65:[function(_dereq_,module,exports){ 'use strict'; var p5 = _dereq_('../core/core'); var shader = _dereq_('./shader'); _dereq_('../core/p5.Renderer'); _dereq_('./p5.Matrix'); var uMVMatrixStack = []; //@TODO should implement public method //to override these attributes var attributes = { alpha: true, depth: true, stencil: true, antialias: false, premultipliedAlpha: false, preserveDrawingBuffer: false }; /** * 3D graphics class * @class p5.RendererGL * @constructor * @extends p5.Renderer * @todo extend class to include public method for offscreen * rendering (FBO). * */ p5.RendererGL = function(elt, pInst, isMainCanvas) { p5.Renderer.call(this, elt, pInst, isMainCanvas); this._initContext(); this.isP3D = true; //lets us know we're in 3d mode this.GL = this.drawingContext; //lights this.ambientLightCount = 0; this.directionalLightCount = 0; this.pointLightCount = 0; //camera this._curCamera = null; /** * model view, projection, & normal * matrices */ this.uMVMatrix = new p5.Matrix(); this.uPMatrix = new p5.Matrix(); this.uNMatrix = new p5.Matrix('mat3'); //Geometry & Material hashes this.gHash = {}; this.mHash = {}; //Imediate Mode //default drawing is done in Retained Mode this.isImmediateDrawing = false; this.immediateMode = {}; this.curFillColor = [0.5,0.5,0.5,1.0]; this.curStrokeColor = [0.5,0.5,0.5,1.0]; this.pointSize = 5.0;//default point/stroke return this; }; p5.RendererGL.prototype = Object.create(p5.Renderer.prototype); ////////////////////////////////////////////// // Setting ////////////////////////////////////////////// p5.RendererGL.prototype._initContext = function() { try { this.drawingContext = this.canvas.getContext('webgl', attributes) || this.canvas.getContext('experimental-webgl', attributes); if (this.drawingContext === null) { throw new Error('Error creating webgl context'); } else { console.log('p5.RendererGL: enabled webgl context'); var gl = this.drawingContext; gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); } } catch (er) { throw new Error(er); } }; //detect if user didn't set the camera //then call this function below p5.RendererGL.prototype._setDefaultCamera = function(){ if(this._curCamera === null){ var _w = this.width; var _h = this.height; this.uPMatrix = p5.Matrix.identity(); var cameraZ = (this.height / 2) / Math.tan(Math.PI * 30 / 180); this.uPMatrix.perspective(60 / 180 * Math.PI, _w / _h, cameraZ * 0.1, cameraZ * 10); this._curCamera = 'default'; } }; p5.RendererGL.prototype._update = function() { this.uMVMatrix = p5.Matrix.identity(); this.translate(0, 0, -(this.height / 2) / Math.tan(Math.PI * 30 / 180)); this.ambientLightCount = 0; this.directionalLightCount = 0; this.pointLightCount = 0; }; /** * [background description] */ p5.RendererGL.prototype.background = function() { var gl = this.GL; var _col = this._pInst.color.apply(this._pInst, arguments); var _r = (_col.levels[0]) / 255; var _g = (_col.levels[1]) / 255; var _b = (_col.levels[2]) / 255; var _a = (_col.levels[3]) / 255; gl.clearColor(_r, _g, _b, _a); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); }; //@TODO implement this // p5.RendererGL.prototype.clear = function() { //@TODO // }; ////////////////////////////////////////////// // SHADER ////////////////////////////////////////////// /** * [_initShaders description] * @param {string} vertId [description] * @param {string} fragId [description] * @return {Object} the shader program */ p5.RendererGL.prototype._initShaders = function(vertId, fragId, isImmediateMode) { var gl = this.GL; //set up our default shaders by: // 1. create the shader, // 2. load the shader source, // 3. compile the shader var _vertShader = gl.createShader(gl.VERTEX_SHADER); //load in our default vertex shader gl.shaderSource(_vertShader, shader[vertId]); gl.compileShader(_vertShader); // if our vertex shader failed compilation? if (!gl.getShaderParameter(_vertShader, gl.COMPILE_STATUS)) { alert('Yikes! An error occurred compiling the shaders:' + gl.getShaderInfoLog(_vertShader)); return null; } var _fragShader = gl.createShader(gl.FRAGMENT_SHADER); //load in our material frag shader gl.shaderSource(_fragShader, shader[fragId]); gl.compileShader(_fragShader); // if our frag shader failed compilation? if (!gl.getShaderParameter(_fragShader, gl.COMPILE_STATUS)) { alert('Darn! An error occurred compiling the shaders:' + gl.getShaderInfoLog(_fragShader)); return null; } var shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, _vertShader); gl.attachShader(shaderProgram, _fragShader); gl.linkProgram(shaderProgram); if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { alert('Snap! Error linking shader program'); } //END SHADERS SETUP this._getLocation(shaderProgram, isImmediateMode); return shaderProgram; }; p5.RendererGL.prototype._getLocation = function(shaderProgram, isImmediateMode) { var gl = this.GL; gl.useProgram(shaderProgram); //projection Matrix uniform shaderProgram.uPMatrixUniform = gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'); //model view Matrix uniform shaderProgram.uMVMatrixUniform = gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'); //@TODO: figure out a better way instead of if statement if(isImmediateMode === undefined){ //normal Matrix uniform shaderProgram.uNMatrixUniform = gl.getUniformLocation(shaderProgram, 'uNormalMatrix'); shaderProgram.samplerUniform = gl.getUniformLocation(shaderProgram, 'uSampler'); } }; /** * Sets a shader uniform given a shaderProgram and uniform string * @param {String} shaderKey key to material Hash. * @param {String} uniform location in shader. * @param {Number} data data to bind uniform. Float data type. * @chainable * @todo currently this function sets uniform1f data. * Should generalize function to accept any uniform * data type. */ p5.RendererGL.prototype._setUniform1f = function(shaderKey,uniform,data) { var gl = this.GL; var shaderProgram = this.mHash[shaderKey]; gl.useProgram(shaderProgram); shaderProgram[uniform] = gl.getUniformLocation(shaderProgram, uniform); gl.uniform1f(shaderProgram[uniform], data); return this; }; p5.RendererGL.prototype._setMatrixUniforms = function(shaderKey) { var gl = this.GL; var shaderProgram = this.mHash[shaderKey]; gl.useProgram(shaderProgram); gl.uniformMatrix4fv( shaderProgram.uPMatrixUniform, false, this.uPMatrix.mat4); gl.uniformMatrix4fv( shaderProgram.uMVMatrixUniform, false, this.uMVMatrix.mat4); this.uNMatrix.inverseTranspose(this.uMVMatrix); gl.uniformMatrix3fv( shaderProgram.uNMatrixUniform, false, this.uNMatrix.mat3); }; ////////////////////////////////////////////// // GET CURRENT | for shader and color ////////////////////////////////////////////// p5.RendererGL.prototype._getShader = function(vertId, fragId, isImmediateMode) { var mId = vertId + '|' + fragId; //create it and put it into hashTable if(!this.materialInHash(mId)){ var shaderProgram = this._initShaders(vertId, fragId, isImmediateMode); this.mHash[mId] = shaderProgram; } this.curShaderId = mId; return this.mHash[this.curShaderId]; }; p5.RendererGL.prototype._getCurShaderId = function(){ //if the shader ID is not yet defined if(this.drawMode !== 'fill' && this.curShaderId === undefined){ //default shader: normalMaterial() var mId = 'normalVert|normalFrag'; var shaderProgram = this._initShaders('normalVert', 'normalFrag'); this.mHash[mId] = shaderProgram; this.curShaderId = mId; } else if(this.isImmediateDrawing && this.drawMode === 'fill'){ // note that this._getShader will check if the shader already exists // by looking up the shader id (composed of vertexShaderId|fragmentShaderId) // in the material hash. If the material isn't found in the hash, it // creates a new one using this._initShaders--however, we'd like // use the cached version as often as possible, so we defer to this._getShader // here instead of calling this._initShaders directly. this._getShader('immediateVert', 'vertexColorFrag', true); } return this.curShaderId; }; ////////////////////////////////////////////// // COLOR ////////////////////////////////////////////// /** * Basic fill material for geometry with a given color * @method fill * @param {Number|Array|String|p5.Color} v1 gray value, * red or hue value (depending on the current color mode), * or color Array, or CSS color string * @param {Number} [v2] optional: green or saturation value * @param {Number} [v3] optional: blue or brightness value * @param {Number} [a] optional: opacity * @chainable * @example *
* * function setup(){ * createCanvas(100, 100, WEBGL); * } * * function draw(){ * background(0); * fill(250, 0, 0); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * rotateZ(frameCount * 0.01); * box(200, 200, 200); * } * *
* * @alt * red canvas * */ p5.RendererGL.prototype.fill = function(v1, v2, v3, a) { var gl = this.GL; var shaderProgram; //see material.js for more info on color blending in webgl var colors = this._applyColorBlend.apply(this, arguments); this.curFillColor = colors; this.drawMode = 'fill'; if(this.isImmediateDrawing){ shaderProgram = this._getShader('immediateVert','vertexColorFrag'); gl.useProgram(shaderProgram); } else { shaderProgram = this._getShader('normalVert', 'basicFrag'); gl.useProgram(shaderProgram); //RetainedMode uses a webgl uniform to pass color vals //in ImmediateMode, we want access to each vertex so therefore //we cannot use a uniform. shaderProgram.uMaterialColor = gl.getUniformLocation( shaderProgram, 'uMaterialColor' ); gl.uniform4f( shaderProgram.uMaterialColor, colors[0], colors[1], colors[2], colors[3]); } return this; }; p5.RendererGL.prototype.stroke = function(r, g, b, a) { var color = this._pInst.color.apply(this._pInst, arguments); var colorNormalized = color._array; this.curStrokeColor = colorNormalized; this.drawMode = 'stroke'; return this; }; //@TODO p5.RendererGL.prototype._strokeCheck = function(){ if(this.drawMode === 'stroke'){ throw new Error( 'stroke for shapes in 3D not yet implemented, use fill for now :(' ); } }; /** * [strokeWeight description] * @param {Number} pointSize stroke point size * @chainable * @todo strokeWeight currently works on points only. * implement on all wireframes and strokes. */ p5.RendererGL.prototype.strokeWeight = function(pointSize) { this.pointSize = pointSize; return this; }; ////////////////////////////////////////////// // HASH | for material and geometry ////////////////////////////////////////////// p5.RendererGL.prototype.geometryInHash = function(gId){ return this.gHash[gId] !== undefined; }; p5.RendererGL.prototype.materialInHash = function(mId){ return this.mHash[mId] !== undefined; }; /** * [resize description] * @param {Number} w [description] * @param {Number} h [description] */ p5.RendererGL.prototype.resize = function(w,h) { var gl = this.GL; p5.Renderer.prototype.resize.call(this, w, h); gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); // If we're using the default camera, update the aspect ratio if(this._curCamera === 'default') { this._curCamera = null; this._setDefaultCamera(); } }; /** * clears color and depth buffers * with r,g,b,a * @param {Number} r normalized red val. * @param {Number} g normalized green val. * @param {Number} b normalized blue val. * @param {Number} a normalized alpha val. */ p5.RendererGL.prototype.clear = function() { var gl = this.GL; gl.clearColor(arguments[0], arguments[1], arguments[2], arguments[3]); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); }; /** * [translate description] * @param {Number} x [description] * @param {Number} y [description] * @param {Number} z [description] * @chainable * @todo implement handle for components or vector as args */ p5.RendererGL.prototype.translate = function(x, y, z) { this.uMVMatrix.translate([x,-y,z]); return this; }; /** * Scales the Model View Matrix by a vector * @param {Number | p5.Vector | Array} x [description] * @param {Number} [y] y-axis scalar * @param {Number} [z] z-axis scalar * @chainable */ p5.RendererGL.prototype.scale = function(x,y,z) { this.uMVMatrix.scale([x,y,z]); return this; }; p5.RendererGL.prototype.rotate = function(rad, axis){ this.uMVMatrix.rotate(rad, axis); return this; }; p5.RendererGL.prototype.rotateX = function(rad) { this.rotate(rad, [1,0,0]); return this; }; p5.RendererGL.prototype.rotateY = function(rad) { this.rotate(rad, [0,1,0]); return this; }; p5.RendererGL.prototype.rotateZ = function(rad) { this.rotate(rad, [0,0,1]); return this; }; /** * pushes a copy of the model view matrix onto the * MV Matrix stack. */ p5.RendererGL.prototype.push = function() { uMVMatrixStack.push(this.uMVMatrix.copy()); }; /** * [pop description] */ p5.RendererGL.prototype.pop = function() { if (uMVMatrixStack.length === 0) { throw new Error('Invalid popMatrix!'); } this.uMVMatrix = uMVMatrixStack.pop(); }; p5.RendererGL.prototype.resetMatrix = function() { this.uMVMatrix = p5.Matrix.identity(); this.translate(0, 0, -800); return this; }; // Text/Typography // @TODO: p5.RendererGL.prototype._applyTextProperties = function() { //@TODO finish implementation console.error('text commands not yet implemented in webgl'); }; module.exports = p5.RendererGL; },{"../core/core":45,"../core/p5.Renderer":52,"./p5.Matrix":64,"./shader":66}],66:[function(_dereq_,module,exports){ module.exports = { immediateVert: "attribute vec3 aPosition;\nattribute vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uResolution;\nuniform float uPointSize;\n\nvarying vec4 vColor;\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition * vec3(1.0, -1.0, 1.0), 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vColor = aVertexColor;\n gl_PointSize = uPointSize;\n}\n", vertexColorVert: "attribute vec3 aPosition;\nattribute vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nvarying vec4 vColor;\n\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition * vec3(1.0, -1.0, 1.0), 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vColor = aVertexColor;\n}\n", vertexColorFrag: "precision mediump float;\nvarying vec4 vColor;\nvoid main(void) {\n gl_FragColor = vColor;\n}", normalVert: "attribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nvarying vec3 vVertexNormal;\nvarying highp vec2 vVertTexCoord;\n\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition * vec3(1.0, -1.0, 1.0), 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vVertexNormal = vec3( uNormalMatrix * aNormal );\n vVertTexCoord = aTexCoord;\n}\n", normalFrag: "precision mediump float;\nvarying vec3 vVertexNormal;\nvoid main(void) {\n gl_FragColor = vec4(vVertexNormal, 1.0);\n}", basicFrag: "precision mediump float;\nvarying vec3 vVertexNormal;\nuniform vec4 uMaterialColor;\nvoid main(void) {\n gl_FragColor = uMaterialColor;\n}", lightVert: "attribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\nuniform int uAmbientLightCount;\nuniform int uDirectionalLightCount;\nuniform int uPointLightCount;\n\nuniform vec3 uAmbientColor[8];\nuniform vec3 uLightingDirection[8];\nuniform vec3 uDirectionalColor[8];\nuniform vec3 uPointLightLocation[8];\nuniform vec3 uPointLightColor[8];\nuniform bool uSpecular;\n\nvarying vec3 vVertexNormal;\nvarying vec2 vVertTexCoord;\nvarying vec3 vLightWeighting;\n\nvec3 ambientLightFactor = vec3(0.0, 0.0, 0.0);\nvec3 directionalLightFactor = vec3(0.0, 0.0, 0.0);\nvec3 pointLightFactor = vec3(0.0, 0.0, 0.0);\nvec3 pointLightFactor2 = vec3(0.0, 0.0, 0.0);\n\nvoid main(void){\n\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n\n vec3 vertexNormal = vec3( uNormalMatrix * aNormal );\n vVertexNormal = vertexNormal;\n vVertTexCoord = aTexCoord;\n\n vec4 mvPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n vec3 eyeDirection = normalize(-mvPosition.xyz);\n\n float shininess = 32.0;\n float specularFactor = 2.0;\n float diffuseFactor = 0.3;\n\n for(int i = 0; i < 8; i++){\n if(uAmbientLightCount == i) break;\n ambientLightFactor += uAmbientColor[i];\n }\n\n for(int j = 0; j < 8; j++){\n if(uDirectionalLightCount == j) break;\n vec3 dir = uLightingDirection[j];\n float directionalLightWeighting = max(dot(vertexNormal, dir), 0.0);\n directionalLightFactor += uDirectionalColor[j] * directionalLightWeighting;\n }\n\n for(int k = 0; k < 8; k++){\n if(uPointLightCount == k) break;\n vec3 loc = uPointLightLocation[k];\n vec3 lightDirection = normalize(loc - mvPosition.xyz);\n\n float directionalLightWeighting = max(dot(vertexNormal, lightDirection), 0.0);\n pointLightFactor += uPointLightColor[k] * directionalLightWeighting;\n\n //factor2 for specular\n vec3 reflectionDirection = reflect(-lightDirection, vertexNormal);\n float specularLightWeighting = pow(max(dot(reflectionDirection, eyeDirection), 0.0), shininess);\n\n pointLightFactor2 += uPointLightColor[k] * (specularFactor * specularLightWeighting\n + directionalLightWeighting * diffuseFactor);\n }\n\n if(!uSpecular){\n vLightWeighting = ambientLightFactor + directionalLightFactor + pointLightFactor;\n }else{\n vLightWeighting = ambientLightFactor + directionalLightFactor + pointLightFactor2;\n }\n\n}\n", lightTextureFrag: "precision mediump float;\n\nuniform vec4 uMaterialColor;\nuniform sampler2D uSampler;\nuniform bool isTexture;\n\nvarying vec3 vLightWeighting;\nvarying highp vec2 vVertTexCoord;\n\nvoid main(void) {\n if(!isTexture){\n gl_FragColor = vec4(vec3(uMaterialColor.rgb * vLightWeighting), uMaterialColor.a);\n }else{\n vec4 textureColor = texture2D(uSampler, vVertTexCoord);\n if(vLightWeighting == vec3(0., 0., 0.)){\n gl_FragColor = textureColor;\n }else{\n gl_FragColor = vec4(vec3(textureColor.rgb * vLightWeighting), textureColor.a);\n }\n }\n}" }; },{}]},{},[45,50,63,51,53,44,47,54,41,42,46,58,56,57,61,62,49])(63) });