Skip to content

Instantly share code, notes, and snippets.

@z3t0
Created April 14, 2015 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save z3t0/59d860ac23c1d33e227f to your computer and use it in GitHub Desktop.
Save z3t0/59d860ac23c1d33e227f to your computer and use it in GitHub Desktop.
VoxelMetaverse Compiled Code
This file has been truncated, but you can view the full file.
(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<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
},{}],2:[function(require,module,exports){
// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// when used in node, this will actually load the util module we depend on
// versus loading the builtin util module as happens otherwise
// this is a bug in node module loading as far as I am concerned
var util = require('util/');
var pSlice = Array.prototype.slice;
var hasOwn = Object.prototype.hasOwnProperty;
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = module.exports = ok;
// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
// actual: actual,
// expected: expected })
assert.AssertionError = function AssertionError(options) {
this.name = 'AssertionError';
this.actual = options.actual;
this.expected = options.expected;
this.operator = options.operator;
if (options.message) {
this.message = options.message;
this.generatedMessage = false;
} else {
this.message = getMessage(this);
this.generatedMessage = true;
}
var stackStartFunction = options.stackStartFunction || fail;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, stackStartFunction);
}
else {
// non v8 browsers so we can have a stacktrace
var err = new Error();
if (err.stack) {
var out = err.stack;
// try to strip useless frames
var fn_name = stackStartFunction.name;
var idx = out.indexOf('\n' + fn_name);
if (idx >= 0) {
// once we have located the function frame
// we need to strip out everything before it (and its line)
var next_line = out.indexOf('\n', idx + 1);
out = out.substring(next_line + 1);
}
this.stack = out;
}
}
};
// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);
function replacer(key, value) {
if (util.isUndefined(value)) {
return '' + value;
}
if (util.isNumber(value) && !isFinite(value)) {
return value.toString();
}
if (util.isFunction(value) || util.isRegExp(value)) {
return value.toString();
}
return value;
}
function truncate(s, n) {
if (util.isString(s)) {
return s.length < n ? s : s.slice(0, n);
} else {
return s;
}
}
function getMessage(self) {
return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' +
self.operator + ' ' +
truncate(JSON.stringify(self.expected, replacer), 128);
}
// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.
// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided. All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.
function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}
// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;
// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.
function ok(value, message) {
if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;
// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);
assert.equal = function equal(actual, expected, message) {
if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};
// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);
assert.notEqual = function notEqual(actual, expected, message) {
if (actual == expected) {
fail(actual, expected, message, '!=', assert.notEqual);
}
};
// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);
assert.deepEqual = function deepEqual(actual, expected, message) {
if (!_deepEqual(actual, expected)) {
fail(actual, expected, message, 'deepEqual', assert.deepEqual);
}
};
function _deepEqual(actual, expected) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (util.isBuffer(actual) && util.isBuffer(expected)) {
if (actual.length != expected.length) return false;
for (var i = 0; i < actual.length; i++) {
if (actual[i] !== expected[i]) return false;
}
return true;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (util.isDate(actual) && util.isDate(expected)) {
return actual.getTime() === expected.getTime();
// 7.3 If the expected value is a RegExp object, the actual value is
// equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
} else if (util.isRegExp(actual) && util.isRegExp(expected)) {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.multiline === expected.multiline &&
actual.lastIndex === expected.lastIndex &&
actual.ignoreCase === expected.ignoreCase;
// 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (!util.isObject(actual) && !util.isObject(expected)) {
return actual == expected;
// 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected);
}
}
function isArguments(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function objEquiv(a, b) {
if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b))
return false;
// an identical 'prototype' property.
if (a.prototype !== b.prototype) return false;
// if one is a primitive, the other must be same
if (util.isPrimitive(a) || util.isPrimitive(b)) {
return a === b;
}
var aIsArgs = isArguments(a),
bIsArgs = isArguments(b);
if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
return false;
if (aIsArgs) {
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b);
}
var ka = objectKeys(a),
kb = objectKeys(b),
key, i;
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key])) return false;
}
return true;
}
// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (_deepEqual(actual, expected)) {
fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
}
};
// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);
assert.strictEqual = function strictEqual(actual, expected, message) {
if (actual !== expected) {
fail(actual, expected, message, '===', assert.strictEqual);
}
};
// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (actual === expected) {
fail(actual, expected, message, '!==', assert.notStrictEqual);
}
};
function expectedException(actual, expected) {
if (!actual || !expected) {
return false;
}
if (Object.prototype.toString.call(expected) == '[object RegExp]') {
return expected.test(actual);
} else if (actual instanceof expected) {
return true;
} else if (expected.call({}, actual) === true) {
return true;
}
return false;
}
function _throws(shouldThrow, block, expected, message) {
var actual;
if (util.isString(expected)) {
message = expected;
expected = null;
}
try {
block();
} catch (e) {
actual = e;
}
message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
(message ? ' ' + message : '.');
if (shouldThrow && !actual) {
fail(actual, expected, 'Missing expected exception' + message);
}
if (!shouldThrow && expectedException(actual, expected)) {
fail(actual, expected, 'Got unwanted exception' + message);
}
if ((shouldThrow && actual && expected &&
!expectedException(actual, expected)) || (!shouldThrow && actual)) {
throw actual;
}
}
// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);
assert.throws = function(block, /*optional*/error, /*optional*/message) {
_throws.apply(this, [true].concat(pSlice.call(arguments)));
};
// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/message) {
_throws.apply(this, [false].concat(pSlice.call(arguments)));
};
assert.ifError = function(err) { if (err) {throw err;}};
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
if (hasOwn.call(obj, key)) keys.push(key);
}
return keys;
};
},{"util/":40}],3:[function(require,module,exports){
arguments[4][1][0].apply(exports,arguments)
},{"dup":1}],4:[function(require,module,exports){
'use strict';
var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
(typeof Uint16Array !== 'undefined') &&
(typeof Int32Array !== 'undefined');
exports.assign = function (obj /*from1, from2, from3, ...*/) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) { continue; }
if (typeof(source) !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (var p in source) {
if (source.hasOwnProperty(p)) {
obj[p] = source[p];
}
}
}
return obj;
};
// reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
if (buf.length === size) { return buf; }
if (buf.subarray) { return buf.subarray(0, size); }
buf.length = size;
return buf;
};
var fnTyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
return;
}
// Fallback to ordinary array
for(var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
var i, l, len, pos, chunk, result;
// calculate data length
len = 0;
for (i=0, l=chunks.length; i<l; i++) {
len += chunks[i].length;
}
// join chunks
result = new Uint8Array(len);
pos = 0;
for (i=0, l=chunks.length; i<l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
};
var fnUntyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
for(var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
return [].concat.apply([], chunks);
}
};
// Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
if (on) {
exports.Buf8 = Uint8Array;
exports.Buf16 = Uint16Array;
exports.Buf32 = Int32Array;
exports.assign(exports, fnTyped);
} else {
exports.Buf8 = Array;
exports.Buf16 = Array;
exports.Buf32 = Array;
exports.assign(exports, fnUntyped);
}
};
exports.setTyped(TYPED_OK);
},{}],5:[function(require,module,exports){
'use strict';
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It doesn't worth to make additional optimizationa as in original.
// Small size is preferable.
function adler32(adler, buf, len, pos) {
var s1 = (adler & 0xffff) |0
, s2 = ((adler >>> 16) & 0xffff) |0
, n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = (s1 + buf[pos++]) |0;
s2 = (s2 + s1) |0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return (s1 | (s2 << 16)) |0;
}
module.exports = adler32;
},{}],6:[function(require,module,exports){
module.exports = {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
//Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8
//Z_NULL: null // Use -1 or null inline, depending on var type
};
},{}],7:[function(require,module,exports){
'use strict';
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// Use ordinary array, since untyped makes no boost here
function makeTable() {
var c, table = [];
for(var n =0; n < 256; n++){
c = n;
for(var k =0; k < 8; k++){
c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
}
// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable
, end = pos + len;
crc = crc ^ (-1);
for (var i = pos; i < end; i++ ) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
module.exports = crc32;
},{}],8:[function(require,module,exports){
'use strict';
var utils = require('../utils/common');
var trees = require('./trees');
var adler32 = require('./adler32');
var crc32 = require('./crc32');
var msg = require('./messages');
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
var Z_NO_FLUSH = 0;
var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
//var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
//var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
//var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* compression levels */
//var Z_NO_COMPRESSION = 0;
//var Z_BEST_SPEED = 1;
//var Z_BEST_COMPRESSION = 9;
var Z_DEFAULT_COMPRESSION = -1;
var Z_FILTERED = 1;
var Z_HUFFMAN_ONLY = 2;
var Z_RLE = 3;
var Z_FIXED = 4;
var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
//var Z_BINARY = 0;
//var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/* The deflate compression method */
var Z_DEFLATED = 8;
/*============================================================================*/
var MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_MEM_LEVEL = 8;
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
var PRESET_DICT = 0x20;
var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;
var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
var BS_BLOCK_DONE = 2; /* block flush performed */
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
function err(strm, errorCode) {
strm.msg = msg[errorCode];
return errorCode;
}
function rank(f) {
return ((f) << 1) - ((f) > 4 ? 9 : 0);
}
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
/* =========================================================================
* Flush as much pending output as possible. All deflate() output goes
* through this function so some applications may wish to modify it
* to avoid allocating a large strm->output buffer and copying into it.
* (See also read_buf()).
*/
function flush_pending(strm) {
var s = strm.state;
//_tr_flush_bits(s);
var len = s.pending;
if (len > strm.avail_out) {
len = strm.avail_out;
}
if (len === 0) { return; }
utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
strm.next_out += len;
s.pending_out += len;
strm.total_out += len;
strm.avail_out -= len;
s.pending -= len;
if (s.pending === 0) {
s.pending_out = 0;
}
}
function flush_block_only (s, last) {
trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
s.block_start = s.strstart;
flush_pending(s.strm);
}
function put_byte(s, b) {
s.pending_buf[s.pending++] = b;
}
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
function putShortMSB(s, b) {
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b & 0xff));
s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
s.pending_buf[s.pending++] = b & 0xff;
}
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->input buffer and copying from it.
* (See also flush_pending()).
*/
function read_buf(strm, buf, start, size) {
var len = strm.avail_in;
if (len > size) { len = size; }
if (len === 0) { return 0; }
strm.avail_in -= len;
utils.arraySet(buf, strm.input, strm.next_in, len, start);
if (strm.state.wrap === 1) {
strm.adler = adler32(strm.adler, buf, len, start);
}
else if (strm.state.wrap === 2) {
strm.adler = crc32(strm.adler, buf, len, start);
}
strm.next_in += len;
strm.total_in += len;
return len;
}
/* ===========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead.
*/
function longest_match(s, cur_match) {
var chain_length = s.max_chain_length; /* max hash chain length */
var scan = s.strstart; /* current string */
var match; /* matched string */
var len; /* length of current match */
var best_len = s.prev_length; /* best match length so far */
var nice_match = s.nice_match; /* stop if match long enough */
var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
var _win = s.window; // shortcut
var wmask = s.w_mask;
var prev = s.prev;
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
var strend = s.strstart + MAX_MATCH;
var scan_end1 = _win[scan + best_len - 1];
var scan_end = _win[scan + best_len];
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
// Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */
if (s.prev_length >= s.good_match) {
chain_length >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (nice_match > s.lookahead) { nice_match = s.lookahead; }
// Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
do {
// Assert(cur_match < s->strstart, "no future");
match = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/
if (_win[match + best_len] !== scan_end ||
_win[match + best_len - 1] !== scan_end1 ||
_win[match] !== _win[scan] ||
_win[++match] !== _win[scan + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2;
match++;
// Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
/*jshint noempty:false*/
} while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
scan < strend);
// Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
s.match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = _win[scan + best_len - 1];
scan_end = _win[scan + best_len];
}
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
if (best_len <= s.lookahead) {
return best_len;
}
return s.lookahead;
}
/* ===========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
function fill_window(s) {
var _w_size = s.w_size;
var p, n, m, more, str;
//Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
do {
more = s.window_size - s.lookahead - s.strstart;
// JS ints have 32 bit, block below not needed
/* Deal with !@#$% 64K limit: */
//if (sizeof(int) <= 2) {
// if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
// more = wsize;
//
// } else if (more == (unsigned)(-1)) {
// /* Very unlikely, but possible on 16 bit machine if
// * strstart == 0 && lookahead == 1 (input done a byte at time)
// */
// more--;
// }
//}
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
s.match_start -= _w_size;
s.strstart -= _w_size;
/* we now have strstart >= MAX_DIST */
s.block_start -= _w_size;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
n = s.hash_size;
p = n;
do {
m = s.head[--p];
s.head[p] = (m >= _w_size ? m - _w_size : 0);
} while (--n);
n = _w_size;
p = n;
do {
m = s.prev[--p];
s.prev[p] = (m >= _w_size ? m - _w_size : 0);
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
more += _w_size;
}
if (s.strm.avail_in === 0) {
break;
}
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
//Assert(more >= 2, "more < 2");
n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
s.lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s.lookahead + s.insert >= MIN_MATCH) {
str = s.strstart - s.insert;
s.ins_h = s.window[str];
/* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call update_hash() MIN_MATCH-3 more times
//#endif
while (s.insert) {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
s.insert--;
if (s.lookahead + s.insert < MIN_MATCH) {
break;
}
}
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
// if (s.high_water < s.window_size) {
// var curr = s.strstart + s.lookahead;
// var init = 0;
//
// if (s.high_water < curr) {
// /* Previous high water mark below current data -- zero WIN_INIT
// * bytes or up to end of window, whichever is less.
// */
// init = s.window_size - curr;
// if (init > WIN_INIT)
// init = WIN_INIT;
// zmemzero(s->window + curr, (unsigned)init);
// s->high_water = curr + init;
// }
// else if (s->high_water < (ulg)curr + WIN_INIT) {
// /* High water mark at or above current data, but below current data
// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
// * to end of window, whichever is less.
// */
// init = (ulg)curr + WIN_INIT - s->high_water;
// if (init > s->window_size - s->high_water)
// init = s->window_size - s->high_water;
// zmemzero(s->window + s->high_water, (unsigned)init);
// s->high_water += init;
// }
// }
//
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
// "not enough room for search");
}
/* ===========================================================================
* Copy without compression as much as possible from the input stream, return
* the current block state.
* This function does not insert new strings in the dictionary since
* uncompressible data is probably not useful. This function is used
* only for the level=0 compression option.
* NOTE: this function should be optimized to avoid extra copying from
* window to pending_buf.
*/
function deflate_stored(s, flush) {
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited
* to pending_buf_size, and each stored block has a 5 byte header:
*/
var max_block_size = 0xffff;
if (max_block_size > s.pending_buf_size - 5) {
max_block_size = s.pending_buf_size - 5;
}
/* Copy as much as possible from input to output: */
for (;;) {
/* Fill the window as much as possible: */
if (s.lookahead <= 1) {
//Assert(s->strstart < s->w_size+MAX_DIST(s) ||
// s->block_start >= (long)s->w_size, "slide too late");
// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
// s.block_start >= s.w_size)) {
// throw new Error("slide too late");
// }
fill_window(s);
if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
/* flush the current block */
}
//Assert(s->block_start >= 0L, "block gone");
// if (s.block_start < 0) throw new Error("block gone");
s.strstart += s.lookahead;
s.lookahead = 0;
/* Emit a stored block if pending_buf will be full: */
var max_start = s.block_start + max_block_size;
if (s.strstart === 0 || s.strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */
s.lookahead = s.strstart - max_start;
s.strstart = max_start;
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
/* Flush if we may have to slide, otherwise block_start may become
* negative and the data will be gone:
*/
if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.strstart > s.block_start) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_NEED_MORE;
}
/* ===========================================================================
* Compress as much as possible from the input stream, return the current
* block state.
* This function does not perform lazy evaluation of matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
function deflate_fast(s, flush) {
var hash_head; /* head of the hash chain */
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break; /* flush the current block */
}
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
}
if (s.match_length >= MIN_MATCH) {
// check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
/*** _tr_tally_dist(s, s.strstart - s.match_start,
s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
s.match_length--; /* string at strstart already in table */
do {
s.strstart++;
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead.
*/
} while (--s.match_length !== 0);
s.strstart++;
} else
{
s.strstart += s.match_length;
s.match_length = 0;
s.ins_h = s.window[s.strstart];
/* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s.window[s.strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
function deflate_slow(s, flush) {
var hash_head; /* head of hash chain */
var bflush; /* set if current block must be flushed */
var max_insert;
/* Process the input block. */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
*/
s.prev_length = s.match_length;
s.prev_match = s.match_start;
s.match_length = MIN_MATCH-1;
if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
if (s.match_length <= 5 &&
(s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
s.match_length = MIN_MATCH-1;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
max_insert = s.strstart + s.lookahead - MIN_MATCH;
/* Do not insert strings in hash table beyond this. */
//check_match(s, s.strstart-1, s.prev_match, s.prev_length);
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
s.prev_length - MIN_MATCH, bflush);***/
bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in
* the hash table.
*/
s.lookahead -= s.prev_length-1;
s.prev_length -= 2;
do {
if (++s.strstart <= max_insert) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
} while (--s.prev_length !== 0);
s.match_available = 0;
s.match_length = MIN_MATCH-1;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
} else if (s.match_available) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
if (bflush) {
/*** FLUSH_BLOCK_ONLY(s, 0) ***/
flush_block_only(s, false);
/***/
}
s.strstart++;
s.lookahead--;
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
s.match_available = 1;
s.strstart++;
s.lookahead--;
}
}
//Assert (flush != Z_NO_FLUSH, "no flush?");
if (s.match_available) {
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
s.match_available = 0;
}
s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
function deflate_rle(s, flush) {
var bflush; /* set if current block must be flushed */
var prev; /* byte at distance one to match */
var scan, strend; /* scan goes up to strend for length of run */
var _win = s.window;
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest run, plus one for the unrolled loop.
*/
if (s.lookahead <= MAX_MATCH) {
fill_window(s);
if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* See how many times the previous byte repeats */
s.match_length = 0;
if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
scan = s.strstart - 1;
prev = _win[scan];
if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
strend = s.strstart + MAX_MATCH;
do {
/*jshint noempty:false*/
} while (prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
scan < strend);
s.match_length = MAX_MATCH - (strend - scan);
if (s.match_length > s.lookahead) {
s.match_length = s.lookahead;
}
}
//Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (s.match_length >= MIN_MATCH) {
//check_match(s, s.strstart, s.strstart - 1, s.match_length);
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
s.strstart += s.match_length;
s.match_length = 0;
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
function deflate_huff(s, flush) {
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
break; /* flush the current block */
}
}
/* Output a literal byte */
s.match_length = 0;
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
};
var configuration_table;
configuration_table = [
/* good lazy nice chain */
new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
new Config(4, 5, 16, 8, deflate_fast), /* 2 */
new Config(4, 6, 32, 32, deflate_fast), /* 3 */
new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
new Config(8, 16, 32, 32, deflate_slow), /* 5 */
new Config(8, 16, 128, 128, deflate_slow), /* 6 */
new Config(8, 32, 128, 256, deflate_slow), /* 7 */
new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
];
/* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream
*/
function lm_init(s) {
s.window_size = 2 * s.w_size;
/*** CLEAR_HASH(s); ***/
zero(s.head); // Fill with NIL (= 0);
/* Set the default configuration parameters:
*/
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
s.ins_h = 0;
}
function DeflateState() {
this.strm = null; /* pointer back to this zlib stream */
this.status = 0; /* as the name implies */
this.pending_buf = null; /* output still pending */
this.pending_buf_size = 0; /* size of pending_buf */
this.pending_out = 0; /* next pending byte to output to the stream */
this.pending = 0; /* nb of bytes in the pending buffer */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.gzhead = null; /* gzip header information to write */
this.gzindex = 0; /* where in extra, name, or comment */
this.method = Z_DEFLATED; /* can only be DEFLATED */
this.last_flush = -1; /* value of flush param for previous deflate call */
this.w_size = 0; /* LZ77 window size (32K by default) */
this.w_bits = 0; /* log2(w_size) (8..16) */
this.w_mask = 0; /* w_size - 1 */
this.window = null;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size.
*/
this.window_size = 0;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
this.prev = null;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
this.head = null; /* Heads of the hash chains or NIL. */
this.ins_h = 0; /* hash index of string to be inserted */
this.hash_size = 0; /* number of elements in hash table */
this.hash_bits = 0; /* log2(hash_size) */
this.hash_mask = 0; /* hash_size-1 */
this.hash_shift = 0;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
this.block_start = 0;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
this.match_length = 0; /* length of best match */
this.prev_match = 0; /* previous match */
this.match_available = 0; /* set if previous match exists */
this.strstart = 0; /* start of string to insert */
this.match_start = 0; /* start of matching string */
this.lookahead = 0; /* number of valid bytes ahead in window */
this.prev_length = 0;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
this.max_chain_length = 0;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
this.max_lazy_match = 0;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
// That's alias to max_lazy_match, don't use directly
//this.max_insert_length = 0;
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
this.level = 0; /* compression level (1..9) */
this.strategy = 0; /* favor or force Huffman coding*/
this.good_match = 0;
/* Use a faster search when the previous match is longer than this */
this.nice_match = 0; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
// struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
// struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
// struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
// Use flat array of DOUBLE size, with interleaved fata,
// because JS does not support effective
this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
zero(this.dyn_ltree);
zero(this.dyn_dtree);
zero(this.bl_tree);
this.l_desc = null; /* desc. for literal tree */
this.d_desc = null; /* desc. for distance tree */
this.bl_desc = null; /* desc. for bit length tree */
//ush bl_count[MAX_BITS+1];
this.bl_count = new utils.Buf16(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
//int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
zero(this.heap);
this.heap_len = 0; /* number of elements in the heap */
this.heap_max = 0; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
zero(this.depth);
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
this.l_buf = 0; /* buffer index for literals or lengths */
this.lit_bufsize = 0;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
this.last_lit = 0; /* running index in l_buf */
this.d_buf = 0;
/* Buffer index for distances. To simplify the code, d_buf and l_buf have
* the same number of elements. To use different lengths, an extra flag
* array would be necessary.
*/
this.opt_len = 0; /* bit length of current block with optimal trees */
this.static_len = 0; /* bit length of current block with static trees */
this.matches = 0; /* number of string matches in current block */
this.insert = 0; /* bytes at end of window left to insert */
this.bi_buf = 0;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
this.bi_valid = 0;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
// Used for window memory init. We safely ignore it for JS. That makes
// sense only for pointers and memory check tools.
//this.high_water = 0;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
}
function deflateResetKeep(strm) {
var s;
if (!strm || !strm.state) {
return err(strm, Z_STREAM_ERROR);
}
strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN;
s = strm.state;
s.pending = 0;
s.pending_out = 0;
if (s.wrap < 0) {
s.wrap = -s.wrap;
/* was made negative by deflate(..., Z_FINISH); */
}
s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
strm.adler = (s.wrap === 2) ?
0 // crc32(0, Z_NULL, 0)
:
1; // adler32(0, Z_NULL, 0)
s.last_flush = Z_NO_FLUSH;
trees._tr_init(s);
return Z_OK;
}
function deflateReset(strm) {
var ret = deflateResetKeep(strm);
if (ret === Z_OK) {
lm_init(strm.state);
}
return ret;
}
function deflateSetHeader(strm, head) {
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
strm.state.gzhead = head;
return Z_OK;
}
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
if (!strm) { // === Z_NULL
return Z_STREAM_ERROR;
}
var wrap = 1;
if (level === Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (windowBits < 0) { /* suppress zlib wrapper */
wrap = 0;
windowBits = -windowBits;
}
else if (windowBits > 15) {
wrap = 2; /* write gzip wrapper instead */
windowBits -= 16;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED) {
return err(strm, Z_STREAM_ERROR);
}
if (windowBits === 8) {
windowBits = 9;
}
/* until 256-byte window bug fixed */
var s = new DeflateState();
strm.state = s;
s.strm = strm;
s.wrap = wrap;
s.gzhead = null;
s.w_bits = windowBits;
s.w_size = 1 << s.w_bits;
s.w_mask = s.w_size - 1;
s.hash_bits = memLevel + 7;
s.hash_size = 1 << s.hash_bits;
s.hash_mask = s.hash_size - 1;
s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
s.window = new utils.Buf8(s.w_size * 2);
s.head = new utils.Buf16(s.hash_size);
s.prev = new utils.Buf16(s.w_size);
// Don't need mem init magic for JS.
//s.high_water = 0; /* nothing written to s->window yet */
s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
s.pending_buf_size = s.lit_bufsize * 4;
s.pending_buf = new utils.Buf8(s.pending_buf_size);
s.d_buf = s.lit_bufsize >> 1;
s.l_buf = (1 + 2) * s.lit_bufsize;
s.level = level;
s.strategy = strategy;
s.method = method;
return deflateReset(strm);
}
function deflateInit(strm, level) {
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
function deflate(strm, flush) {
var old_flush, s;
var beg, val; // for gzip header write only
if (!strm || !strm.state ||
flush > Z_BLOCK || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
}
s = strm.state;
if (!strm.output ||
(!strm.input && strm.avail_in !== 0) ||
(s.status === FINISH_STATE && flush !== Z_FINISH)) {
return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
}
s.strm = strm; /* just in case */
old_flush = s.last_flush;
s.last_flush = flush;
/* Write the header */
if (s.status === INIT_STATE) {
if (s.wrap === 2) { // GZIP header
strm.adler = 0; //crc32(0L, Z_NULL, 0);
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (!s.gzhead) { // s->gzhead == Z_NULL
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, OS_CODE);
s.status = BUSY_STATE;
}
else {
put_byte(s, (s.gzhead.text ? 1 : 0) +
(s.gzhead.hcrc ? 2 : 0) +
(!s.gzhead.extra ? 0 : 4) +
(!s.gzhead.name ? 0 : 8) +
(!s.gzhead.comment ? 0 : 16)
);
put_byte(s, s.gzhead.time & 0xff);
put_byte(s, (s.gzhead.time >> 8) & 0xff);
put_byte(s, (s.gzhead.time >> 16) & 0xff);
put_byte(s, (s.gzhead.time >> 24) & 0xff);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, s.gzhead.os & 0xff);
if (s.gzhead.extra && s.gzhead.extra.length) {
put_byte(s, s.gzhead.extra.length & 0xff);
put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
}
if (s.gzhead.hcrc) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
}
s.gzindex = 0;
s.status = EXTRA_STATE;
}
}
else // DEFLATE header
{
var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
var level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0;
} else if (s.level < 6) {
level_flags = 1;
} else if (s.level === 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= (level_flags << 6);
if (s.strstart !== 0) { header |= PRESET_DICT; }
header += 31 - (header % 31);
s.status = BUSY_STATE;
putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */
if (s.strstart !== 0) {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
strm.adler = 1; // adler32(0L, Z_NULL, 0);
}
}
//#ifdef GZIP
if (s.status === EXTRA_STATE) {
if (s.gzhead.extra/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
break;
}
}
put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
s.gzindex++;
}
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (s.gzindex === s.gzhead.extra.length) {
s.gzindex = 0;
s.status = NAME_STATE;
}
}
else {
s.status = NAME_STATE;
}
}
if (s.status === NAME_STATE) {
if (s.gzhead.name/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.name.length) {
val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg){
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.gzindex = 0;
s.status = COMMENT_STATE;
}
}
else {
s.status = COMMENT_STATE;
}
}
if (s.status === COMMENT_STATE) {
if (s.gzhead.comment/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.comment.length) {
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.status = HCRC_STATE;
}
}
else {
s.status = HCRC_STATE;
}
}
if (s.status === HCRC_STATE) {
if (s.gzhead.hcrc) {
if (s.pending + 2 > s.pending_buf_size) {
flush_pending(strm);
}
if (s.pending + 2 <= s.pending_buf_size) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
strm.adler = 0; //crc32(0L, Z_NULL, 0);
s.status = BUSY_STATE;
}
}
else {
s.status = BUSY_STATE;
}
}
//#endif
/* Flush as much pending output as possible */
if (s.pending !== 0) {
flush_pending(strm);
if (strm.avail_out === 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s.last_flush = -1;
return Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
flush !== Z_FINISH) {
return err(strm, Z_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
return err(strm, Z_BUF_ERROR);
}
/* Start a new block or continue the current one.
*/
if (strm.avail_in !== 0 || s.lookahead !== 0 ||
(flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
(s.strategy === Z_RLE ? deflate_rle(s, flush) :
configuration_table[s.level].func(s, flush));
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
s.status = FINISH_STATE;
}
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
if (strm.avail_out === 0) {
s.last_flush = -1;
/* avoid BUF_ERROR next call, see above */
}
return Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) {
trees._tr_align(s);
}
else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
trees._tr_stored_block(s, 0, 0, false);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush === Z_FULL_FLUSH) {
/*** CLEAR_HASH(s); ***/ /* forget history */
zero(s.head); // Fill with NIL (= 0);
if (s.lookahead === 0) {
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return Z_OK;
}
}
}
//Assert(strm->avail_out > 0, "bug2");
//if (strm.avail_out <= 0) { throw new Error("bug2");}
if (flush !== Z_FINISH) { return Z_OK; }
if (s.wrap <= 0) { return Z_STREAM_END; }
/* Write the trailer */
if (s.wrap === 2) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
put_byte(s, (strm.adler >> 16) & 0xff);
put_byte(s, (strm.adler >> 24) & 0xff);
put_byte(s, strm.total_in & 0xff);
put_byte(s, (strm.total_in >> 8) & 0xff);
put_byte(s, (strm.total_in >> 16) & 0xff);
put_byte(s, (strm.total_in >> 24) & 0xff);
}
else
{
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s.wrap > 0) { s.wrap = -s.wrap; }
/* write the trailer only once! */
return s.pending !== 0 ? Z_OK : Z_STREAM_END;
}
function deflateEnd(strm) {
var status;
if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
return Z_STREAM_ERROR;
}
status = strm.state.status;
if (status !== INIT_STATE &&
status !== EXTRA_STATE &&
status !== NAME_STATE &&
status !== COMMENT_STATE &&
status !== HCRC_STATE &&
status !== BUSY_STATE &&
status !== FINISH_STATE
) {
return err(strm, Z_STREAM_ERROR);
}
strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}
/* =========================================================================
* Copy the source state to the destination state
*/
//function deflateCopy(dest, source) {
//
//}
exports.deflateInit = deflateInit;
exports.deflateInit2 = deflateInit2;
exports.deflateReset = deflateReset;
exports.deflateResetKeep = deflateResetKeep;
exports.deflateSetHeader = deflateSetHeader;
exports.deflate = deflate;
exports.deflateEnd = deflateEnd;
exports.deflateInfo = 'pako deflate (from Nodeca project)';
/* Not implemented
exports.deflateBound = deflateBound;
exports.deflateCopy = deflateCopy;
exports.deflateSetDictionary = deflateSetDictionary;
exports.deflateParams = deflateParams;
exports.deflatePending = deflatePending;
exports.deflatePrime = deflatePrime;
exports.deflateTune = deflateTune;
*/
},{"../utils/common":4,"./adler32":5,"./crc32":7,"./messages":12,"./trees":13}],9:[function(require,module,exports){
'use strict';
// See state defs from inflate.js
var BAD = 30; /* got a data error -- remain here until reset */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
module.exports = function inflate_fast(strm, start) {
var state;
var _in; /* local strm.input */
var last; /* have enough input while in < last */
var _out; /* local strm.output */
var beg; /* inflate()'s initial strm.output */
var end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
var dmax; /* maximum distance from zlib header */
//#endif
var wsize; /* window size or zero if not using window */
var whave; /* valid bytes in the window */
var wnext; /* window write index */
var window; /* allocated sliding window, if wsize != 0 */
var hold; /* local strm.hold */
var bits; /* local strm.bits */
var lcode; /* local strm.lencode */
var dcode; /* local strm.distcode */
var lmask; /* mask for first level of length codes */
var dmask; /* mask for first level of distance codes */
var here; /* retrieved table entry */
var op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
var len; /* match length, unused bytes */
var dist; /* match distance */
var from; /* where to copy match from */
var from_source;
var input, output; // JS specific, because we have no pointers
/* copy state to local variables */
state = strm.state;
//here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
dmax = state.dmax;
//#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;;) { // Goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op === 0) { /* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff/*here.val*/;
}
else if (op & 16) { /* length base */
len = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
//Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;;) { // goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op & 16) { /* distance base */
dist = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
//#endif
hold >>>= op;
bits -= op;
//Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg; /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // window index
from_source = window;
if (wnext === 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
output[_out++] = window[from++];
} while (--op);
from = 0;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
output[_out++] = window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
}
else {
from = _out - dist; /* copy direct from output */
do { /* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
}
else if ((op & 64) === 0) { /* 2nd level distance code */
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dodist;
}
else {
strm.msg = 'invalid distance code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
}
else if ((op & 64) === 0) { /* 2nd level length code */
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dolen;
}
else if (op & 32) { /* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE;
break top;
}
else {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
state.hold = hold;
state.bits = bits;
return;
};
},{}],10:[function(require,module,exports){
'use strict';
var utils = require('../utils/common');
var adler32 = require('./adler32');
var crc32 = require('./crc32');
var inflate_fast = require('./inffast');
var inflate_table = require('./inftrees');
var CODES = 0;
var LENS = 1;
var DISTS = 2;
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
//var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* The deflate compression method */
var Z_DEFLATED = 8;
/* STATES ====================================================================*/
/* ===========================================================================*/
var HEAD = 1; /* i: waiting for magic header */
var FLAGS = 2; /* i: waiting for method and flags (gzip) */
var TIME = 3; /* i: waiting for modification time (gzip) */
var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
var EXLEN = 5; /* i: waiting for extra length (gzip) */
var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
var NAME = 7; /* i: waiting for end of file name (gzip) */
var COMMENT = 8; /* i: waiting for end of comment (gzip) */
var HCRC = 9; /* i: waiting for header crc (gzip) */
var DICTID = 10; /* i: waiting for dictionary check value */
var DICT = 11; /* waiting for inflateSetDictionary() call */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
var STORED = 14; /* i: waiting for stored size (length and complement) */
var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
var COPY = 16; /* i/o: waiting for input or output to copy stored block */
var TABLE = 17; /* i: waiting for dynamic block table lengths */
var LENLENS = 18; /* i: waiting for code length code lengths */
var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
var LEN_ = 20; /* i: same as LEN below, but only first time in */
var LEN = 21; /* i: waiting for length/lit/eob code */
var LENEXT = 22; /* i: waiting for length extra bits */
var DIST = 23; /* i: waiting for distance code */
var DISTEXT = 24; /* i: waiting for distance extra bits */
var MATCH = 25; /* o: waiting for output space to copy string */
var LIT = 26; /* o: waiting for output space to write literal */
var CHECK = 27; /* i: waiting for 32-bit check value */
var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
var DONE = 29; /* finished check, done -- remain here until reset */
var BAD = 30; /* got a data error -- remain here until reset */
var MEM = 31; /* got an inflate() memory error -- remain here until reset */
var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS;
function ZSWAP32(q) {
return (((q >>> 24) & 0xff) +
((q >>> 8) & 0xff00) +
((q & 0xff00) << 8) +
((q & 0xff) << 24));
}
function InflateState() {
this.mode = 0; /* current inflate mode */
this.last = false; /* true if processing last block */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.havedict = false; /* true if dictionary provided */
this.flags = 0; /* gzip header method and flags (0 if zlib) */
this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
this.check = 0; /* protected copy of check value */
this.total = 0; /* protected copy of output count */
// TODO: may be {}
this.head = null; /* where to save gzip header information */
/* sliding window */
this.wbits = 0; /* log base 2 of requested window size */
this.wsize = 0; /* window size or zero if not using window */
this.whave = 0; /* valid bytes in the window */
this.wnext = 0; /* window write index */
this.window = null; /* allocated sliding window, if needed */
/* bit accumulator */
this.hold = 0; /* input bit accumulator */
this.bits = 0; /* number of bits in "in" */
/* for string and stored block copying */
this.length = 0; /* literal or length of data to copy */
this.offset = 0; /* distance back to copy string from */
/* for table and code decoding */
this.extra = 0; /* extra bits needed */
/* fixed and dynamic code tables */
this.lencode = null; /* starting table for length/literal codes */
this.distcode = null; /* starting table for distance codes */
this.lenbits = 0; /* index bits for lencode */
this.distbits = 0; /* index bits for distcode */
/* dynamic table building */
this.ncode = 0; /* number of code length code lengths */
this.nlen = 0; /* number of length code lengths */
this.ndist = 0; /* number of distance code lengths */
this.have = 0; /* number of code lengths in lens[] */
this.next = null; /* next available space in codes[] */
this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
this.work = new utils.Buf16(288); /* work area for code table building */
/*
because we don't have pointers in js, we use lencode and distcode directly
as buffers so we don't need codes
*/
//this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
this.distdyn = null; /* dynamic table for distance codes (JS specific) */
this.sane = 0; /* if false, allow invalid distance too far */
this.back = 0; /* bits back of last unprocessed length/lit */
this.was = 0; /* initial length of match */
}
function inflateResetKeep(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = ''; /*Z_NULL*/
if (state.wrap) { /* to support ill-conceived Java test suite */
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.dmax = 32768;
state.head = null/*Z_NULL*/;
state.hold = 0;
state.bits = 0;
//state.lencode = state.distcode = state.next = state.codes;
state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
state.sane = 1;
state.back = -1;
//Tracev((stderr, "inflate: reset\n"));
return Z_OK;
}
function inflateReset(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
}
function inflateReset2(strm, windowBits) {
var wrap;
var state;
/* get the state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
/* extract wrap request from windowBits parameter */
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
}
else {
wrap = (windowBits >> 4) + 1;
if (windowBits < 48) {
windowBits &= 15;
}
}
/* set number of window bits, free window if different */
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR;
}
if (state.window !== null && state.wbits !== windowBits) {
state.window = null;
}
/* update state and reset the rest of it */
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
}
function inflateInit2(strm, windowBits) {
var ret;
var state;
if (!strm) { return Z_STREAM_ERROR; }
//strm.msg = Z_NULL; /* in case we return an error */
state = new InflateState();
//if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n"));
strm.state = state;
state.window = null/*Z_NULL*/;
ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK) {
strm.state = null/*Z_NULL*/;
}
return ret;
}
function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS);
}
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe.
*/
var virgin = true;
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
function fixedtables(state) {
/* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) {
var sym;
lenfix = new utils.Buf32(512);
distfix = new utils.Buf32(32);
/* literal/length table */
sym = 0;
while (sym < 144) { state.lens[sym++] = 8; }
while (sym < 256) { state.lens[sym++] = 9; }
while (sym < 280) { state.lens[sym++] = 7; }
while (sym < 288) { state.lens[sym++] = 8; }
inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
/* distance table */
sym = 0;
while (sym < 32) { state.lens[sym++] = 5; }
inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
/* do this just once */
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
}
/*
Update the window with the last wsize (normally 32K) bytes written before
returning. If window does not exist yet, create it. This is only called
when a window is already in use, or when output has been written during this
inflate call, but the end of the deflate stream has not been reached yet.
It is also called to create a window for dictionary data when a dictionary
is loaded.
Providing output buffers larger than 32K to inflate() should provide a speed
advantage, since only the last 32K of output is copied to the sliding window
upon return from inflate(), and since all distances after the first 32K of
output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches.
*/
function updatewindow(strm, src, end, copy) {
var dist;
var state = strm.state;
/* if it hasn't been done already, allocate space for the window */
if (state.window === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.window = new utils.Buf8(state.wsize);
}
/* copy state->wsize or less output bytes into the circular window */
if (copy >= state.wsize) {
utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
state.wnext = 0;
state.whave = state.wsize;
}
else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
}
//zmemcpy(state->window + state->wnext, end - copy, dist);
utils.arraySet(state.window,src, end - copy, dist, state.wnext);
copy -= dist;
if (copy) {
//zmemcpy(state->window, end - copy, copy);
utils.arraySet(state.window,src, end - copy, copy, 0);
state.wnext = copy;
state.whave = state.wsize;
}
else {
state.wnext += dist;
if (state.wnext === state.wsize) { state.wnext = 0; }
if (state.whave < state.wsize) { state.whave += dist; }
}
}
return 0;
}
function inflate(strm, flush) {
var state;
var input, output; // input/output buffers
var next; /* next input INDEX */
var put; /* next output INDEX */
var have, left; /* available input and output */
var hold; /* bit buffer */
var bits; /* bits in bit buffer */
var _in, _out; /* save starting available input and output */
var copy; /* number of stored or match bytes to copy */
var from; /* where to copy match bytes from */
var from_source;
var here = 0; /* current decoding table entry */
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//var last; /* parent table entry */
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
var len; /* length to copy for repeats, bits to drop */
var ret; /* return code */
var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
var opts;
var n; // temporary var for NEED_BITS
var order = /* permutation of code lengths */
[16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
if (!strm || !strm.state || !strm.output ||
(!strm.input && strm.avail_in !== 0)) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
_in = have;
_out = left;
ret = Z_OK;
inf_leave: // goto emulation
for (;;) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
}
//=== NEEDBITS(16);
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
state.check = 0/*crc32(0L, Z_NULL, 0)*/;
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = FLAGS;
break;
}
state.flags = 0; /* expect zlib header */
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) || /* check if zlib header allowed */
(((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
strm.msg = 'incorrect header check';
state.mode = BAD;
break;
}
if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
len = (hold & 0x0f)/*BITS(4)*/ + 8;
if (state.wbits === 0) {
state.wbits = len;
}
else if (len > state.wbits) {
strm.msg = 'invalid window size';
state.mode = BAD;
break;
}
state.dmax = 1 << len;
//Tracev((stderr, "inflate: zlib header ok\n"));
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = hold & 0x200 ? DICTID : TYPE;
//=== INITBITS();
hold = 0;
bits = 0;
//===//
break;
case FLAGS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.flags = hold;
if ((state.flags & 0xff) !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
if (state.flags & 0xe000) {
strm.msg = 'unknown header flags set';
state.mode = BAD;
break;
}
if (state.head) {
state.head.text = ((hold >> 8) & 1);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = TIME;
/* falls through */
case TIME:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.time = hold;
}
if (state.flags & 0x0200) {
//=== CRC4(state.check, hold)
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
hbuf[2] = (hold >>> 16) & 0xff;
hbuf[3] = (hold >>> 24) & 0xff;
state.check = crc32(state.check, hbuf, 4, 0);
//===
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = OS;
/* falls through */
case OS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.xflags = (hold & 0xff);
state.head.os = (hold >> 8);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = EXLEN;
/* falls through */
case EXLEN:
if (state.flags & 0x0400) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
else if (state.head) {
state.head.extra = null/*Z_NULL*/;
}
state.mode = EXTRA;
/* falls through */
case EXTRA:
if (state.flags & 0x0400) {
copy = state.length;
if (copy > have) { copy = have; }
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
// Use untyped array for more conveniend processing later
state.head.extra = new Array(state.head.extra_len);
}
utils.arraySet(
state.head.extra,
input,
next,
// extra field is limited to 65536 bytes
// - no need for additional size check
copy,
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
len
);
//zmemcpy(state.head.extra + len, next,
// len + copy > state.head.extra_max ?
// state.head.extra_max - len : copy);
}
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) { break inf_leave; }
}
state.length = 0;
state.mode = NAME;
/* falls through */
case NAME:
if (state.flags & 0x0800) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
// TODO: 2 or 1 bytes?
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.name_max*/)) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
/* falls through */
case COMMENT:
if (state.flags & 0x1000) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.comm_max*/)) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
/* falls through */
case HCRC:
if (state.flags & 0x0200) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.check & 0xffff)) {
strm.msg = 'header crc mismatch';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
if (state.head) {
state.head.hcrc = ((state.flags >> 9) & 1);
state.head.done = true;
}
strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
break;
case DICTID:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
strm.adler = state.check = ZSWAP32(hold);
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = DICT;
/* falls through */
case DICT:
if (state.havedict === 0) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
return Z_NEED_DICT;
}
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
/* falls through */
case TYPE:
if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
/* falls through */
case TYPEDO:
if (state.last) {
//--- BYTEBITS() ---//
hold >>>= bits & 7;
bits -= bits & 7;
//---//
state.mode = CHECK;
break;
}
//=== NEEDBITS(3); */
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.last = (hold & 0x01)/*BITS(1)*/;
//--- DROPBITS(1) ---//
hold >>>= 1;
bits -= 1;
//---//
switch ((hold & 0x03)/*BITS(2)*/) {
case 0: /* stored block */
//Tracev((stderr, "inflate: stored block%s\n",
// state.last ? " (last)" : ""));
state.mode = STORED;
break;
case 1: /* fixed block */
fixedtables(state);
//Tracev((stderr, "inflate: fixed codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = LEN_; /* decode codes */
if (flush === Z_TREES) {
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break inf_leave;
}
break;
case 2: /* dynamic block */
//Tracev((stderr, "inflate: dynamic codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = TABLE;
break;
case 3:
strm.msg = 'invalid block type';
state.mode = BAD;
}
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break;
case STORED:
//--- BYTEBITS() ---// /* go to byte boundary */
hold >>>= bits & 7;
bits -= bits & 7;
//---//
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
strm.msg = 'invalid stored block lengths';
state.mode = BAD;
break;
}
state.length = hold & 0xffff;
//Tracev((stderr, "inflate: stored length %u\n",
// state.length));
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = COPY_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case COPY_:
state.mode = COPY;
/* falls through */
case COPY:
copy = state.length;
if (copy) {
if (copy > have) { copy = have; }
if (copy > left) { copy = left; }
if (copy === 0) { break inf_leave; }
//--- zmemcpy(put, next, copy); ---
utils.arraySet(output, input, next, copy, put);
//---//
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
}
//Tracev((stderr, "inflate: stored end\n"));
state.mode = TYPE;
break;
case TABLE:
//=== NEEDBITS(14); */
while (bits < 14) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
//#ifndef PKZIP_BUG_WORKAROUND
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = 'too many length or distance symbols';
state.mode = BAD;
break;
}
//#endif
//Tracev((stderr, "inflate: table sizes ok\n"));
state.have = 0;
state.mode = LENLENS;
/* falls through */
case LENLENS:
while (state.have < state.ncode) {
//=== NEEDBITS(3);
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
}
// We have separate tables & no pointers. 2 commented lines below not needed.
//state.next = state.codes;
//state.lencode = state.next;
// Switch to use dynamic table
state.lencode = state.lendyn;
state.lenbits = 7;
opts = {bits: state.lenbits};
ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = 'invalid code lengths set';
state.mode = BAD;
break;
}
//Tracev((stderr, "inflate: code lengths ok\n"));
state.have = 0;
state.mode = CODELENS;
/* falls through */
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_val < 16) {
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.lens[state.have++] = here_val;
}
else {
if (here_val === 16) {
//=== NEEDBITS(here.bits + 2);
n = here_bits + 2;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
if (state.have === 0) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 0x03);//BITS(2);
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
}
else if (here_val === 17) {
//=== NEEDBITS(here.bits + 3);
n = here_bits + 3;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 3 + (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
else {
//=== NEEDBITS(here.bits + 7);
n = here_bits + 7;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 11 + (hold & 0x7f);//BITS(7);
//--- DROPBITS(7) ---//
hold >>>= 7;
bits -= 7;
//---//
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
/* handle error breaks in while */
if (state.mode === BAD) { break; }
/* check for end-of-block code (better have one) */
if (state.lens[256] === 0) {
strm.msg = 'invalid code -- missing end-of-block';
state.mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state.lenbits = 9;
opts = {bits: state.lenbits};
ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.lenbits = opts.bits;
// state.lencode = state.next;
if (ret) {
strm.msg = 'invalid literal/lengths set';
state.mode = BAD;
break;
}
state.distbits = 6;
//state.distcode.copy(state.codes);
// Switch to use dynamic table
state.distcode = state.distdyn;
opts = {bits: state.distbits};
ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.distbits = opts.bits;
// state.distcode = state.next;
if (ret) {
strm.msg = 'invalid distances set';
state.mode = BAD;
break;
}
//Tracev((stderr, 'inflate: codes ok\n'));
state.mode = LEN_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case LEN_:
state.mode = LEN;
/* falls through */
case LEN:
if (have >= 6 && left >= 258) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
inflate_fast(strm, _out);
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
if (state.mode === TYPE) {
state.back = -1;
}
break;
}
state.back = 0;
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_op && (here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.lencode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
state.mode = LIT;
break;
}
if (here_op & 32) {
//Tracevv((stderr, "inflate: end of block\n"));
state.back = -1;
state.mode = TYPE;
break;
}
if (here_op & 64) {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
/* falls through */
case LENEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//Tracevv((stderr, "inflate: length %u\n", state.length));
state.was = state.length;
state.mode = DIST;
/* falls through */
case DIST:
for (;;) {
here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if ((here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.distcode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
if (here_op & 64) {
strm.msg = 'invalid distance code';
state.mode = BAD;
break;
}
state.offset = here_val;
state.extra = (here_op) & 15;
state.mode = DISTEXT;
/* falls through */
case DISTEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//#ifdef INFLATE_STRICT
if (state.offset > state.dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
//#endif
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
state.mode = MATCH;
/* falls through */
case MATCH:
if (left === 0) { break inf_leave; }
copy = _out - left;
if (state.offset > copy) { /* copy from window */
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// Trace((stderr, "inflate.c too far\n"));
// copy -= state.whave;
// if (copy > state.length) { copy = state.length; }
// if (copy > left) { copy = left; }
// left -= copy;
// state.length -= copy;
// do {
// output[put++] = 0;
// } while (--copy);
// if (state.length === 0) { state.mode = LEN; }
// break;
//#endif
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
}
else {
from = state.wnext - copy;
}
if (copy > state.length) { copy = state.length; }
from_source = state.window;
}
else { /* copy from output */
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) { copy = left; }
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) { state.mode = LEN; }
break;
case LIT:
if (left === 0) { break inf_leave; }
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
// Use '|' insdead of '+' to make sure that result is signed
hold |= input[next++] << bits;
bits += 8;
}
//===//
_out -= left;
strm.total_out += _out;
state.total += _out;
if (_out) {
strm.adler = state.check =
/*UPDATE(state.check, put - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
}
_out = left;
// NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
strm.msg = 'incorrect data check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: check matches trailer\n"));
}
state.mode = LENGTH;
/* falls through */
case LENGTH:
if (state.wrap && state.flags) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.total & 0xffffffff)) {
strm.msg = 'incorrect length check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: length matches trailer\n"));
}
state.mode = DONE;
/* falls through */
case DONE:
ret = Z_STREAM_END;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR;
break inf_leave;
case MEM:
return Z_MEM_ERROR;
case SYNC:
/* falls through */
default:
return Z_STREAM_ERROR;
}
}
// inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
/*
Return from inflate(), updating the total counts and the check value.
If there was no progress during the inflate() call, return a buffer
error. Call updatewindow() to create and/or update the window state.
Note: a memory error from inflate() is non-recoverable.
*/
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
(state.mode < CHECK || flush !== Z_FINISH))) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
state.mode = MEM;
return Z_MEM_ERROR;
}
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if (state.wrap && _out) {
strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
}
strm.data_type = state.bits + (state.last ? 64 : 0) +
(state.mode === TYPE ? 128 : 0) +
(state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
ret = Z_BUF_ERROR;
}
return ret;
}
function inflateEnd(strm) {
if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
return Z_STREAM_ERROR;
}
var state = strm.state;
if (state.window) {
state.window = null;
}
strm.state = null;
return Z_OK;
}
function inflateGetHeader(strm, head) {
var state;
/* check state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
/* save header structure */
state.head = head;
head.done = false;
return Z_OK;
}
exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2;
exports.inflateResetKeep = inflateResetKeep;
exports.inflateInit = inflateInit;
exports.inflateInit2 = inflateInit2;
exports.inflate = inflate;
exports.inflateEnd = inflateEnd;
exports.inflateGetHeader = inflateGetHeader;
exports.inflateInfo = 'pako inflate (from Nodeca project)';
/* Not implemented
exports.inflateCopy = inflateCopy;
exports.inflateGetDictionary = inflateGetDictionary;
exports.inflateMark = inflateMark;
exports.inflatePrime = inflatePrime;
exports.inflateSetDictionary = inflateSetDictionary;
exports.inflateSync = inflateSync;
exports.inflateSyncPoint = inflateSyncPoint;
exports.inflateUndermine = inflateUndermine;
*/
},{"../utils/common":4,"./adler32":5,"./crc32":7,"./inffast":9,"./inftrees":11}],11:[function(require,module,exports){
'use strict';
var utils = require('../utils/common');
var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var lbase = [ /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
];
var lext = [ /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
];
var dbase = [ /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0
];
var dext = [ /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64
];
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
var bits = opts.bits;
//here = opts.here; /* table entry for duplication */
var len = 0; /* a code's length in bits */
var sym = 0; /* index of code symbols */
var min = 0, max = 0; /* minimum and maximum code lengths */
var root = 0; /* number of index bits for root table */
var curr = 0; /* number of index bits for current table */
var drop = 0; /* code bits to drop for sub-table */
var left = 0; /* number of prefix codes available */
var used = 0; /* code entries in table used */
var huff = 0; /* Huffman code */
var incr; /* for incrementing code, index */
var fill; /* index for replicating entries */
var low; /* low bits for current root entry */
var mask; /* mask for low root bits */
var next; /* next available space in table */
var base = null; /* base value table to use */
var base_index = 0;
// var shoextra; /* extra bits table to use */
var end; /* use base and extra for symbol > end */
var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
var extra = null;
var extra_index = 0;
var here_bits, here_op, here_val;
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
/* bound code lengths, force root to be within code lengths */
root = bits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] !== 0) { break; }
}
if (root > max) {
root = max;
}
if (max === 0) { /* no symbols to code at all */
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
//table.op[opts.table_index] = 64;
//table.bits[opts.table_index] = 1;
//table.val[opts.table_index++] = 0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
opts.bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++) {
if (count[min] !== 0) { break; }
}
if (root < min) {
root = min;
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
} /* over-subscribed */
}
if (left > 0 && (type === CODES || max !== 1)) {
return -1; /* incomplete set */
}
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
// poor man optimization - use if-else instead of switch,
// to avoid deopts in old v8
if (type === CODES) {
base = extra = work; /* dummy value--not used */
end = 19;
} else if (type === LENS) {
base = lbase;
base_index -= 257;
extra = lext;
extra_index -= 257;
end = 256;
} else { /* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize opts for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = table_index; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = -1; /* trigger new sub-table when len > root */
used = 1 << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
var i=0;
/* process all codes and make table entries */
for (;;) {
i++;
/* create table entry */
here_bits = len - drop;
if (work[sym] < end) {
here_op = 0;
here_val = work[sym];
}
else if (work[sym] > end) {
here_op = extra[extra_index + work[sym]];
here_val = base[base_index + work[sym]];
}
else {
here_op = 32 + 64; /* end of block */
here_val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1 << (len - drop);
fill = 1 << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
} while (fill !== 0);
/* backwards increment the len-bit code huff */
incr = 1 << (len - 1);
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
/* go to next symbol, update count, len */
sym++;
if (--count[len] === 0) {
if (len === max) { break; }
len = lens[lens_index + work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) !== low) {
/* if first time, transition to sub-tables */
if (drop === 0) {
drop = root;
}
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) { break; }
curr++;
left <<= 1;
}
/* check for enough space */
used += 1 << curr;
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
/* point entry in root table to sub-table */
low = huff & mask;
/*table.op[low] = curr;
table.bits[low] = root;
table.val[low] = next - opts.table_index;*/
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff !== 0) {
//table.op[next + huff] = 64; /* invalid code marker */
//table.bits[next + huff] = len - drop;
//table.val[next + huff] = 0;
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
}
/* set return parameters */
//opts.table_index += used;
opts.bits = root;
return 0;
};
},{"../utils/common":4}],12:[function(require,module,exports){
'use strict';
module.exports = {
'2': 'need dictionary', /* Z_NEED_DICT 2 */
'1': 'stream end', /* Z_STREAM_END 1 */
'0': '', /* Z_OK 0 */
'-1': 'file error', /* Z_ERRNO (-1) */
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
'-3': 'data error', /* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};
},{}],13:[function(require,module,exports){
'use strict';
var utils = require('../utils/common');
/* Public constants ==========================================================*/
/* ===========================================================================*/
//var Z_FILTERED = 1;
//var Z_HUFFMAN_ONLY = 2;
//var Z_RLE = 3;
var Z_FIXED = 4;
//var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
var Z_BINARY = 0;
var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/*============================================================================*/
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
// From zutil.h
var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES = 2;
/* The three kinds of block type */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
/* The minimum and maximum match lengths */
// From deflate.h
/* ===========================================================================
* Internal compression state.
*/
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var Buf_size = 16;
/* size of bit buffer in bi_buf */
/* ===========================================================================
* Constants
*/
var MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */
var END_BLOCK = 256;
/* end of block literal code */
var REP_3_6 = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
var REPZ_3_10 = 17;
/* repeat a zero length 3-10 times (3 bits of repeat count) */
var REPZ_11_138 = 18;
/* repeat a zero length 11-138 times (7 bits of repeat count) */
var extra_lbits = /* extra bits for each length code */
[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
var extra_dbits = /* extra bits for each distance code */
[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
var extra_blbits = /* extra bits for each bit length code */
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
var bl_order =
[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
// We pre-fill arrays with 0 to avoid uninitialized gaps
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
var static_ltree = new Array((L_CODES+2) * 2);
zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
var static_dtree = new Array(D_CODES * 2);
zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
var _dist_code = new Array(DIST_CODE_LEN);
zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */
var base_length = new Array(LENGTH_CODES);
zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */
var base_dist = new Array(D_CODES);
zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */
var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
this.static_tree = static_tree; /* static tree or NULL */
this.extra_bits = extra_bits; /* extra bits for each code or NULL */
this.extra_base = extra_base; /* base index for extra_bits */
this.elems = elems; /* max number of elements in the tree */
this.max_length = max_length; /* max bit length for the codes */
// show if `static_tree` has data or dummy - needed for monomorphic objects
this.has_stree = static_tree && static_tree.length;
};
var static_l_desc;
var static_d_desc;
var static_bl_desc;
var TreeDesc = function(dyn_tree, stat_desc) {
this.dyn_tree = dyn_tree; /* the dynamic tree */
this.max_code = 0; /* largest code with non zero frequency */
this.stat_desc = stat_desc; /* the corresponding static tree */
};
function d_code(dist) {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
function put_short (s, w) {
// put_byte(s, (uch)((w) & 0xff));
// put_byte(s, (uch)((ush)(w) >> 8));
s.pending_buf[s.pending++] = (w) & 0xff;
s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
function send_bits(s, value, length) {
if (s.bi_valid > (Buf_size - length)) {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = value >> (Buf_size - s.bi_valid);
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += length;
}
}
function send_code(s, c, tree) {
send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
function bi_reverse(code, len) {
var res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
function bi_flush(s) {
if (s.bi_valid === 16) {
put_short(s, s.bi_buf);
s.bi_buf = 0;
s.bi_valid = 0;
} else if (s.bi_valid >= 8) {
s.pending_buf[s.pending++] = s.bi_buf & 0xff;
s.bi_buf >>= 8;
s.bi_valid -= 8;
}
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
function gen_bitlen(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var max_code = desc.max_code;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var extra = desc.stat_desc.extra_bits;
var base = desc.stat_desc.extra_base;
var max_length = desc.stat_desc.max_length;
var h; /* heap index */
var n, m; /* iterate over the tree elements */
var bits; /* bit length */
var xbits; /* extra bits */
var f; /* frequency */
var overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0;
}
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n*2 + 1]/*.Len*/ = bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) { continue; } /* not a leaf node */
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n-base];
}
f = tree[n * 2]/*.Freq*/;
s.opt_len += f * (bits + xbits);
if (has_stree) {
s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
}
}
if (overflow === 0) { return; }
// Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length-1;
while (s.bl_count[bits] === 0) { bits--; }
s.bl_count[bits]--; /* move one leaf down the tree */
s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
s.bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits !== 0; bits--) {
n = s.bl_count[bits];
while (n !== 0) {
m = s.heap[--h];
if (m > max_code) { continue; }
if (tree[m*2 + 1]/*.Len*/ !== bits) {
// Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
tree[m*2 + 1]/*.Len*/ = bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
function gen_codes(tree, max_code, bl_count)
// ct_data *tree; /* the tree to decorate */
// int max_code; /* largest code with non zero frequency */
// ushf *bl_count; /* number of codes at each bit length */
{
var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
var code = 0; /* running code value */
var bits; /* bit index */
var n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits-1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
var len = tree[n*2 + 1]/*.Len*/;
if (len === 0) { continue; }
/* Now reverse the bits */
tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
function tr_static_init() {
var n; /* iterates over tree elements */
var bits; /* bit counter */
var length; /* length value */
var code; /* code value */
var dist; /* distance index */
var bl_count = new Array(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
// do check in _tr_init()
//if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
/*#ifdef NO_INIT_GLOBAL_POINTERS
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
#endif*/
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES-1; code++) {
base_length[code] = length;
for (n = 0; n < (1<<extra_lbits[code]); n++) {
_length_code[length++] = code;
}
}
//Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length-1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0 ; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1<<extra_dbits[code]); n++) {
_dist_code[dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for ( ; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
_dist_code[256 + dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) {
bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
while (n <= 255) {
static_ltree[n*2 + 1]/*.Len*/ = 9;
n++;
bl_count[9]++;
}
while (n <= 279) {
static_ltree[n*2 + 1]/*.Len*/ = 7;
n++;
bl_count[7]++;
}
while (n <= 287) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes(static_ltree, L_CODES+1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n*2 + 1]/*.Len*/ = 5;
static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
}
// Now data ready and we can init static trees
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
//static_init_done = true;
}
/* ===========================================================================
* Initialize a new block.
*/
function init_block(s) {
var n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
s.opt_len = s.static_len = 0;
s.last_lit = s.matches = 0;
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
function bi_windup(s)
{
if (s.bi_valid > 8) {
put_short(s, s.bi_buf);
} else if (s.bi_valid > 0) {
//put_byte(s, (Byte)s->bi_buf);
s.pending_buf[s.pending++] = s.bi_buf;
}
s.bi_buf = 0;
s.bi_valid = 0;
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
function copy_block(s, buf, len, header)
//DeflateState *s;
//charf *buf; /* the input data */
//unsigned len; /* its length */
//int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
if (header) {
put_short(s, len);
put_short(s, ~len);
}
// while (len--) {
// put_byte(s, *buf++);
// }
utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
s.pending += len;
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
function smaller(tree, n, m, depth) {
var _n2 = n*2;
var _m2 = m*2;
return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
}
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
function pqdownheap(s, tree, k)
// deflate_state *s;
// ct_data *tree; /* the tree to restore */
// int k; /* node to move down */
{
var v = s.heap[k];
var j = k << 1; /* left son of k */
while (j <= s.heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s.heap_len &&
smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s.heap[j], s.depth)) { break; }
/* Exchange v with the smallest son */
s.heap[k] = s.heap[j];
k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s.heap[k] = v;
}
// inlined manually
// var SMALLEST = 1;
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
function compress_block(s, ltree, dtree)
// deflate_state *s;
// const ct_data *ltree; /* literal tree */
// const ct_data *dtree; /* distance tree */
{
var dist; /* distance of matched string */
var lc; /* match length or unmatched char (if dist == 0) */
var lx = 0; /* running index in l_buf */
var code; /* the code to send */
var extra; /* number of extra bits to send */
if (s.last_lit !== 0) {
do {
dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
lc = s.pending_buf[s.l_buf + lx];
lx++;
if (dist === 0) {
send_code(s, lc, ltree); /* send a literal byte */
//Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code+LITERALS+1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra !== 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
//Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra !== 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
//Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
// "pendingBuf overflow");
} while (lx < s.last_lit);
}
send_code(s, END_BLOCK, ltree);
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
function build_tree(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var elems = desc.stat_desc.elems;
var n, m; /* iterate over heap elements */
var max_code = -1; /* largest code with non zero frequency */
var node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n * 2]/*.Freq*/ !== 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n*2 + 1]/*.Len*/ = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node * 2]/*.Freq*/ = 1;
s.depth[node] = 0;
s.opt_len--;
if (has_stree) {
s.static_len -= stree[node*2 + 1]/*.Len*/;
}
/* node is 0 or 1 so it does not have extra bits */
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
//pqremove(s, tree, n); /* n = node of least frequency */
/*** pqremove ***/
n = s.heap[1/*SMALLEST*/];
s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
pqdownheap(s, tree, 1/*SMALLEST*/);
/***/
m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
s.heap[--s.heap_max] = m;
/* Create a new node father of n and m */
tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
/* and insert the new node in the heap */
s.heap[1/*SMALLEST*/] = node++;
pqdownheap(s, tree, 1/*SMALLEST*/);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, desc);
/* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code, s.bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
function scan_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
s.bl_tree[curlen * 2]/*.Freq*/ += count;
} else if (curlen !== 0) {
if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
s.bl_tree[REP_3_6*2]/*.Freq*/++;
} else if (count <= 10) {
s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
} else {
s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
function send_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
} else if (curlen !== 0) {
if (curlen !== prevlen) {
send_code(s, curlen, s.bl_tree);
count--;
}
//Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s.bl_tree);
send_bits(s, count-3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s.bl_tree);
send_bits(s, count-3, 3);
} else {
send_code(s, REPZ_11_138, s.bl_tree);
send_bits(s, count-11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
function build_bl_tree(s) {
var max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, s.bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
break;
}
}
/* Update opt_len to include the bit length tree and counts */
s.opt_len += 3*(max_blindex+1) + 5+5+4;
//Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
function send_all_trees(s, lcodes, dcodes, blcodes)
// deflate_state *s;
// int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
var rank; /* index in bl_order */
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
//Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes-1, 5);
send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
}
//Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "black list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
function detect_data_type(s) {
/* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
var black_mask = 0xf3ffc07f;
var n;
/* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>>= 1) {
if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
return Z_BINARY;
}
}
/* Check for textual ("white-listed") bytes. */
if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
for (n = 32; n < LITERALS; n++) {
if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
}
/* There are no "black-listed" or "white-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
}
var static_init_done = false;
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
function _tr_init(s)
{
if (!static_init_done) {
tr_static_init();
static_init_done = true;
}
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
s.bi_buf = 0;
s.bi_valid = 0;
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Send a stored block
*/
function _tr_stored_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
copy_block(s, buf, stored_len, true); /* with header */
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
*/
function _tr_align(s) {
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
bi_flush(s);
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
function _tr_flush_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block, or NULL if too old */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
var max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s.level > 0) {
/* Check if the file is binary or text */
if (s.strm.data_type === Z_UNKNOWN) {
s.strm.data_type = detect_data_type(s);
}
/* Construct the literal and distance trees */
build_tree(s, s.l_desc);
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
build_tree(s, s.d_desc);
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s.opt_len+3+7) >>> 3;
static_lenb = (s.static_len+3+7) >>> 3;
// Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
// s->last_lit));
if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
} else {
// Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
/* 4: two words for the lengths */
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, last);
} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
compress_block(s, static_ltree, static_dtree);
} else {
send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
}
// Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
}
// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
// s->compressed_len-7*last));
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
function _tr_tally(s, dist, lc)
// deflate_state *s;
// unsigned dist; /* distance of matched string */
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
//var out_length, in_length, dcode;
s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
s.last_lit++;
if (dist === 0) {
/* lc is the unmatched char */
s.dyn_ltree[lc*2]/*.Freq*/++;
} else {
s.matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
//Assert((ush)dist < (ush)MAX_DIST(s) &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef TRUNCATE_BLOCK
// /* Try to guess if it is profitable to stop the current block here */
// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
// /* Compute an upper bound for the compressed length */
// out_length = s.last_lit*8;
// in_length = s.strstart - s.block_start;
//
// for (dcode = 0; dcode < D_CODES; dcode++) {
// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
// }
// out_length >>>= 3;
// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
// // s->last_lit, in_length, out_length,
// // 100L - out_length*100L/in_length));
// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
// return true;
// }
// }
//#endif
return (s.last_lit === s.lit_bufsize-1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
exports._tr_init = _tr_init;
exports._tr_stored_block = _tr_stored_block;
exports._tr_flush_block = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;
},{"../utils/common":4}],14:[function(require,module,exports){
'use strict';
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
module.exports = ZStream;
},{}],15:[function(require,module,exports){
(function (process,Buffer){
var msg = require('pako/lib/zlib/messages');
var zstream = require('pako/lib/zlib/zstream');
var zlib_deflate = require('pako/lib/zlib/deflate.js');
var zlib_inflate = require('pako/lib/zlib/inflate.js');
var constants = require('pako/lib/zlib/constants');
for (var key in constants) {
exports[key] = constants[key];
}
// zlib modes
exports.NONE = 0;
exports.DEFLATE = 1;
exports.INFLATE = 2;
exports.GZIP = 3;
exports.GUNZIP = 4;
exports.DEFLATERAW = 5;
exports.INFLATERAW = 6;
exports.UNZIP = 7;
/**
* Emulate Node's zlib C++ layer for use by the JS layer in index.js
*/
function Zlib(mode) {
if (mode < exports.DEFLATE || mode > exports.UNZIP)
throw new TypeError("Bad argument");
this.mode = mode;
this.init_done = false;
this.write_in_progress = false;
this.pending_close = false;
this.windowBits = 0;
this.level = 0;
this.memLevel = 0;
this.strategy = 0;
this.dictionary = null;
}
Zlib.prototype.init = function(windowBits, level, memLevel, strategy, dictionary) {
this.windowBits = windowBits;
this.level = level;
this.memLevel = memLevel;
this.strategy = strategy;
// dictionary not supported.
if (this.mode === exports.GZIP || this.mode === exports.GUNZIP)
this.windowBits += 16;
if (this.mode === exports.UNZIP)
this.windowBits += 32;
if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW)
this.windowBits = -this.windowBits;
this.strm = new zstream();
switch (this.mode) {
case exports.DEFLATE:
case exports.GZIP:
case exports.DEFLATERAW:
var status = zlib_deflate.deflateInit2(
this.strm,
this.level,
exports.Z_DEFLATED,
this.windowBits,
this.memLevel,
this.strategy
);
break;
case exports.INFLATE:
case exports.GUNZIP:
case exports.INFLATERAW:
case exports.UNZIP:
var status = zlib_inflate.inflateInit2(
this.strm,
this.windowBits
);
break;
default:
throw new Error("Unknown mode " + this.mode);
}
if (status !== exports.Z_OK) {
this._error(status);
return;
}
this.write_in_progress = false;
this.init_done = true;
};
Zlib.prototype.params = function() {
throw new Error("deflateParams Not supported");
};
Zlib.prototype._writeCheck = function() {
if (!this.init_done)
throw new Error("write before init");
if (this.mode === exports.NONE)
throw new Error("already finalized");
if (this.write_in_progress)
throw new Error("write already in progress");
if (this.pending_close)
throw new Error("close is pending");
};
Zlib.prototype.write = function(flush, input, in_off, in_len, out, out_off, out_len) {
this._writeCheck();
this.write_in_progress = true;
var self = this;
process.nextTick(function() {
self.write_in_progress = false;
var res = self._write(flush, input, in_off, in_len, out, out_off, out_len);
self.callback(res[0], res[1]);
if (self.pending_close)
self.close();
});
return this;
};
// set method for Node buffers, used by pako
function bufferSet(data, offset) {
for (var i = 0; i < data.length; i++) {
this[offset + i] = data[i];
}
}
Zlib.prototype.writeSync = function(flush, input, in_off, in_len, out, out_off, out_len) {
this._writeCheck();
return this._write(flush, input, in_off, in_len, out, out_off, out_len);
};
Zlib.prototype._write = function(flush, input, in_off, in_len, out, out_off, out_len) {
this.write_in_progress = true;
if (flush !== exports.Z_NO_FLUSH &&
flush !== exports.Z_PARTIAL_FLUSH &&
flush !== exports.Z_SYNC_FLUSH &&
flush !== exports.Z_FULL_FLUSH &&
flush !== exports.Z_FINISH &&
flush !== exports.Z_BLOCK) {
throw new Error("Invalid flush value");
}
if (input == null) {
input = new Buffer(0);
in_len = 0;
in_off = 0;
}
if (out._set)
out.set = out._set;
else
out.set = bufferSet;
var strm = this.strm;
strm.avail_in = in_len;
strm.input = input;
strm.next_in = in_off;
strm.avail_out = out_len;
strm.output = out;
strm.next_out = out_off;
switch (this.mode) {
case exports.DEFLATE:
case exports.GZIP:
case exports.DEFLATERAW:
var status = zlib_deflate.deflate(strm, flush);
break;
case exports.UNZIP:
case exports.INFLATE:
case exports.GUNZIP:
case exports.INFLATERAW:
var status = zlib_inflate.inflate(strm, flush);
break;
default:
throw new Error("Unknown mode " + this.mode);
}
if (status !== exports.Z_STREAM_END && status !== exports.Z_OK) {
this._error(status);
}
this.write_in_progress = false;
return [strm.avail_in, strm.avail_out];
};
Zlib.prototype.close = function() {
if (this.write_in_progress) {
this.pending_close = true;
return;
}
this.pending_close = false;
if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
zlib_deflate.deflateEnd(this.strm);
} else {
zlib_inflate.inflateEnd(this.strm);
}
this.mode = exports.NONE;
};
Zlib.prototype.reset = function() {
switch (this.mode) {
case exports.DEFLATE:
case exports.DEFLATERAW:
var status = zlib_deflate.deflateReset(this.strm);
break;
case exports.INFLATE:
case exports.INFLATERAW:
var status = zlib_inflate.inflateReset(this.strm);
break;
}
if (status !== exports.Z_OK) {
this._error(status);
}
};
Zlib.prototype._error = function(status) {
this.onerror(msg[status] + ': ' + this.strm.msg, status);
this.write_in_progress = false;
if (this.pending_close)
this.close();
};
exports.Zlib = Zlib;
}).call(this,require('_process'),require("buffer").Buffer)
},{"_process":25,"buffer":17,"pako/lib/zlib/constants":6,"pako/lib/zlib/deflate.js":8,"pako/lib/zlib/inflate.js":10,"pako/lib/zlib/messages":12,"pako/lib/zlib/zstream":14}],16:[function(require,module,exports){
(function (process,Buffer){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var Transform = require('_stream_transform');
var binding = require('./binding');
var util = require('util');
var assert = require('assert').ok;
// zlib doesn't provide these, so kludge them in following the same
// const naming scheme zlib uses.
binding.Z_MIN_WINDOWBITS = 8;
binding.Z_MAX_WINDOWBITS = 15;
binding.Z_DEFAULT_WINDOWBITS = 15;
// fewer than 64 bytes per chunk is stupid.
// technically it could work with as few as 8, but even 64 bytes
// is absurdly low. Usually a MB or more is best.
binding.Z_MIN_CHUNK = 64;
binding.Z_MAX_CHUNK = Infinity;
binding.Z_DEFAULT_CHUNK = (16 * 1024);
binding.Z_MIN_MEMLEVEL = 1;
binding.Z_MAX_MEMLEVEL = 9;
binding.Z_DEFAULT_MEMLEVEL = 8;
binding.Z_MIN_LEVEL = -1;
binding.Z_MAX_LEVEL = 9;
binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
// expose all the zlib constants
Object.keys(binding).forEach(function(k) {
if (k.match(/^Z/)) exports[k] = binding[k];
});
// translation table for return codes.
exports.codes = {
Z_OK: binding.Z_OK,
Z_STREAM_END: binding.Z_STREAM_END,
Z_NEED_DICT: binding.Z_NEED_DICT,
Z_ERRNO: binding.Z_ERRNO,
Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
Z_DATA_ERROR: binding.Z_DATA_ERROR,
Z_MEM_ERROR: binding.Z_MEM_ERROR,
Z_BUF_ERROR: binding.Z_BUF_ERROR,
Z_VERSION_ERROR: binding.Z_VERSION_ERROR
};
Object.keys(exports.codes).forEach(function(k) {
exports.codes[exports.codes[k]] = k;
});
exports.Deflate = Deflate;
exports.Inflate = Inflate;
exports.Gzip = Gzip;
exports.Gunzip = Gunzip;
exports.DeflateRaw = DeflateRaw;
exports.InflateRaw = InflateRaw;
exports.Unzip = Unzip;
exports.createDeflate = function(o) {
return new Deflate(o);
};
exports.createInflate = function(o) {
return new Inflate(o);
};
exports.createDeflateRaw = function(o) {
return new DeflateRaw(o);
};
exports.createInflateRaw = function(o) {
return new InflateRaw(o);
};
exports.createGzip = function(o) {
return new Gzip(o);
};
exports.createGunzip = function(o) {
return new Gunzip(o);
};
exports.createUnzip = function(o) {
return new Unzip(o);
};
// Convenience methods.
// compress/decompress a string or buffer in one step.
exports.deflate = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Deflate(opts), buffer, callback);
};
exports.deflateSync = function(buffer, opts) {
return zlibBufferSync(new Deflate(opts), buffer);
};
exports.gzip = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Gzip(opts), buffer, callback);
};
exports.gzipSync = function(buffer, opts) {
return zlibBufferSync(new Gzip(opts), buffer);
};
exports.deflateRaw = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new DeflateRaw(opts), buffer, callback);
};
exports.deflateRawSync = function(buffer, opts) {
return zlibBufferSync(new DeflateRaw(opts), buffer);
};
exports.unzip = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Unzip(opts), buffer, callback);
};
exports.unzipSync = function(buffer, opts) {
return zlibBufferSync(new Unzip(opts), buffer);
};
exports.inflate = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Inflate(opts), buffer, callback);
};
exports.inflateSync = function(buffer, opts) {
return zlibBufferSync(new Inflate(opts), buffer);
};
exports.gunzip = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Gunzip(opts), buffer, callback);
};
exports.gunzipSync = function(buffer, opts) {
return zlibBufferSync(new Gunzip(opts), buffer);
};
exports.inflateRaw = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new InflateRaw(opts), buffer, callback);
};
exports.inflateRawSync = function(buffer, opts) {
return zlibBufferSync(new InflateRaw(opts), buffer);
};
function zlibBuffer(engine, buffer, callback) {
var buffers = [];
var nread = 0;
engine.on('error', onError);
engine.on('end', onEnd);
engine.end(buffer);
flow();
function flow() {
var chunk;
while (null !== (chunk = engine.read())) {
buffers.push(chunk);
nread += chunk.length;
}
engine.once('readable', flow);
}
function onError(err) {
engine.removeListener('end', onEnd);
engine.removeListener('readable', flow);
callback(err);
}
function onEnd() {
var buf = Buffer.concat(buffers, nread);
buffers = [];
callback(null, buf);
engine.close();
}
}
function zlibBufferSync(engine, buffer) {
if (typeof buffer === 'string')
buffer = new Buffer(buffer);
if (!Buffer.isBuffer(buffer))
throw new TypeError('Not a string or buffer');
var flushFlag = binding.Z_FINISH;
return engine._processChunk(buffer, flushFlag);
}
// generic zlib
// minimal 2-byte header
function Deflate(opts) {
if (!(this instanceof Deflate)) return new Deflate(opts);
Zlib.call(this, opts, binding.DEFLATE);
}
function Inflate(opts) {
if (!(this instanceof Inflate)) return new Inflate(opts);
Zlib.call(this, opts, binding.INFLATE);
}
// gzip - bigger header, same deflate compression
function Gzip(opts) {
if (!(this instanceof Gzip)) return new Gzip(opts);
Zlib.call(this, opts, binding.GZIP);
}
function Gunzip(opts) {
if (!(this instanceof Gunzip)) return new Gunzip(opts);
Zlib.call(this, opts, binding.GUNZIP);
}
// raw - no header
function DeflateRaw(opts) {
if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
Zlib.call(this, opts, binding.DEFLATERAW);
}
function InflateRaw(opts) {
if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
Zlib.call(this, opts, binding.INFLATERAW);
}
// auto-detect header.
function Unzip(opts) {
if (!(this instanceof Unzip)) return new Unzip(opts);
Zlib.call(this, opts, binding.UNZIP);
}
// the Zlib class they all inherit from
// This thing manages the queue of requests, and returns
// true or false if there is anything in the queue when
// you call the .write() method.
function Zlib(opts, mode) {
this._opts = opts = opts || {};
this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
Transform.call(this, opts);
if (opts.flush) {
if (opts.flush !== binding.Z_NO_FLUSH &&
opts.flush !== binding.Z_PARTIAL_FLUSH &&
opts.flush !== binding.Z_SYNC_FLUSH &&
opts.flush !== binding.Z_FULL_FLUSH &&
opts.flush !== binding.Z_FINISH &&
opts.flush !== binding.Z_BLOCK) {
throw new Error('Invalid flush flag: ' + opts.flush);
}
}
this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
if (opts.chunkSize) {
if (opts.chunkSize < exports.Z_MIN_CHUNK ||
opts.chunkSize > exports.Z_MAX_CHUNK) {
throw new Error('Invalid chunk size: ' + opts.chunkSize);
}
}
if (opts.windowBits) {
if (opts.windowBits < exports.Z_MIN_WINDOWBITS ||
opts.windowBits > exports.Z_MAX_WINDOWBITS) {
throw new Error('Invalid windowBits: ' + opts.windowBits);
}
}
if (opts.level) {
if (opts.level < exports.Z_MIN_LEVEL ||
opts.level > exports.Z_MAX_LEVEL) {
throw new Error('Invalid compression level: ' + opts.level);
}
}
if (opts.memLevel) {
if (opts.memLevel < exports.Z_MIN_MEMLEVEL ||
opts.memLevel > exports.Z_MAX_MEMLEVEL) {
throw new Error('Invalid memLevel: ' + opts.memLevel);
}
}
if (opts.strategy) {
if (opts.strategy != exports.Z_FILTERED &&
opts.strategy != exports.Z_HUFFMAN_ONLY &&
opts.strategy != exports.Z_RLE &&
opts.strategy != exports.Z_FIXED &&
opts.strategy != exports.Z_DEFAULT_STRATEGY) {
throw new Error('Invalid strategy: ' + opts.strategy);
}
}
if (opts.dictionary) {
if (!Buffer.isBuffer(opts.dictionary)) {
throw new Error('Invalid dictionary: it should be a Buffer instance');
}
}
this._binding = new binding.Zlib(mode);
var self = this;
this._hadError = false;
this._binding.onerror = function(message, errno) {
// there is no way to cleanly recover.
// continuing only obscures problems.
self._binding = null;
self._hadError = true;
var error = new Error(message);
error.errno = errno;
error.code = exports.codes[errno];
self.emit('error', error);
};
var level = exports.Z_DEFAULT_COMPRESSION;
if (typeof opts.level === 'number') level = opts.level;
var strategy = exports.Z_DEFAULT_STRATEGY;
if (typeof opts.strategy === 'number') strategy = opts.strategy;
this._binding.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS,
level,
opts.memLevel || exports.Z_DEFAULT_MEMLEVEL,
strategy,
opts.dictionary);
this._buffer = new Buffer(this._chunkSize);
this._offset = 0;
this._closed = false;
this._level = level;
this._strategy = strategy;
this.once('end', this.close);
}
util.inherits(Zlib, Transform);
Zlib.prototype.params = function(level, strategy, callback) {
if (level < exports.Z_MIN_LEVEL ||
level > exports.Z_MAX_LEVEL) {
throw new RangeError('Invalid compression level: ' + level);
}
if (strategy != exports.Z_FILTERED &&
strategy != exports.Z_HUFFMAN_ONLY &&
strategy != exports.Z_RLE &&
strategy != exports.Z_FIXED &&
strategy != exports.Z_DEFAULT_STRATEGY) {
throw new TypeError('Invalid strategy: ' + strategy);
}
if (this._level !== level || this._strategy !== strategy) {
var self = this;
this.flush(binding.Z_SYNC_FLUSH, function() {
self._binding.params(level, strategy);
if (!self._hadError) {
self._level = level;
self._strategy = strategy;
if (callback) callback();
}
});
} else {
process.nextTick(callback);
}
};
Zlib.prototype.reset = function() {
return this._binding.reset();
};
// This is the _flush function called by the transform class,
// internally, when the last chunk has been written.
Zlib.prototype._flush = function(callback) {
this._transform(new Buffer(0), '', callback);
};
Zlib.prototype.flush = function(kind, callback) {
var ws = this._writableState;
if (typeof kind === 'function' || (kind === void 0 && !callback)) {
callback = kind;
kind = binding.Z_FULL_FLUSH;
}
if (ws.ended) {
if (callback)
process.nextTick(callback);
} else if (ws.ending) {
if (callback)
this.once('end', callback);
} else if (ws.needDrain) {
var self = this;
this.once('drain', function() {
self.flush(callback);
});
} else {
this._flushFlag = kind;
this.write(new Buffer(0), '', callback);
}
};
Zlib.prototype.close = function(callback) {
if (callback)
process.nextTick(callback);
if (this._closed)
return;
this._closed = true;
this._binding.close();
var self = this;
process.nextTick(function() {
self.emit('close');
});
};
Zlib.prototype._transform = function(chunk, encoding, cb) {
var flushFlag;
var ws = this._writableState;
var ending = ws.ending || ws.ended;
var last = ending && (!chunk || ws.length === chunk.length);
if (!chunk === null && !Buffer.isBuffer(chunk))
return cb(new Error('invalid input'));
// If it's the last chunk, or a final flush, we use the Z_FINISH flush flag.
// If it's explicitly flushing at some other time, then we use
// Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
// goodness.
if (last)
flushFlag = binding.Z_FINISH;
else {
flushFlag = this._flushFlag;
// once we've flushed the last of the queue, stop flushing and
// go back to the normal behavior.
if (chunk.length >= ws.length) {
this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
}
}
var self = this;
this._processChunk(chunk, flushFlag, cb);
};
Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
var availInBefore = chunk && chunk.length;
var availOutBefore = this._chunkSize - this._offset;
var inOff = 0;
var self = this;
var async = typeof cb === 'function';
if (!async) {
var buffers = [];
var nread = 0;
var error;
this.on('error', function(er) {
error = er;
});
do {
var res = this._binding.writeSync(flushFlag,
chunk, // in
inOff, // in_off
availInBefore, // in_len
this._buffer, // out
this._offset, //out_off
availOutBefore); // out_len
} while (!this._hadError && callback(res[0], res[1]));
if (this._hadError) {
throw error;
}
var buf = Buffer.concat(buffers, nread);
this.close();
return buf;
}
var req = this._binding.write(flushFlag,
chunk, // in
inOff, // in_off
availInBefore, // in_len
this._buffer, // out
this._offset, //out_off
availOutBefore); // out_len
req.buffer = chunk;
req.callback = callback;
function callback(availInAfter, availOutAfter) {
if (self._hadError)
return;
var have = availOutBefore - availOutAfter;
assert(have >= 0, 'have should not go down');
if (have > 0) {
var out = self._buffer.slice(self._offset, self._offset + have);
self._offset += have;
// serve some output to the consumer.
if (async) {
self.push(out);
} else {
buffers.push(out);
nread += out.length;
}
}
// exhausted the output buffer, or used all the input create a new one.
if (availOutAfter === 0 || self._offset >= self._chunkSize) {
availOutBefore = self._chunkSize;
self._offset = 0;
self._buffer = new Buffer(self._chunkSize);
}
if (availOutAfter === 0) {
// Not actually done. Need to reprocess.
// Also, update the availInBefore to the availInAfter value,
// so that if we have to hit it a third (fourth, etc.) time,
// it'll have the correct byte counts.
inOff += (availInBefore - availInAfter);
availInBefore = availInAfter;
if (!async)
return true;
var newReq = self._binding.write(flushFlag,
chunk,
inOff,
availInBefore,
self._buffer,
self._offset,
self._chunkSize);
newReq.callback = callback; // this same function
newReq.buffer = chunk;
return;
}
if (!async)
return false;
// finished with the chunk.
cb();
}
};
util.inherits(Deflate, Zlib);
util.inherits(Inflate, Zlib);
util.inherits(Gzip, Zlib);
util.inherits(Gunzip, Zlib);
util.inherits(DeflateRaw, Zlib);
util.inherits(InflateRaw, Zlib);
util.inherits(Unzip, Zlib);
}).call(this,require('_process'),require("buffer").Buffer)
},{"./binding":15,"_process":25,"_stream_transform":35,"assert":2,"buffer":17,"util":40}],17:[function(require,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
var base64 = require('base64-js')
var ieee754 = require('ieee754')
var isArray = require('is-array')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
Buffer.poolSize = 8192 // not used by this implementation
var kMaxLength = 0x3fffffff
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+.
*
* Note:
*
* - Implementation must support adding new properties to `Uint8Array` instances.
* Firefox 4-29 lacked support, fixed in Firefox 30+.
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - 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 will
* get the Object implementation, which is slower but will work correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = (function () {
try {
var buf = new ArrayBuffer(0)
var arr = new Uint8Array(buf)
arr.foo = function () { return 42 }
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
})()
/**
* 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 (subject, encoding) {
var self = this
if (!(self instanceof Buffer)) return new Buffer(subject, encoding)
var type = typeof subject
var length
if (type === 'number') {
length = +subject
} else if (type === 'string') {
length = Buffer.byteLength(subject, encoding)
} else if (type === 'object' && subject !== null) {
// assume object is array-like
if (subject.type === 'Buffer' && isArray(subject.data)) subject = subject.data
length = +subject.length
} else {
throw new TypeError('must start with number, buffer, array or string')
}
if (length > kMaxLength) {
throw new RangeError('Attempt to allocate Buffer larger than maximum size: 0x' +
kMaxLength.toString(16) + ' bytes')
}
if (length < 0) length = 0
else length >>>= 0 // coerce to uint32
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Preferred: Return an augmented `Uint8Array` instance for best performance
self = Buffer._augment(new Uint8Array(length)) // eslint-disable-line consistent-this
} else {
// Fallback: Return THIS instance of Buffer (created by `new`)
self.length = length
self._isBuffer = true
}
var i
if (Buffer.TYPED_ARRAY_SUPPORT && typeof subject.byteLength === 'number') {
// Speed optimization -- use set if we're copying from a typed array
self._set(subject)
} else if (isArrayish(subject)) {
// Treat array-ish objects as a byte array
if (Buffer.isBuffer(subject)) {
for (i = 0; i < length; i++) {
self[i] = subject.readUInt8(i)
}
} else {
for (i = 0; i < length; i++) {
self[i] = ((subject[i] % 256) + 256) % 256
}
}
} else if (type === 'string') {
self.write(subject, 0, encoding)
} else if (type === 'number' && !Buffer.TYPED_ARRAY_SUPPORT) {
for (i = 0; i < length; i++) {
self[i] = 0
}
}
if (length > 0 && length <= Buffer.poolSize) self.parent = rootParent
return self
}
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
for (var i = 0, len = Math.min(x, y); i < len && a[i] === b[i]; 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, totalLength) {
if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
if (list.length === 0) {
return new Buffer(0)
} else if (list.length === 1) {
return list[0]
}
var i
if (totalLength === undefined) {
totalLength = 0
for (i = 0; i < list.length; i++) {
totalLength += list[i].length
}
}
var buf = new Buffer(totalLength)
var pos = 0
for (i = 0; i < list.length; i++) {
var item = list[i]
item.copy(buf, pos)
pos += item.length
}
return buf
}
Buffer.byteLength = function byteLength (str, encoding) {
var ret
str = str + ''
switch (encoding || 'utf8') {
case 'ascii':
case 'binary':
case 'raw':
ret = str.length
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = str.length * 2
break
case 'hex':
ret = str.length >>> 1
break
case 'utf8':
case 'utf-8':
ret = utf8ToBytes(str).length
break
case 'base64':
ret = base64ToBytes(str).length
break
default:
ret = str.length
}
return ret
}
// pre-set for values that may exist in the future
Buffer.prototype.length = undefined
Buffer.prototype.parent = undefined
// toString(encoding, start=0, end=buffer.length)
Buffer.prototype.toString = function toString (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.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 ' + str + '>'
}
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` will be removed in Node 0.13+
Buffer.prototype.get = function get (offset) {
console.log('.get() is deprecated. Access using array indexes instead.')
return this.readUInt8(offset)
}
// `set` will be removed in Node 0.13+
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) {
var charsWritten = blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
return charsWritten
}
function asciiWrite (buf, string, offset, length) {
var charsWritten = blitBuffer(asciiToBytes(string), buf, offset, length)
return charsWritten
}
function binaryWrite (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
var charsWritten = blitBuffer(base64ToBytes(string), buf, offset, length)
return charsWritten
}
function utf16leWrite (buf, string, offset, length) {
var charsWritten = blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
return charsWritten
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Support both (string, offset, length, encoding)
// and the legacy (string, encoding, offset, length)
if (isFinite(offset)) {
if (!isFinite(length)) {
encoding = length
length = undefined
}
} else { // legacy
var swap = encoding
encoding = offset
offset = length
length = swap
}
offset = Number(offset) || 0
if (length < 0 || offset < 0 || offset > this.length) {
throw new RangeError('attempt to write outside buffer bounds')
}
var remaining = this.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
encoding = String(encoding || 'utf8').toLowerCase()
var ret
switch (encoding) {
case 'hex':
ret = hexWrite(this, string, offset, length)
break
case 'utf8':
case 'utf-8':
ret = utf8Write(this, string, offset, length)
break
case 'ascii':
ret = asciiWrite(this, string, offset, length)
break
case 'binary':
ret = binaryWrite(this, string, offset, length)
break
case 'base64':
ret = base64Write(this, string, offset, length)
break
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
ret = utf16leWrite(this, string, offset, length)
break
default:
throw new TypeError('Unknown encoding: ' + encoding)
}
return ret
}
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) {
var res = ''
var tmp = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
if (buf[i] <= 0x7F) {
res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
tmp = ''
} else {
tmp += '%' + buf[i].toString(16)
}
}
return res + decodeUtf8Char(tmp)
}
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) >>> 0 & 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) >>> 0 & 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
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
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
} 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
} 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
} 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) {
checkInt(
this, value, offset, byteLength,
Math.pow(2, 8 * byteLength - 1) - 1,
-Math.pow(2, 8 * byteLength - 1)
)
}
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) {
checkInt(
this, value, offset, byteLength,
Math.pow(2, 8 * byteLength - 1) - 1,
-Math.pow(2, 8 * byteLength - 1)
)
}
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
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
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
} 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
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
} 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, target_start, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (target_start >= target.length) target_start = target.length
if (!target_start) target_start = 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 (target_start < 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 - target_start < end - start) {
end = target.length - target_start + start
}
var len = end - start
if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < len; i++) {
target[i + target_start] = this[i + start]
}
} else {
target._set(this.subarray(start, start + len), target_start)
}
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, will be removed in node 0.13+
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-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 isArrayish (subject) {
return isArray(subject) || Buffer.isBuffer(subject) ||
subject && typeof subject === 'object' &&
typeof subject.length === 'number'
}
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 = []
var i = 0
for (; i < length; i++) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (leadSurrogate) {
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
} else {
// valid surrogate pair
codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
leadSurrogate = null
}
} else {
// 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
} else {
// valid lead
leadSurrogate = codePoint
continue
}
}
} 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 < 0x200000) {
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
}
function decodeUtf8Char (str) {
try {
return decodeURIComponent(str)
} catch (err) {
return String.fromCharCode(0xFFFD) // UTF 8 invalid char
}
}
},{"base64-js":18,"ieee754":19,"is-array":20}],18:[function(require,module,exports){
var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
;(function (exports) {
'use strict';
var Arr = (typeof Uint8Array !== 'undefined')
? Uint8Array
: Array
var PLUS = '+'.charCodeAt(0)
var SLASH = '/'.charCodeAt(0)
var NUMBER = '0'.charCodeAt(0)
var LOWER = 'a'.charCodeAt(0)
var UPPER = 'A'.charCodeAt(0)
var PLUS_URL_SAFE = '-'.charCodeAt(0)
var SLASH_URL_SAFE = '_'.charCodeAt(0)
function decode (elt) {
var code = elt.charCodeAt(0)
if (code === PLUS ||
code === PLUS_URL_SAFE)
return 62 // '+'
if (code === SLASH ||
code === SLASH_URL_SAFE)
return 63 // '/'
if (code < NUMBER)
return -1 //no match
if (code < NUMBER + 10)
return code - NUMBER + 26 + 26
if (code < UPPER + 26)
return code - UPPER
if (code < LOWER + 26)
return code - LOWER + 26
}
function b64ToByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
if (b64.length % 4 > 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))
},{}],19:[function(require,module,exports){
exports.read = function(buffer, offset, isLE, mLen, nBytes) {
var e, m,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
nBits = -7,
i = isLE ? (nBytes - 1) : 0,
d = isLE ? -1 : 1,
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,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
i = isLE ? 0 : (nBytes - 1),
d = isLE ? 1 : -1,
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;
};
},{}],20:[function(require,module,exports){
/**
* isArray
*/
var isArray = Array.isArray;
/**
* toString
*/
var str = Object.prototype.toString;
/**
* Whether or not the given `val`
* is an array.
*
* example:
*
* isArray([]);
* // > true
* isArray(arguments);
* // > false
* isArray('');
* // > false
*
* @param {mixed} val
* @return {bool}
*/
module.exports = isArray || function (val) {
return !! val && '[object Array]' == str.call(val);
};
},{}],21:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (isObject(handler)) {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
var m;
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (isFunction(emitter._events[type]))
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],22:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],23:[function(require,module,exports){
module.exports = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
},{}],24:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
return splitPathRe.exec(filename).slice(1);
};
// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function(p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function(path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function(p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function(path) {
var result = splitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
exports.basename = function(path, ext) {
var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function(path) {
return splitPath(path)[3];
};
function filter (xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
? function (str, start, len) { return str.substr(start, len) }
: function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
}
;
}).call(this,require('_process'))
},{"_process":25}],25:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
function drainQueue() {
if (draining) {
return;
}
draining = true;
var currentQueue;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
var i = -1;
while (++i < len) {
currentQueue[i]();
}
len = queue.length;
}
draining = false;
}
process.nextTick = function (fun) {
queue.push(fun);
if (!draining) {
setTimeout(drainQueue, 0);
}
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],26:[function(require,module,exports){
module.exports = require("./lib/_stream_duplex.js")
},{"./lib/_stream_duplex.js":27}],27:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
module.exports = Duplex;
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
/*</replacement>*/
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
util.inherits(Duplex, Readable);
forEach(objectKeys(Writable.prototype), function(method) {
if (!Duplex.prototype[method])
Duplex.prototype[method] = Writable.prototype[method];
});
function Duplex(options) {
if (!(this instanceof Duplex))
return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false)
this.readable = false;
if (options && options.writable === false)
this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false)
this.allowHalfOpen = false;
this.once('end', onend);
}
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended)
return;
// no more data can be written.
// But allow more writes to happen in this tick.
process.nextTick(this.end.bind(this));
}
function forEach (xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
}).call(this,require('_process'))
},{"./_stream_readable":29,"./_stream_writable":31,"_process":25,"core-util-is":32,"inherits":22}],28:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
module.exports = PassThrough;
var Transform = require('./_stream_transform');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough))
return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function(chunk, encoding, cb) {
cb(null, chunk);
};
},{"./_stream_transform":30,"core-util-is":32,"inherits":22}],29:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
module.exports = Readable;
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
Readable.ReadableState = ReadableState;
var EE = require('events').EventEmitter;
/*<replacement>*/
if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
var Stream = require('stream');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var StringDecoder;
/*<replacement>*/
var debug = require('util');
if (debug && debug.debuglog) {
debug = debug.debuglog('stream');
} else {
debug = function () {};
}
/*</replacement>*/
util.inherits(Readable, Stream);
function ReadableState(options, stream) {
var Duplex = require('./_stream_duplex');
options = options || {};
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var defaultHwm = options.objectMode ? 16 : 16 * 1024;
this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.buffer = [];
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex)
this.objectMode = this.objectMode || !!options.readableObjectMode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// when piping, we only care about 'readable' events that happen
// after read()ing all the bytes and not getting any pushback.
this.ranOut = false;
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder)
StringDecoder = require('string_decoder/').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
var Duplex = require('./_stream_duplex');
if (!(this instanceof Readable))
return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
Stream.call(this);
}
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function(chunk, encoding) {
var state = this._readableState;
if (util.isString(chunk) && !state.objectMode) {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = new Buffer(chunk, encoding);
encoding = '';
}
}
return readableAddChunk(this, state, chunk, encoding, false);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function(chunk) {
var state = this._readableState;
return readableAddChunk(this, state, chunk, '', true);
};
function readableAddChunk(stream, state, chunk, encoding, addToFront) {
var er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (util.isNullOrUndefined(chunk)) {
state.reading = false;
if (!state.ended)
onEofChunk(stream, state);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (state.ended && !addToFront) {
var e = new Error('stream.push() after EOF');
stream.emit('error', e);
} else if (state.endEmitted && addToFront) {
var e = new Error('stream.unshift() after end event');
stream.emit('error', e);
} else {
if (state.decoder && !addToFront && !encoding)
chunk = state.decoder.write(chunk);
if (!addToFront)
state.reading = false;
// if we want the data now, just emit it.
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront)
state.buffer.unshift(chunk);
else
state.buffer.push(chunk);
if (state.needReadable)
emitReadable(stream);
}
maybeReadMore(stream, state);
}
} else if (!addToFront) {
state.reading = false;
}
return needMoreData(state);
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended &&
(state.needReadable ||
state.length < state.highWaterMark ||
state.length === 0);
}
// backwards compatibility.
Readable.prototype.setEncoding = function(enc) {
if (!StringDecoder)
StringDecoder = require('string_decoder/').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 128MB
var MAX_HWM = 0x800000;
function roundUpToNextPowerOf2(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2
n--;
for (var p = 1; p < 32; p <<= 1) n |= n >> p;
n++;
}
return n;
}
function howMuchToRead(n, state) {
if (state.length === 0 && state.ended)
return 0;
if (state.objectMode)
return n === 0 ? 0 : 1;
if (isNaN(n) || util.isNull(n)) {
// only flow one buffer at a time
if (state.flowing && state.buffer.length)
return state.buffer[0].length;
else
return state.length;
}
if (n <= 0)
return 0;
// If we're asking for more than the target buffer level,
// then raise the water mark. Bump up to the next highest
// power of 2, to prevent increasing it excessively in tiny
// amounts.
if (n > state.highWaterMark)
state.highWaterMark = roundUpToNextPowerOf2(n);
// don't have that much. return null, unless we've ended.
if (n > state.length) {
if (!state.ended) {
state.needReadable = true;
return 0;
} else
return state.length;
}
return n;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function(n) {
debug('read', n);
var state = this._readableState;
var nOrig = n;
if (!util.isNumber(n) || n > 0)
state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 &&
state.needReadable &&
(state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended)
endReadable(this);
else
emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0)
endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
}
if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0)
state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
}
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (doRead && !state.reading)
n = howMuchToRead(nOrig, state);
var ret;
if (n > 0)
ret = fromList(n, state);
else
ret = null;
if (util.isNull(ret)) {
state.needReadable = true;
n = 0;
}
state.length -= n;
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (state.length === 0 && !state.ended)
state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended && state.length === 0)
endReadable(this);
if (!util.isNull(ret))
this.emit('data', ret);
return ret;
};
function chunkInvalid(state, chunk) {
var er = null;
if (!util.isBuffer(chunk) &&
!util.isString(chunk) &&
!util.isNullOrUndefined(chunk) &&
!state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
function onEofChunk(stream, state) {
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync)
process.nextTick(function() {
emitReadable_(stream);
});
else
emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
process.nextTick(function() {
maybeReadMore_(stream, state);
});
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended &&
state.length < state.highWaterMark) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;
else
len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function(n) {
this.emit('error', new Error('not implemented'));
};
Readable.prototype.pipe = function(dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
dest !== process.stdout &&
dest !== process.stderr;
var endFn = doEnd ? onend : cleanup;
if (state.endEmitted)
process.nextTick(endFn);
else
src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable) {
debug('onunpipe');
if (readable === src) {
cleanup();
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', cleanup);
src.removeListener('data', ondata);
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain &&
(!dest._writableState || dest._writableState.needDrain))
ondrain();
}
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
var ret = dest.write(chunk);
if (false === ret) {
debug('false write response, pause',
src._readableState.awaitDrain);
src._readableState.awaitDrain++;
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EE.listenerCount(dest, 'error') === 0)
dest.emit('error', er);
}
// This is a brutally ugly hack to make sure that our error handler
// is attached before any userland ones. NEVER DO THIS.
if (!dest._events || !dest._events.error)
dest.on('error', onerror);
else if (isArray(dest._events.error))
dest._events.error.unshift(onerror);
else
dest._events.error = [onerror, dest._events.error];
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function() {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain)
state.awaitDrain--;
if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function(dest) {
var state = this._readableState;
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0)
return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes)
return this;
if (!dest)
dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest)
dest.emit('unpipe', this);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var i = 0; i < len; i++)
dests[i].emit('unpipe', this);
return this;
}
// try to find the right one.
var i = indexOf(state.pipes, dest);
if (i === -1)
return this;
state.pipes.splice(i, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1)
state.pipes = state.pipes[0];
dest.emit('unpipe', this);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function(ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
// If listening to data, and it has not explicitly been paused,
// then call resume to start the flow of data on the next tick.
if (ev === 'data' && false !== this._readableState.flowing) {
this.resume();
}
if (ev === 'readable' && this.readable) {
var state = this._readableState;
if (!state.readableListening) {
state.readableListening = true;
state.emittedReadable = false;
state.needReadable = true;
if (!state.reading) {
var self = this;
process.nextTick(function() {
debug('readable nexttick read 0');
self.read(0);
});
} else if (state.length) {
emitReadable(this, state);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function() {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
if (!state.reading) {
debug('resume read 0');
this.read(0);
}
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
process.nextTick(function() {
resume_(stream, state);
});
}
}
function resume_(stream, state) {
state.resumeScheduled = false;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading)
stream.read(0);
}
Readable.prototype.pause = function() {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
if (state.flowing) {
do {
var chunk = stream.read();
} while (null !== chunk && state.flowing);
}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function(stream) {
var state = this._readableState;
var paused = false;
var self = this;
stream.on('end', function() {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length)
self.push(chunk);
}
self.push(null);
});
stream.on('data', function(chunk) {
debug('wrapped data');
if (state.decoder)
chunk = state.decoder.write(chunk);
if (!chunk || !state.objectMode && !chunk.length)
return;
var ret = self.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
this[i] = function(method) { return function() {
return stream[method].apply(stream, arguments);
}}(i);
}
}
// proxy certain important events.
var events = ['error', 'close', 'destroy', 'pause', 'resume'];
forEach(events, function(ev) {
stream.on(ev, self.emit.bind(self, ev));
});
// when we try to consume some more bytes, simply unpause the
// underlying stream.
self._read = function(n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return self;
};
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
function fromList(n, state) {
var list = state.buffer;
var length = state.length;
var stringMode = !!state.decoder;
var objectMode = !!state.objectMode;
var ret;
// nothing in the list, definitely empty.
if (list.length === 0)
return null;
if (length === 0)
ret = null;
else if (objectMode)
ret = list.shift();
else if (!n || n >= length) {
// read it all, truncate the array.
if (stringMode)
ret = list.join('');
else
ret = Buffer.concat(list, length);
list.length = 0;
} else {
// read just some of it.
if (n < list[0].length) {
// just take a part of the first list item.
// slice is the same for buffers and strings.
var buf = list[0];
ret = buf.slice(0, n);
list[0] = buf.slice(n);
} else if (n === list[0].length) {
// first list is a perfect match
ret = list.shift();
} else {
// complex case.
// we have enough to cover it, but it spans past the first buffer.
if (stringMode)
ret = '';
else
ret = new Buffer(n);
var c = 0;
for (var i = 0, l = list.length; i < l && c < n; i++) {
var buf = list[0];
var cpy = Math.min(n - c, buf.length);
if (stringMode)
ret += buf.slice(0, cpy);
else
buf.copy(ret, c, 0, cpy);
if (cpy < buf.length)
list[0] = buf.slice(cpy);
else
list.shift();
c += cpy;
}
}
}
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0)
throw new Error('endReadable called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
process.nextTick(function() {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
});
}
}
function forEach (xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
function indexOf (xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
}).call(this,require('_process'))
},{"./_stream_duplex":27,"_process":25,"buffer":17,"core-util-is":32,"events":21,"inherits":22,"isarray":23,"stream":37,"string_decoder/":38,"util":3}],30:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
module.exports = Transform;
var Duplex = require('./_stream_duplex');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(Transform, Duplex);
function TransformState(options, stream) {
this.afterTransform = function(er, data) {
return afterTransform(stream, er, data);
};
this.needTransform = false;
this.transforming = false;
this.writecb = null;
this.writechunk = null;
}
function afterTransform(stream, er, data) {
var ts = stream._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb)
return stream.emit('error', new Error('no writecb in Transform class'));
ts.writechunk = null;
ts.writecb = null;
if (!util.isNullOrUndefined(data))
stream.push(data);
if (cb)
cb(er);
var rs = stream._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
stream._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform))
return new Transform(options);
Duplex.call(this, options);
this._transformState = new TransformState(options, this);
// when the writable side finishes, then flush out anything remaining.
var stream = this;
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
this.once('prefinish', function() {
if (util.isFunction(this._flush))
this._flush(function(er) {
done(stream, er);
});
else
done(stream);
});
}
Transform.prototype.push = function(chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function(chunk, encoding, cb) {
throw new Error('not implemented');
};
Transform.prototype._write = function(chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform ||
rs.needReadable ||
rs.length < rs.highWaterMark)
this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function(n) {
var ts = this._transformState;
if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
function done(stream, er) {
if (er)
return stream.emit('error', er);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
var ws = stream._writableState;
var ts = stream._transformState;
if (ws.length)
throw new Error('calling transform done when ws.length != 0');
if (ts.transforming)
throw new Error('calling transform done when still transforming');
return stream.push(null);
}
},{"./_stream_duplex":27,"core-util-is":32,"inherits":22}],31:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, cb), and it'll handle all
// the drain event emission and buffering.
module.exports = Writable;
/*<replacement>*/
var Buffer = require('buffer').Buffer;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Stream = require('stream');
util.inherits(Writable, Stream);
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
}
function WritableState(options, stream) {
var Duplex = require('./_stream_duplex');
options = options || {};
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var defaultHwm = options.objectMode ? 16 : 16 * 1024;
this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex)
this.objectMode = this.objectMode || !!options.writableObjectMode;
// cast to ints.
this.highWaterMark = ~~this.highWaterMark;
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function(er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.buffer = [];
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
}
function Writable(options) {
var Duplex = require('./_stream_duplex');
// Writable ctor is applied to Duplexes, though they're not
// instanceof Writable, they're instanceof Readable.
if (!(this instanceof Writable) && !(this instanceof Duplex))
return new Writable(options);
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function() {
this.emit('error', new Error('Cannot pipe. Not readable.'));
};
function writeAfterEnd(stream, state, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
}
// If we get something that is not a buffer, string, null, or undefined,
// and we're not in objectMode, then that's an error.
// Otherwise stream chunks are all considered to be of length=1, and the
// watermarks determine how many objects to keep in the buffer, rather than
// how many bytes or characters.
function validChunk(stream, state, chunk, cb) {
var valid = true;
if (!util.isBuffer(chunk) &&
!util.isString(chunk) &&
!util.isNullOrUndefined(chunk) &&
!state.objectMode) {
var er = new TypeError('Invalid non-string/buffer chunk');
stream.emit('error', er);
process.nextTick(function() {
cb(er);
});
valid = false;
}
return valid;
}
Writable.prototype.write = function(chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
if (util.isFunction(encoding)) {
cb = encoding;
encoding = null;
}
if (util.isBuffer(chunk))
encoding = 'buffer';
else if (!encoding)
encoding = state.defaultEncoding;
if (!util.isFunction(cb))
cb = function() {};
if (state.ended)
writeAfterEnd(this, state, cb);
else if (validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function() {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function() {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing &&
!state.corked &&
!state.finished &&
!state.bufferProcessing &&
state.buffer.length)
clearBuffer(this, state);
}
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode &&
state.decodeStrings !== false &&
util.isString(chunk)) {
chunk = new Buffer(chunk, encoding);
}
return chunk;
}
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
if (util.isBuffer(chunk))
encoding = 'buffer';
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret)
state.needDrain = true;
if (state.writing || state.corked)
state.buffer.push(new WriteReq(chunk, encoding, cb));
else
doWrite(stream, state, false, len, chunk, encoding, cb);
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev)
stream._writev(chunk, state.onwrite);
else
stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
if (sync)
process.nextTick(function() {
state.pendingcb--;
cb(er);
});
else {
state.pendingcb--;
cb(er);
}
stream._writableState.errorEmitted = true;
stream.emit('error', er);
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er)
onwriteError(stream, state, sync, er, cb);
else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(stream, state);
if (!finished &&
!state.corked &&
!state.bufferProcessing &&
state.buffer.length) {
clearBuffer(stream, state);
}
if (sync) {
process.nextTick(function() {
afterWrite(stream, state, finished, cb);
});
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished)
onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
if (stream._writev && state.buffer.length > 1) {
// Fast case, write everything using _writev()
var cbs = [];
for (var c = 0; c < state.buffer.length; c++)
cbs.push(state.buffer[c].callback);
// count the one we are adding, as well.
// TODO(isaacs) clean this up
state.pendingcb++;
doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
for (var i = 0; i < cbs.length; i++) {
state.pendingcb--;
cbs[i](err);
}
});
// Clear buffer
state.buffer = [];
} else {
// Slow case, write chunks one-by-one
for (var c = 0; c < state.buffer.length; c++) {
var entry = state.buffer[c];
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
c++;
break;
}
}
if (c < state.buffer.length)
state.buffer = state.buffer.slice(c);
else
state.buffer.length = 0;
}
state.bufferProcessing = false;
}
Writable.prototype._write = function(chunk, encoding, cb) {
cb(new Error('not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function(chunk, encoding, cb) {
var state = this._writableState;
if (util.isFunction(chunk)) {
cb = chunk;
chunk = null;
encoding = null;
} else if (util.isFunction(encoding)) {
cb = encoding;
encoding = null;
}
if (!util.isNullOrUndefined(chunk))
this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished)
endWritable(this, state, cb);
};
function needFinish(stream, state) {
return (state.ending &&
state.length === 0 &&
!state.finished &&
!state.writing);
}
function prefinish(stream, state) {
if (!state.prefinished) {
state.prefinished = true;
stream.emit('prefinish');
}
}
function finishMaybe(stream, state) {
var need = needFinish(stream, state);
if (need) {
if (state.pendingcb === 0) {
prefinish(stream, state);
state.finished = true;
stream.emit('finish');
} else
prefinish(stream, state);
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished)
process.nextTick(cb);
else
stream.once('finish', cb);
}
state.ended = true;
}
}).call(this,require('_process'))
},{"./_stream_duplex":27,"_process":25,"buffer":17,"core-util-is":32,"inherits":22,"stream":37}],32:[function(require,module,exports){
(function (Buffer){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
function isBuffer(arg) {
return Buffer.isBuffer(arg);
}
exports.isBuffer = isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this,require("buffer").Buffer)
},{"buffer":17}],33:[function(require,module,exports){
module.exports = require("./lib/_stream_passthrough.js")
},{"./lib/_stream_passthrough.js":28}],34:[function(require,module,exports){
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = require('stream');
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
},{"./lib/_stream_duplex.js":27,"./lib/_stream_passthrough.js":28,"./lib/_stream_readable.js":29,"./lib/_stream_transform.js":30,"./lib/_stream_writable.js":31,"stream":37}],35:[function(require,module,exports){
module.exports = require("./lib/_stream_transform.js")
},{"./lib/_stream_transform.js":30}],36:[function(require,module,exports){
module.exports = require("./lib/_stream_writable.js")
},{"./lib/_stream_writable.js":31}],37:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
module.exports = Stream;
var EE = require('events').EventEmitter;
var inherits = require('inherits');
inherits(Stream, EE);
Stream.Readable = require('readable-stream/readable.js');
Stream.Writable = require('readable-stream/writable.js');
Stream.Duplex = require('readable-stream/duplex.js');
Stream.Transform = require('readable-stream/transform.js');
Stream.PassThrough = require('readable-stream/passthrough.js');
// Backwards-compat with node 0.4.x
Stream.Stream = Stream;
// old-style streams. Note that the pipe method (the only relevant
// part of this class) is overridden in the Readable class.
function Stream() {
EE.call(this);
}
Stream.prototype.pipe = function(dest, options) {
var source = this;
function ondata(chunk) {
if (dest.writable) {
if (false === dest.write(chunk) && source.pause) {
source.pause();
}
}
}
source.on('data', ondata);
function ondrain() {
if (source.readable && source.resume) {
source.resume();
}
}
dest.on('drain', ondrain);
// If the 'end' option is not supplied, dest.end() will be called when
// source gets the 'end' or 'close' events. Only dest.end() once.
if (!dest._isStdio && (!options || options.end !== false)) {
source.on('end', onend);
source.on('close', onclose);
}
var didOnEnd = false;
function onend() {
if (didOnEnd) return;
didOnEnd = true;
dest.end();
}
function onclose() {
if (didOnEnd) return;
didOnEnd = true;
if (typeof dest.destroy === 'function') dest.destroy();
}
// don't leave dangling pipes when there are errors.
function onerror(er) {
cleanup();
if (EE.listenerCount(this, 'error') === 0) {
throw er; // Unhandled stream error in pipe.
}
}
source.on('error', onerror);
dest.on('error', onerror);
// remove all the event listeners that were added.
function cleanup() {
source.removeListener('data', ondata);
dest.removeListener('drain', ondrain);
source.removeListener('end', onend);
source.removeListener('close', onclose);
source.removeListener('error', onerror);
dest.removeListener('error', onerror);
source.removeListener('end', cleanup);
source.removeListener('close', cleanup);
dest.removeListener('close', cleanup);
}
source.on('end', cleanup);
source.on('close', cleanup);
dest.on('close', cleanup);
dest.emit('pipe', source);
// Allow for unix-like usage: A.pipe(B).pipe(C)
return dest;
};
},{"events":21,"inherits":22,"readable-stream/duplex.js":26,"readable-stream/passthrough.js":33,"readable-stream/readable.js":34,"readable-stream/transform.js":35,"readable-stream/writable.js":36}],38:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var Buffer = require('buffer').Buffer;
var isBufferEncoding = Buffer.isEncoding
|| function(encoding) {
switch (encoding && encoding.toLowerCase()) {
case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
default: return false;
}
}
function assertEncoding(encoding) {
if (encoding && !isBufferEncoding(encoding)) {
throw new Error('Unknown encoding: ' + encoding);
}
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters. CESU-8 is handled as part of the UTF-8 encoding.
//
// @TODO Handling all encodings inside a single object makes it very difficult
// to reason about this code, so it should be split up in the future.
// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
// points as used by CESU-8.
var StringDecoder = exports.StringDecoder = function(encoding) {
this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
assertEncoding(encoding);
switch (this.encoding) {
case 'utf8':
// CESU-8 represents each of Surrogate Pair by 3-bytes
this.surrogateSize = 3;
break;
case 'ucs2':
case 'utf16le':
// UTF-16 represents each of Surrogate Pair by 2-bytes
this.surrogateSize = 2;
this.detectIncompleteChar = utf16DetectIncompleteChar;
break;
case 'base64':
// Base-64 stores 3 bytes in 4 chars, and pads the remainder.
this.surrogateSize = 3;
this.detectIncompleteChar = base64DetectIncompleteChar;
break;
default:
this.write = passThroughWrite;
return;
}
// Enough space to store all bytes of a single character. UTF-8 needs 4
// bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
this.charBuffer = new Buffer(6);
// Number of bytes received for the current incomplete multi-byte character.
this.charReceived = 0;
// Number of bytes expected for the current incomplete multi-byte character.
this.charLength = 0;
};
// write decodes the given buffer and returns it as JS string that is
// guaranteed to not contain any partial multi-byte characters. Any partial
// character found at the end of the buffer is buffered up, and will be
// returned when calling write again with the remaining bytes.
//
// Note: Converting a Buffer containing an orphan surrogate to a String
// currently works, but converting a String to a Buffer (via `new Buffer`, or
// Buffer#write) will replace incomplete surrogates with the unicode
// replacement character. See https://codereview.chromium.org/121173009/ .
StringDecoder.prototype.write = function(buffer) {
var charStr = '';
// if our last write ended with an incomplete multibyte character
while (this.charLength) {
// determine how many remaining bytes this buffer has to offer for this char
var available = (buffer.length >= this.charLength - this.charReceived) ?
this.charLength - this.charReceived :
buffer.length;
// add the new bytes to the char buffer
buffer.copy(this.charBuffer, this.charReceived, 0, available);
this.charReceived += available;
if (this.charReceived < this.charLength) {
// still not enough chars in this buffer? wait for more ...
return '';
}
// remove bytes belonging to the current character from the buffer
buffer = buffer.slice(available, buffer.length);
// get the character that was split
charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
var charCode = charStr.charCodeAt(charStr.length - 1);
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
this.charLength += this.surrogateSize;
charStr = '';
continue;
}
this.charReceived = this.charLength = 0;
// if there are no more bytes in this buffer, just emit our char
if (buffer.length === 0) {
return charStr;
}
break;
}
// determine and set charLength / charReceived
this.detectIncompleteChar(buffer);
var end = buffer.length;
if (this.charLength) {
// buffer the incomplete character bytes we got
buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
end -= this.charReceived;
}
charStr += buffer.toString(this.encoding, 0, end);
var end = charStr.length - 1;
var charCode = charStr.charCodeAt(end);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
var size = this.surrogateSize;
this.charLength += size;
this.charReceived += size;
this.charBuffer.copy(this.charBuffer, size, 0, size);
buffer.copy(this.charBuffer, 0, 0, size);
return charStr.substring(0, end);
}
// or just emit the charStr
return charStr;
};
// detectIncompleteChar determines if there is an incomplete UTF-8 character at
// the end of the given buffer. If so, it sets this.charLength to the byte
// length that character, and sets this.charReceived to the number of bytes
// that are available for this character.
StringDecoder.prototype.detectIncompleteChar = function(buffer) {
// determine how many bytes we have to check at the end of this buffer
var i = (buffer.length >= 3) ? 3 : buffer.length;
// Figure out if one of the last i bytes of our buffer announces an
// incomplete char.
for (; i > 0; i--) {
var c = buffer[buffer.length - i];
// See http://en.wikipedia.org/wiki/UTF-8#Description
// 110XXXXX
if (i == 1 && c >> 5 == 0x06) {
this.charLength = 2;
break;
}
// 1110XXXX
if (i <= 2 && c >> 4 == 0x0E) {
this.charLength = 3;
break;
}
// 11110XXX
if (i <= 3 && c >> 3 == 0x1E) {
this.charLength = 4;
break;
}
}
this.charReceived = i;
};
StringDecoder.prototype.end = function(buffer) {
var res = '';
if (buffer && buffer.length)
res = this.write(buffer);
if (this.charReceived) {
var cr = this.charReceived;
var buf = this.charBuffer;
var enc = this.encoding;
res += buf.slice(0, cr).toString(enc);
}
return res;
};
function passThroughWrite(buffer) {
return buffer.toString(this.encoding);
}
function utf16DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 2;
this.charLength = this.charReceived ? 2 : 0;
}
function base64DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 3;
this.charLength = this.charReceived ? 3 : 0;
}
},{"buffer":17}],39:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],40:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":39,"_process":25,"inherits":22}],41:[function(require,module,exports){
var indexOf = require('indexof');
var Object_keys = function (obj) {
if (Object.keys) return Object.keys(obj)
else {
var res = [];
for (var key in obj) res.push(key)
return res;
}
};
var forEach = function (xs, fn) {
if (xs.forEach) return xs.forEach(fn)
else for (var i = 0; i < xs.length; i++) {
fn(xs[i], i, xs);
}
};
var defineProp = (function() {
try {
Object.defineProperty({}, '_', {});
return function(obj, name, value) {
Object.defineProperty(obj, name, {
writable: true,
enumerable: false,
configurable: true,
value: value
})
};
} catch(e) {
return function(obj, name, value) {
obj[name] = value;
};
}
}());
var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function',
'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError',
'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError',
'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape',
'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape'];
function Context() {}
Context.prototype = {};
var Script = exports.Script = function NodeScript (code) {
if (!(this instanceof Script)) return new Script(code);
this.code = code;
};
Script.prototype.runInContext = function (context) {
if (!(context instanceof Context)) {
throw new TypeError("needs a 'context' argument.");
}
var iframe = document.createElement('iframe');
if (!iframe.style) iframe.style = {};
iframe.style.display = 'none';
document.body.appendChild(iframe);
var win = iframe.contentWindow;
var wEval = win.eval, wExecScript = win.execScript;
if (!wEval && wExecScript) {
// win.eval() magically appears when this is called in IE:
wExecScript.call(win, 'null');
wEval = win.eval;
}
forEach(Object_keys(context), function (key) {
win[key] = context[key];
});
forEach(globals, function (key) {
if (context[key]) {
win[key] = context[key];
}
});
var winKeys = Object_keys(win);
var res = wEval.call(win, this.code);
forEach(Object_keys(win), function (key) {
// Avoid copying circular objects like `top` and `window` by only
// updating existing context properties or new properties in the `win`
// that was only introduced after the eval.
if (key in context || indexOf(winKeys, key) === -1) {
context[key] = win[key];
}
});
forEach(globals, function (key) {
if (!(key in context)) {
defineProp(context, key, win[key]);
}
});
document.body.removeChild(iframe);
return res;
};
Script.prototype.runInThisContext = function () {
return eval(this.code); // maybe...
};
Script.prototype.runInNewContext = function (context) {
var ctx = Script.createContext(context);
var res = this.runInContext(ctx);
forEach(Object_keys(ctx), function (key) {
context[key] = ctx[key];
});
return res;
};
forEach(Object_keys(Script.prototype), function (name) {
exports[name] = Script[name] = function (code) {
var s = Script(code);
return s[name].apply(s, [].slice.call(arguments, 1));
};
});
exports.createScript = function (code) {
return exports.Script(code);
};
exports.createContext = Script.createContext = function (context) {
var copy = new Context();
if(typeof context === 'object') {
forEach(Object_keys(context), function (key) {
copy[key] = context[key];
});
}
return copy;
};
},{"indexof":42}],42:[function(require,module,exports){
var indexOf = [].indexOf;
module.exports = function(arr, obj){
if (indexOf) return arr.indexOf(obj);
for (var i = 0; i < arr.length; ++i) {
if (arr[i] === obj) return i;
}
return -1;
};
},{}],43:[function(require,module,exports){
(function (global){
var createEngine, main;
global.__BROWSERIFY_META_DATA__GIT_VERSION = "a8c6995a142f9a61731b4df4fd46b15c278c9b7a";
global.__BROWSERIFY_META_DATA__CREATED_AT = "Tue Apr 14 2015 13:06:48 GMT-0600 (Canada Central Standard Time)";
require('voxel-artpacks');
require('voxel-wireframe');
require('voxel-chunkborder');
require('voxel-outline');
require('voxel-carry');
require('voxel-bucket');
require('voxel-fluid');
require('voxel-skyhook');
require('voxel-recipes');
require('voxel-quarry');
require('voxel-measure');
require('voxel-webview');
require('voxel-vr');
require('voxel-workbench');
require('voxel-furnace');
require('voxel-chest');
require('voxel-inventory-hotbar');
require('voxel-inventory-crafting');
require('voxel-voila');
require('voxel-health');
require('voxel-health-bar');
require('voxel-food');
require('voxel-sfx');
require('voxel-flight');
require('voxel-gamemode');
require('voxel-sprint');
require('voxel-decals');
require('voxel-mine');
require('voxel-harvest');
require('voxel-use');
require('voxel-reach');
require('voxel-pickaxe');
require('voxel-hammer');
require('voxel-wool');
require('voxel-pumpkin');
require('voxel-blockdata');
require('voxel-glass');
require('voxel-land');
require('voxel-decorative');
require('voxel-inventory-creative');
require('voxel-console');
require('voxel-commands');
require('voxel-drop');
require('voxel-zen');
require('camera-debug');
require('voxel-plugins-ui');
require('voxel-fullscreen');
require('voxel-keys');
require('kb-bindings-ui');
require('voxel-background-music');
createEngine = require('voxel-engine-stackgl');
main = function() {
console.log('voxelmetaverse starting: ', global.__BROWSERIFY_META_DATA__GIT_VERSION, global.__BROWSERIFY_META_DATA__CREATED_AT);
return createEngine({
require: require,
exposeGlobal: true,
pluginOpts: {
'voxel-engine-stackgl': {
appendDocument: true,
exposeGlobal: true,
lightsDisabled: true,
arrayTypeSize: 2,
useAtlas: true,
generateChunks: false,
chunkDistance: 2,
worldOrigin: [0, 0, 0],
controls: {
discreteFire: false,
fireRate: 100,
jumpTimer: 25
},
keybindings: {
'W': 'forward',
'A': 'left',
'S': 'backward',
'D': 'right',
'<up>': 'forward',
'<left>': 'left',
'<down>': 'backward',
'<right>': 'right',
'<mouse 1>': 'fire',
'<mouse 3>': 'firealt',
'<space>': 'jump',
'<shift>': 'crouch',
'<control>': 'alt',
'<tab>': 'sprint',
'F5': 'pov',
'O': 'home',
'E': 'inventory',
'T': 'console',
'/': 'console2',
'.': 'console3',
'P': 'packs',
'F1': 'zen'
}
},
'voxel-registry': {},
'voxel-stitch': {
artpacks: ['ProgrammerArt-ResourcePack.zip']
},
'voxel-shader': {
cameraFOV: 90
},
'voxel-mesher': {},
'game-shell-fps-camera': {
position: [0, -100, 0]
},
'voxel-artpacks': {},
'voxel-wireframe': {},
'voxel-chunkborder': {},
'voxel-outline': {},
'voxel-recipes': {},
'voxel-quarry': {},
'voxel-measure': {},
'voxel-webview': {},
'voxel-vr': {
onDemand: true
},
'voxel-carry': {
inventoryWidth: 10,
inventoryRows: 5
},
'voxel-bucket': {
fluids: ['water', 'lava']
},
'voxel-fluid': {},
'voxel-skyhook': {},
'voxel-blockdata': {},
'voxel-chest': {},
'voxel-workbench': {},
'voxel-furnace': {},
'voxel-pickaxe': {},
'voxel-hammer': {},
'voxel-wool': {},
'voxel-pumpkin': {},
'voxel-glass': {},
'voxel-land': {
populateTrees: true
},
'voxel-decorative': {},
'voxel-inventory-creative': {},
'voxel-console': {},
'voxel-commands': {},
'voxel-drop': {},
'voxel-zen': {},
'voxel-health': {},
'voxel-health-bar': {},
'voxel-food': {},
'voxel-sfx': {},
'voxel-flight': {
flySpeed: 0.8,
onDemand: true
},
'voxel-gamemode': {},
'voxel-sprint': {},
'voxel-inventory-hotbar': {
inventorySize: 10,
wheelEnable: true
},
'voxel-inventory-crafting': {},
'voxel-reach': {
reachDistance: 8
},
'voxel-decals': {},
'voxel-mine': {
instaMine: false,
progressTexturesPrefix: 'destroy_stage_',
progressTexturesCount: 9
},
'voxel-use': {},
'voxel-harvest': {},
'voxel-voila': {},
'voxel-fullscreen': {},
'voxel-keys': {},
'camera-debug': {},
'voxel-plugins-ui': {},
'kb-bindings-ui': {},
'voxel-background-music': {
canPlay: false
}
}
});
};
main();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"camera-debug":44,"kb-bindings-ui":51,"voxel-artpacks":56,"voxel-background-music":60,"voxel-blockdata":61,"voxel-bucket":62,"voxel-carry":69,"voxel-chest":76,"voxel-chunkborder":95,"voxel-commands":129,"voxel-console":136,"voxel-decals":144,"voxel-decorative":195,"voxel-drop":197,"voxel-engine-stackgl":220,"voxel-flight":470,"voxel-fluid":471,"voxel-food":473,"voxel-fullscreen":474,"voxel-furnace":475,"voxel-gamemode":494,"voxel-glass":495,"voxel-hammer":502,"voxel-harvest":503,"voxel-health":510,"voxel-health-bar":509,"voxel-inventory-crafting":512,"voxel-inventory-creative":531,"voxel-inventory-hotbar":556,"voxel-keys":566,"voxel-land":570,"voxel-measure":585,"voxel-mine":620,"voxel-outline":682,"voxel-pickaxe":689,"voxel-plugins-ui":693,"voxel-pumpkin":703,"voxel-quarry":704,"voxel-reach":707,"voxel-recipes":714,"voxel-sfx":724,"voxel-skyhook":725,"voxel-sprint":726,"voxel-use":727,"voxel-voila":728,"voxel-vr":761,"voxel-webview":813,"voxel-wireframe":871,"voxel-wool":873,"voxel-workbench":894,"voxel-zen":895}],44:[function(require,module,exports){
'use strict';
var createDatgui = require('dat-gui');
module.exports = function(game, opts) {
return new CameraDebug(game, opts);
};
module.exports.pluginInfo = {
loadAfter: ['voxel-plugins-ui', 'voxel-shader', 'game-shell-fps-camera']
};
function CameraDebug(game, opts) {
this.game = game;
this.gui = opts.gui || (game.plugins && game.plugins.get('voxel-plugins-ui') ? game.plugins.get('voxel-plugins-ui').gui : new createDatgui.GUI());
this.shader = game.plugins.get('voxel-shader');
if (!this.shader) throw new Error('camera-debug requires voxel-shader');
this.enable();
}
CameraDebug.prototype.enable = function() {
this.folder = this.gui.addFolder('camera');
var updateProjectionMatrix = this.shader.updateProjectionMatrix.bind(this.shader);
this.folder.add(this.shader, 'cameraFOV', 45, 110).onChange(updateProjectionMatrix);
this.folder.add(this.shader, 'cameraNear', 0.1, 10, 0.1).onChange(updateProjectionMatrix);
this.folder.add(this.shader, 'cameraFar', 10, 1000).onChange(updateProjectionMatrix);
this.updateables = [];
this.addVectorFolder('position', game.controls.target().avatar, 'position');
this.addVectorFolder('rotation', game.controls.target().avatar, 'rotation');
this.addVectorFolder('game.cameraPosition()', game, 'cameraPosition');
this.addVectorFolder('game.cameraVector()', game, 'cameraVector');
this.game.on('tick', this.onTick = this.tick.bind(this));
};
CameraDebug.prototype.disable = function() {
// TODO: remove folder. but, https://code.google.com/p/dat-gui/issues/detail?id=21
this.game.removeListener('tick', this.onTick);
};
var VectorProxy = function(obj, prop, gui) {
this.obj = obj;
this.prop = prop;
this.gui = gui;
this.x = this.y = this.z = 0.01
};
VectorProxy.prototype.update = function() {
var value = this.obj[this.prop];
if (typeof value === 'function') {
// function returning vec3 array
var vector = value.call(this.obj);
this.x = vector[0];
this.y = vector[1];
this.z = vector[2];
} else {
// property with .x .y .z
this.x = value.x;
this.y = value.y;
this.z = value.z;
}
// http://workshop.chromeexperiments.com/examples/gui/#10--Updating-the-Display-Manually
for (var i in this.gui.__controllers) {
this.gui.__controllers[i].updateDisplay();
}
};
CameraDebug.prototype.addVectorFolder = function(name, obj, prop) {
var folder = this.folder.addFolder(name);
var proxy = new VectorProxy(obj, prop, folder);
folder.add(proxy, 'x');
folder.add(proxy, 'y');
folder.add(proxy, 'z');
this.updateables.push(proxy);
};
CameraDebug.prototype.tick = function() {
for (var i = 0; i < this.updateables.length; i += 1) {
// update method pattern, http://gameprogrammingpatterns.com/update-method.html
this.updateables[i].update();
}
};
},{"dat-gui":45}],45:[function(require,module,exports){
module.exports = require('./vendor/dat.gui')
module.exports.color = require('./vendor/dat.color')
},{"./vendor/dat.color":46,"./vendor/dat.gui":47}],46:[function(require,module,exports){
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
/** @namespace */
var dat = module.exports = dat || {};
/** @namespace */
dat.color = dat.color || {};
/** @namespace */
dat.utils = dat.utils || {};
dat.utils.common = (function () {
var ARR_EACH = Array.prototype.forEach;
var ARR_SLICE = Array.prototype.slice;
/**
* Band-aid methods for things that should be a lot easier in JavaScript.
* Implementation and structure inspired by underscore.js
* http://documentcloud.github.com/underscore/
*/
return {
BREAK: {},
extend: function(target) {
this.each(ARR_SLICE.call(arguments, 1), function(obj) {
for (var key in obj)
if (!this.isUndefined(obj[key]))
target[key] = obj[key];
}, this);
return target;
},
defaults: function(target) {
this.each(ARR_SLICE.call(arguments, 1), function(obj) {
for (var key in obj)
if (this.isUndefined(target[key]))
target[key] = obj[key];
}, this);
return target;
},
compose: function() {
var toCall = ARR_SLICE.call(arguments);
return function() {
var args = ARR_SLICE.call(arguments);
for (var i = toCall.length -1; i >= 0; i--) {
args = [toCall[i].apply(this, args)];
}
return args[0];
}
},
each: function(obj, itr, scope) {
if (ARR_EACH && obj.forEach === ARR_EACH) {
obj.forEach(itr, scope);
} else if (obj.length === obj.length + 0) { // Is number but not NaN
for (var key = 0, l = obj.length; key < l; key++)
if (key in obj && itr.call(scope, obj[key], key) === this.BREAK)
return;
} else {
for (var key in obj)
if (itr.call(scope, obj[key], key) === this.BREAK)
return;
}
},
defer: function(fnc) {
setTimeout(fnc, 0);
},
toArray: function(obj) {
if (obj.toArray) return obj.toArray();
return ARR_SLICE.call(obj);
},
isUndefined: function(obj) {
return obj === undefined;
},
isNull: function(obj) {
return obj === null;
},
isNaN: function(obj) {
return obj !== obj;
},
isArray: Array.isArray || function(obj) {
return obj.constructor === Array;
},
isObject: function(obj) {
return obj === Object(obj);
},
isNumber: function(obj) {
return obj === obj+0;
},
isString: function(obj) {
return obj === obj+'';
},
isBoolean: function(obj) {
return obj === false || obj === true;
},
isFunction: function(obj) {
return Object.prototype.toString.call(obj) === '[object Function]';
}
};
})();
dat.color.toString = (function (common) {
return function(color) {
if (color.a == 1 || common.isUndefined(color.a)) {
var s = color.hex.toString(16);
while (s.length < 6) {
s = '0' + s;
}
return '#' + s;
} else {
return 'rgba(' + Math.round(color.r) + ',' + Math.round(color.g) + ',' + Math.round(color.b) + ',' + color.a + ')';
}
}
})(dat.utils.common);
dat.Color = dat.color.Color = (function (interpret, math, toString, common) {
var Color = function() {
this.__state = interpret.apply(this, arguments);
if (this.__state === false) {
throw 'Failed to interpret color arguments';
}
this.__state.a = this.__state.a || 1;
};
Color.COMPONENTS = ['r','g','b','h','s','v','hex','a'];
common.extend(Color.prototype, {
toString: function() {
return toString(this);
},
toOriginal: function() {
return this.__state.conversion.write(this);
}
});
defineRGBComponent(Color.prototype, 'r', 2);
defineRGBComponent(Color.prototype, 'g', 1);
defineRGBComponent(Color.prototype, 'b', 0);
defineHSVComponent(Color.prototype, 'h');
defineHSVComponent(Color.prototype, 's');
defineHSVComponent(Color.prototype, 'v');
Object.defineProperty(Color.prototype, 'a', {
get: function() {
return this.__state.a;
},
set: function(v) {
this.__state.a = v;
}
});
Object.defineProperty(Color.prototype, 'hex', {
get: function() {
if (!this.__state.space !== 'HEX') {
this.__state.hex = math.rgb_to_hex(this.r, this.g, this.b);
}
return this.__state.hex;
},
set: function(v) {
this.__state.space = 'HEX';
this.__state.hex = v;
}
});
function defineRGBComponent(target, component, componentHexIndex) {
Object.defineProperty(target, component, {
get: function() {
if (this.__state.space === 'RGB') {
return this.__state[component];
}
recalculateRGB(this, component, componentHexIndex);
return this.__state[component];
},
set: function(v) {
if (this.__state.space !== 'RGB') {
recalculateRGB(this, component, componentHexIndex);
this.__state.space = 'RGB';
}
this.__state[component] = v;
}
});
}
function defineHSVComponent(target, component) {
Object.defineProperty(target, component, {
get: function() {
if (this.__state.space === 'HSV')
return this.__state[component];
recalculateHSV(this);
return this.__state[component];
},
set: function(v) {
if (this.__state.space !== 'HSV') {
recalculateHSV(this);
this.__state.space = 'HSV';
}
this.__state[component] = v;
}
});
}
function recalculateRGB(color, component, componentHexIndex) {
if (color.__state.space === 'HEX') {
color.__state[component] = math.component_from_hex(color.__state.hex, componentHexIndex);
} else if (color.__state.space === 'HSV') {
common.extend(color.__state, math.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
} else {
throw 'Corrupted color state';
}
}
function recalculateHSV(color) {
var result = math.rgb_to_hsv(color.r, color.g, color.b);
common.extend(color.__state,
{
s: result.s,
v: result.v
}
);
if (!common.isNaN(result.h)) {
color.__state.h = result.h;
} else if (common.isUndefined(color.__state.h)) {
color.__state.h = 0;
}
}
return Color;
})(dat.color.interpret = (function (toString, common) {
var result, toReturn;
var interpret = function() {
toReturn = false;
var original = arguments.length > 1 ? common.toArray(arguments) : arguments[0];
common.each(INTERPRETATIONS, function(family) {
if (family.litmus(original)) {
common.each(family.conversions, function(conversion, conversionName) {
result = conversion.read(original);
if (toReturn === false && result !== false) {
toReturn = result;
result.conversionName = conversionName;
result.conversion = conversion;
return common.BREAK;
}
});
return common.BREAK;
}
});
return toReturn;
};
var INTERPRETATIONS = [
// Strings
{
litmus: common.isString,
conversions: {
THREE_CHAR_HEX: {
read: function(original) {
var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
if (test === null) return false;
return {
space: 'HEX',
hex: parseInt(
'0x' +
test[1].toString() + test[1].toString() +
test[2].toString() + test[2].toString() +
test[3].toString() + test[3].toString())
};
},
write: toString
},
SIX_CHAR_HEX: {
read: function(original) {
var test = original.match(/^#([A-F0-9]{6})$/i);
if (test === null) return false;
return {
space: 'HEX',
hex: parseInt('0x' + test[1].toString())
};
},
write: toString
},
CSS_RGB: {
read: function(original) {
var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
if (test === null) return false;
return {
space: 'RGB',
r: parseFloat(test[1]),
g: parseFloat(test[2]),
b: parseFloat(test[3])
};
},
write: toString
},
CSS_RGBA: {
read: function(original) {
var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\,\s*(.+)\s*\)/);
if (test === null) return false;
return {
space: 'RGB',
r: parseFloat(test[1]),
g: parseFloat(test[2]),
b: parseFloat(test[3]),
a: parseFloat(test[4])
};
},
write: toString
}
}
},
// Numbers
{
litmus: common.isNumber,
conversions: {
HEX: {
read: function(original) {
return {
space: 'HEX',
hex: original,
conversionName: 'HEX'
}
},
write: function(color) {
return color.hex;
}
}
}
},
// Arrays
{
litmus: common.isArray,
conversions: {
RGB_ARRAY: {
read: function(original) {
if (original.length != 3) return false;
return {
space: 'RGB',
r: original[0],
g: original[1],
b: original[2]
};
},
write: function(color) {
return [color.r, color.g, color.b];
}
},
RGBA_ARRAY: {
read: function(original) {
if (original.length != 4) return false;
return {
space: 'RGB',
r: original[0],
g: original[1],
b: original[2],
a: original[3]
};
},
write: function(color) {
return [color.r, color.g, color.b, color.a];
}
}
}
},
// Objects
{
litmus: common.isObject,
conversions: {
RGBA_OBJ: {
read: function(original) {
if (common.isNumber(original.r) &&
common.isNumber(original.g) &&
common.isNumber(original.b) &&
common.isNumber(original.a)) {
return {
space: 'RGB',
r: original.r,
g: original.g,
b: original.b,
a: original.a
}
}
return false;
},
write: function(color) {
return {
r: color.r,
g: color.g,
b: color.b,
a: color.a
}
}
},
RGB_OBJ: {
read: function(original) {
if (common.isNumber(original.r) &&
common.isNumber(original.g) &&
common.isNumber(original.b)) {
return {
space: 'RGB',
r: original.r,
g: original.g,
b: original.b
}
}
return false;
},
write: function(color) {
return {
r: color.r,
g: color.g,
b: color.b
}
}
},
HSVA_OBJ: {
read: function(original) {
if (common.isNumber(original.h) &&
common.isNumber(original.s) &&
common.isNumber(original.v) &&
common.isNumber(original.a)) {
return {
space: 'HSV',
h: original.h,
s: original.s,
v: original.v,
a: original.a
}
}
return false;
},
write: function(color) {
return {
h: color.h,
s: color.s,
v: color.v,
a: color.a
}
}
},
HSV_OBJ: {
read: function(original) {
if (common.isNumber(original.h) &&
common.isNumber(original.s) &&
common.isNumber(original.v)) {
return {
space: 'HSV',
h: original.h,
s: original.s,
v: original.v
}
}
return false;
},
write: function(color) {
return {
h: color.h,
s: color.s,
v: color.v
}
}
}
}
}
];
return interpret;
})(dat.color.toString,
dat.utils.common),
dat.color.math = (function () {
var tmpComponent;
return {
hsv_to_rgb: function(h, s, v) {
var hi = Math.floor(h / 60) % 6;
var f = h / 60 - Math.floor(h / 60);
var p = v * (1.0 - s);
var q = v * (1.0 - (f * s));
var t = v * (1.0 - ((1.0 - f) * s));
var c = [
[v, t, p],
[q, v, p],
[p, v, t],
[p, q, v],
[t, p, v],
[v, p, q]
][hi];
return {
r: c[0] * 255,
g: c[1] * 255,
b: c[2] * 255
};
},
rgb_to_hsv: function(r, g, b) {
var min = Math.min(r, g, b),
max = Math.max(r, g, b),
delta = max - min,
h, s;
if (max != 0) {
s = delta / max;
} else {
return {
h: NaN,
s: 0,
v: 0
};
}
if (r == max) {
h = (g - b) / delta;
} else if (g == max) {
h = 2 + (b - r) / delta;
} else {
h = 4 + (r - g) / delta;
}
h /= 6;
if (h < 0) {
h += 1;
}
return {
h: h * 360,
s: s,
v: max / 255
};
},
rgb_to_hex: function(r, g, b) {
var hex = this.hex_with_component(0, 2, r);
hex = this.hex_with_component(hex, 1, g);
hex = this.hex_with_component(hex, 0, b);
return hex;
},
component_from_hex: function(hex, componentIndex) {
return (hex >> (componentIndex * 8)) & 0xFF;
},
hex_with_component: function(hex, componentIndex, value) {
return value << (tmpComponent = componentIndex * 8) | (hex & ~ (0xFF << tmpComponent));
}
}
})(),
dat.color.toString,
dat.utils.common);
},{}],47:[function(require,module,exports){
/**
* dat-gui JavaScript Controller Library
* http://code.google.com/p/dat-gui
*
* Copyright 2011 Data Arts Team, Google Creative Lab
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
/** @namespace */
var dat = module.exports = dat || {};
/** @namespace */
dat.gui = dat.gui || {};
/** @namespace */
dat.utils = dat.utils || {};
/** @namespace */
dat.controllers = dat.controllers || {};
/** @namespace */
dat.dom = dat.dom || {};
/** @namespace */
dat.color = dat.color || {};
dat.utils.css = (function () {
return {
load: function (url, doc) {
doc = doc || document;
var link = doc.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = url;
doc.getElementsByTagName('head')[0].appendChild(link);
},
inject: function(css, doc) {
doc = doc || document;
var injected = document.createElement('style');
injected.type = 'text/css';
injected.innerHTML = css;
doc.getElementsByTagName('head')[0].appendChild(injected);
}
}
})();
dat.utils.common = (function () {
var ARR_EACH = Array.prototype.forEach;
var ARR_SLICE = Array.prototype.slice;
/**
* Band-aid methods for things that should be a lot easier in JavaScript.
* Implementation and structure inspired by underscore.js
* http://documentcloud.github.com/underscore/
*/
return {
BREAK: {},
extend: function(target) {
this.each(ARR_SLICE.call(arguments, 1), function(obj) {
for (var key in obj)
if (!this.isUndefined(obj[key]))
target[key] = obj[key];
}, this);
return target;
},
defaults: function(target) {
this.each(ARR_SLICE.call(arguments, 1), function(obj) {
for (var key in obj)
if (this.isUndefined(target[key]))
target[key] = obj[key];
}, this);
return target;
},
compose: function() {
var toCall = ARR_SLICE.call(arguments);
return function() {
var args = ARR_SLICE.call(arguments);
for (var i = toCall.length -1; i >= 0; i--) {
args = [toCall[i].apply(this, args)];
}
return args[0];
}
},
each: function(obj, itr, scope) {
if (ARR_EACH && obj.forEach === ARR_EACH) {
obj.forEach(itr, scope);
} else if (obj.length === obj.length + 0) { // Is number but not NaN
for (var key = 0, l = obj.length; key < l; key++)
if (key in obj && itr.call(scope, obj[key], key) === this.BREAK)
return;
} else {
for (var key in obj)
if (itr.call(scope, obj[key], key) === this.BREAK)
return;
}
},
defer: function(fnc) {
setTimeout(fnc, 0);
},
toArray: function(obj) {
if (obj.toArray) return obj.toArray();
return ARR_SLICE.call(obj);
},
isUndefined: function(obj) {
return obj === undefined;
},
isNull: function(obj) {
return obj === null;
},
isNaN: function(obj) {
return obj !== obj;
},
isArray: Array.isArray || function(obj) {
return obj.constructor === Array;
},
isObject: function(obj) {
return obj === Object(obj);
},
isNumber: function(obj) {
return obj === obj+0;
},
isString: function(obj) {
return obj === obj+'';
},
isBoolean: function(obj) {
return obj === false || obj === true;
},
isFunction: function(obj) {
return Object.prototype.toString.call(obj) === '[object Function]';
}
};
})();
dat.controllers.Controller = (function (common) {
/**
* @class An "abstract" class that represents a given property of an object.
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
*
* @member dat.controllers
*/
var Controller = function(object, property) {
this.initialValue = object[property];
/**
* Those who extend this class will put their DOM elements in here.
* @type {DOMElement}
*/
this.domElement = document.createElement('div');
/**
* The object to manipulate
* @type {Object}
*/
this.object = object;
/**
* The name of the property to manipulate
* @type {String}
*/
this.property = property;
/**
* The function to be called on change.
* @type {Function}
* @ignore
*/
this.__onChange = undefined;
/**
* The function to be called on finishing change.
* @type {Function}
* @ignore
*/
this.__onFinishChange = undefined;
};
common.extend(
Controller.prototype,
/** @lends dat.controllers.Controller.prototype */
{
/**
* Specify that a function fire every time someone changes the value with
* this Controller.
*
* @param {Function} fnc This function will be called whenever the value
* is modified via this Controller.
* @returns {dat.controllers.Controller} this
*/
onChange: function(fnc) {
this.__onChange = fnc;
return this;
},
/**
* Specify that a function fire every time someone "finishes" changing
* the value wih this Controller. Useful for values that change
* incrementally like numbers or strings.
*
* @param {Function} fnc This function will be called whenever
* someone "finishes" changing the value via this Controller.
* @returns {dat.controllers.Controller} this
*/
onFinishChange: function(fnc) {
this.__onFinishChange = fnc;
return this;
},
/**
* Change the value of <code>object[property]</code>
*
* @param {Object} newValue The new value of <code>object[property]</code>
*/
setValue: function(newValue) {
this.object[this.property] = newValue;
if (this.__onChange) {
this.__onChange.call(this, newValue);
}
this.updateDisplay();
return this;
},
/**
* Gets the value of <code>object[property]</code>
*
* @returns {Object} The current value of <code>object[property]</code>
*/
getValue: function() {
return this.object[this.property];
},
/**
* Refreshes the visual display of a Controller in order to keep sync
* with the object's current value.
* @returns {dat.controllers.Controller} this
*/
updateDisplay: function() {
return this;
},
/**
* @returns {Boolean} true if the value has deviated from initialValue
*/
isModified: function() {
return this.initialValue !== this.getValue()
}
}
);
return Controller;
})(dat.utils.common);
dat.dom.dom = (function (common) {
var EVENT_MAP = {
'HTMLEvents': ['change'],
'MouseEvents': ['click','mousemove','mousedown','mouseup', 'mouseover'],
'KeyboardEvents': ['keydown']
};
var EVENT_MAP_INV = {};
common.each(EVENT_MAP, function(v, k) {
common.each(v, function(e) {
EVENT_MAP_INV[e] = k;
});
});
var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
function cssValueToPixels(val) {
if (val === '0' || common.isUndefined(val)) return 0;
var match = val.match(CSS_VALUE_PIXELS);
if (!common.isNull(match)) {
return parseFloat(match[1]);
}
// TODO ...ems? %?
return 0;
}
/**
* @namespace
* @member dat.dom
*/
var dom = {
/**
*
* @param elem
* @param selectable
*/
makeSelectable: function(elem, selectable) {
if (elem === undefined || elem.style === undefined) return;
elem.onselectstart = selectable ? function() {
return false;
} : function() {
};
elem.style.MozUserSelect = selectable ? 'auto' : 'none';
elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
elem.unselectable = selectable ? 'on' : 'off';
},
/**
*
* @param elem
* @param horizontal
* @param vertical
*/
makeFullscreen: function(elem, horizontal, vertical) {
if (common.isUndefined(horizontal)) horizontal = true;
if (common.isUndefined(vertical)) vertical = true;
elem.style.position = 'absolute';
if (horizontal) {
elem.style.left = 0;
elem.style.right = 0;
}
if (vertical) {
elem.style.top = 0;
elem.style.bottom = 0;
}
},
/**
*
* @param elem
* @param eventType
* @param params
*/
fakeEvent: function(elem, eventType, params, aux) {
params = params || {};
var className = EVENT_MAP_INV[eventType];
if (!className) {
throw new Error('Event type ' + eventType + ' not supported.');
}
var evt = document.createEvent(className);
switch (className) {
case 'MouseEvents':
var clientX = params.x || params.clientX || 0;
var clientY = params.y || params.clientY || 0;
evt.initMouseEvent(eventType, params.bubbles || false,
params.cancelable || true, window, params.clickCount || 1,
0, //screen X
0, //screen Y
clientX, //client X
clientY, //client Y
false, false, false, false, 0, null);
break;
case 'KeyboardEvents':
var init = evt.initKeyboardEvent || evt.initKeyEvent; // webkit || moz
common.defaults(params, {
cancelable: true,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
keyCode: undefined,
charCode: undefined
});
init(eventType, params.bubbles || false,
params.cancelable, window,
params.ctrlKey, params.altKey,
params.shiftKey, params.metaKey,
params.keyCode, params.charCode);
break;
default:
evt.initEvent(eventType, params.bubbles || false,
params.cancelable || true);
break;
}
common.defaults(evt, aux);
elem.dispatchEvent(evt);
},
/**
*
* @param elem
* @param event
* @param func
* @param bool
*/
bind: function(elem, event, func, bool) {
bool = bool || false;
if (elem.addEventListener)
elem.addEventListener(event, func, bool);
else if (elem.attachEvent)
elem.attachEvent('on' + event, func);
return dom;
},
/**
*
* @param elem
* @param event
* @param func
* @param bool
*/
unbind: function(elem, event, func, bool) {
bool = bool || false;
if (elem.removeEventListener)
elem.removeEventListener(event, func, bool);
else if (elem.detachEvent)
elem.detachEvent('on' + event, func);
return dom;
},
/**
*
* @param elem
* @param className
*/
addClass: function(elem, className) {
if (elem.className === undefined) {
elem.className = className;
} else if (elem.className !== className) {
var classes = elem.className.split(/ +/);
if (classes.indexOf(className) == -1) {
classes.push(className);
elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
}
}
return dom;
},
/**
*
* @param elem
* @param className
*/
removeClass: function(elem, className) {
if (className) {
if (elem.className === undefined) {
// elem.className = className;
} else if (elem.className === className) {
elem.removeAttribute('class');
} else {
var classes = elem.className.split(/ +/);
var index = classes.indexOf(className);
if (index != -1) {
classes.splice(index, 1);
elem.className = classes.join(' ');
}
}
} else {
elem.className = undefined;
}
return dom;
},
hasClass: function(elem, className) {
return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
},
/**
*
* @param elem
*/
getWidth: function(elem) {
var style = getComputedStyle(elem);
return cssValueToPixels(style['border-left-width']) +
cssValueToPixels(style['border-right-width']) +
cssValueToPixels(style['padding-left']) +
cssValueToPixels(style['padding-right']) +
cssValueToPixels(style['width']);
},
/**
*
* @param elem
*/
getHeight: function(elem) {
var style = getComputedStyle(elem);
return cssValueToPixels(style['border-top-width']) +
cssValueToPixels(style['border-bottom-width']) +
cssValueToPixels(style['padding-top']) +
cssValueToPixels(style['padding-bottom']) +
cssValueToPixels(style['height']);
},
/**
*
* @param elem
*/
getOffset: function(elem) {
var offset = {left: 0, top:0};
if (elem.offsetParent) {
do {
offset.left += elem.offsetLeft;
offset.top += elem.offsetTop;
} while (elem = elem.offsetParent);
}
return offset;
},
// http://stackoverflow.com/posts/2684561/revisions
/**
*
* @param elem
*/
isActive: function(elem) {
return elem === document.activeElement && ( elem.type || elem.href );
}
};
return dom;
})(dat.utils.common);
dat.controllers.OptionController = (function (Controller, dom, common) {
/**
* @class Provides a select input to alter the property of an object, using a
* list of accepted values.
*
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
* @param {Object|string[]} options A map of labels to acceptable values, or
* a list of acceptable string values.
*
* @member dat.controllers
*/
var OptionController = function(object, property, options) {
OptionController.superclass.call(this, object, property);
var _this = this;
/**
* The drop down menu
* @ignore
*/
this.__select = document.createElement('select');
if (common.isArray(options)) {
var map = {};
common.each(options, function(element) {
map[element] = element;
});
options = map;
}
common.each(options, function(value, key) {
var opt = document.createElement('option');
opt.innerHTML = key;
opt.setAttribute('value', value);
_this.__select.appendChild(opt);
});
// Acknowledge original value
this.updateDisplay();
dom.bind(this.__select, 'change', function() {
var desiredValue = this.options[this.selectedIndex].value;
_this.setValue(desiredValue);
});
this.domElement.appendChild(this.__select);
};
OptionController.superclass = Controller;
common.extend(
OptionController.prototype,
Controller.prototype,
{
setValue: function(v) {
var toReturn = OptionController.superclass.prototype.setValue.call(this, v);
if (this.__onFinishChange) {
this.__onFinishChange.call(this, this.getValue());
}
return toReturn;
},
updateDisplay: function() {
this.__select.value = this.getValue();
return OptionController.superclass.prototype.updateDisplay.call(this);
}
}
);
return OptionController;
})(dat.controllers.Controller,
dat.dom.dom,
dat.utils.common);
dat.controllers.NumberController = (function (Controller, common) {
/**
* @class Represents a given property of an object that is a number.
*
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
* @param {Object} [params] Optional parameters
* @param {Number} [params.min] Minimum allowed value
* @param {Number} [params.max] Maximum allowed value
* @param {Number} [params.step] Increment by which to change value
*
* @member dat.controllers
*/
var NumberController = function(object, property, params) {
NumberController.superclass.call(this, object, property);
params = params || {};
this.__min = params.min;
this.__max = params.max;
this.__step = params.step;
if (common.isUndefined(this.__step)) {
if (this.initialValue == 0) {
this.__impliedStep = 1; // What are we, psychics?
} else {
// Hey Doug, check this out.
this.__impliedStep = Math.pow(10, Math.floor(Math.log(this.initialValue)/Math.LN10))/10;
}
} else {
this.__impliedStep = this.__step;
}
this.__precision = numDecimals(this.__impliedStep);
};
NumberController.superclass = Controller;
common.extend(
NumberController.prototype,
Controller.prototype,
/** @lends dat.controllers.NumberController.prototype */
{
setValue: function(v) {
if (this.__min !== undefined && v < this.__min) {
v = this.__min;
} else if (this.__max !== undefined && v > this.__max) {
v = this.__max;
}
if (this.__step !== undefined && v % this.__step != 0) {
v = Math.round(v / this.__step) * this.__step;
}
return NumberController.superclass.prototype.setValue.call(this, v);
},
/**
* Specify a minimum value for <code>object[property]</code>.
*
* @param {Number} minValue The minimum value for
* <code>object[property]</code>
* @returns {dat.controllers.NumberController} this
*/
min: function(v) {
this.__min = v;
return this;
},
/**
* Specify a maximum value for <code>object[property]</code>.
*
* @param {Number} maxValue The maximum value for
* <code>object[property]</code>
* @returns {dat.controllers.NumberController} this
*/
max: function(v) {
this.__max = v;
return this;
},
/**
* Specify a step value that dat.controllers.NumberController
* increments by.
*
* @param {Number} stepValue The step value for
* dat.controllers.NumberController
* @default if minimum and maximum specified increment is 1% of the
* difference otherwise stepValue is 1
* @returns {dat.controllers.NumberController} this
*/
step: function(v) {
this.__step = v;
return this;
}
}
);
function numDecimals(x) {
x = x.toString();
if (x.indexOf('.') > -1) {
return x.length - x.indexOf('.') - 1;
} else {
return 0;
}
}
return NumberController;
})(dat.controllers.Controller,
dat.utils.common);
dat.controllers.NumberControllerBox = (function (NumberController, dom, common) {
/**
* @class Represents a given property of an object that is a number and
* provides an input element with which to manipulate it.
*
* @extends dat.controllers.Controller
* @extends dat.controllers.NumberController
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
* @param {Object} [params] Optional parameters
* @param {Number} [params.min] Minimum allowed value
* @param {Number} [params.max] Maximum allowed value
* @param {Number} [params.step] Increment by which to change value
*
* @member dat.controllers
*/
var NumberControllerBox = function(object, property, params) {
this.__truncationSuspended = false;
NumberControllerBox.superclass.call(this, object, property, params);
var _this = this;
/**
* {Number} Previous mouse y position
* @ignore
*/
var prev_y;
this.__input = document.createElement('input');
this.__input.setAttribute('type', 'text');
// Makes it so manually specified values are not truncated.
dom.bind(this.__input, 'change', onChange);
dom.bind(this.__input, 'blur', onBlur);
dom.bind(this.__input, 'mousedown', onMouseDown);
dom.bind(this.__input, 'keydown', function(e) {
// When pressing entire, you can be as precise as you want.
if (e.keyCode === 13) {
_this.__truncationSuspended = true;
this.blur();
_this.__truncationSuspended = false;
}
});
function onChange() {
var attempted = parseFloat(_this.__input.value);
if (!common.isNaN(attempted)) _this.setValue(attempted);
}
function onBlur() {
onChange();
if (_this.__onFinishChange) {
_this.__onFinishChange.call(_this, _this.getValue());
}
}
function onMouseDown(e) {
dom.bind(window, 'mousemove', onMouseDrag);
dom.bind(window, 'mouseup', onMouseUp);
prev_y = e.clientY;
}
function onMouseDrag(e) {
var diff = prev_y - e.clientY;
_this.setValue(_this.getValue() + diff * _this.__impliedStep);
prev_y = e.clientY;
}
function onMouseUp() {
dom.unbind(window, 'mousemove', onMouseDrag);
dom.unbind(window, 'mouseup', onMouseUp);
}
this.updateDisplay();
this.domElement.appendChild(this.__input);
};
NumberControllerBox.superclass = NumberController;
common.extend(
NumberControllerBox.prototype,
NumberController.prototype,
{
updateDisplay: function() {
this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
return NumberControllerBox.superclass.prototype.updateDisplay.call(this);
}
}
);
function roundToDecimal(value, decimals) {
var tenTo = Math.pow(10, decimals);
return Math.round(value * tenTo) / tenTo;
}
return NumberControllerBox;
})(dat.controllers.NumberController,
dat.dom.dom,
dat.utils.common);
dat.controllers.NumberControllerSlider = (function (NumberController, dom, css, common, styleSheet) {
/**
* @class Represents a given property of an object that is a number, contains
* a minimum and maximum, and provides a slider element with which to
* manipulate it. It should be noted that the slider element is made up of
* <code>&lt;div&gt;</code> tags, <strong>not</strong> the html5
* <code>&lt;slider&gt;</code> element.
*
* @extends dat.controllers.Controller
* @extends dat.controllers.NumberController
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
* @param {Number} minValue Minimum allowed value
* @param {Number} maxValue Maximum allowed value
* @param {Number} stepValue Increment by which to change value
*
* @member dat.controllers
*/
var NumberControllerSlider = function(object, property, min, max, step) {
NumberControllerSlider.superclass.call(this, object, property, { min: min, max: max, step: step });
var _this = this;
this.__background = document.createElement('div');
this.__foreground = document.createElement('div');
dom.bind(this.__background, 'mousedown', onMouseDown);
dom.addClass(this.__background, 'slider');
dom.addClass(this.__foreground, 'slider-fg');
function onMouseDown(e) {
dom.bind(window, 'mousemove', onMouseDrag);
dom.bind(window, 'mouseup', onMouseUp);
onMouseDrag(e);
}
function onMouseDrag(e) {
e.preventDefault();
var offset = dom.getOffset(_this.__background);
var width = dom.getWidth(_this.__background);
_this.setValue(
map(e.clientX, offset.left, offset.left + width, _this.__min, _this.__max)
);
return false;
}
function onMouseUp() {
dom.unbind(window, 'mousemove', onMouseDrag);
dom.unbind(window, 'mouseup', onMouseUp);
if (_this.__onFinishChange) {
_this.__onFinishChange.call(_this, _this.getValue());
}
}
this.updateDisplay();
this.__background.appendChild(this.__foreground);
this.domElement.appendChild(this.__background);
};
NumberControllerSlider.superclass = NumberController;
/**
* Injects default stylesheet for slider elements.
*/
NumberControllerSlider.useDefaultStyles = function() {
css.inject(styleSheet);
};
common.extend(
NumberControllerSlider.prototype,
NumberController.prototype,
{
updateDisplay: function() {
var pct = (this.getValue() - this.__min)/(this.__max - this.__min);
this.__foreground.style.width = pct*100+'%';
return NumberControllerSlider.superclass.prototype.updateDisplay.call(this);
}
}
);
function map(v, i1, i2, o1, o2) {
return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
}
return NumberControllerSlider;
})(dat.controllers.NumberController,
dat.dom.dom,
dat.utils.css,
dat.utils.common,
".slider {\n box-shadow: inset 0 2px 4px rgba(0,0,0,0.15);\n height: 1em;\n border-radius: 1em;\n background-color: #eee;\n padding: 0 0.5em;\n overflow: hidden;\n}\n\n.slider-fg {\n padding: 1px 0 2px 0;\n background-color: #aaa;\n height: 1em;\n margin-left: -0.5em;\n padding-right: 0.5em;\n border-radius: 1em 0 0 1em;\n}\n\n.slider-fg:after {\n display: inline-block;\n border-radius: 1em;\n background-color: #fff;\n border: 1px solid #aaa;\n content: '';\n float: right;\n margin-right: -1em;\n margin-top: -1px;\n height: 0.9em;\n width: 0.9em;\n}");
dat.controllers.FunctionController = (function (Controller, dom, common) {
/**
* @class Provides a GUI interface to fire a specified method, a property of an object.
*
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
*
* @member dat.controllers
*/
var FunctionController = function(object, property, text) {
FunctionController.superclass.call(this, object, property);
var _this = this;
this.__button = document.createElement('div');
this.__button.innerHTML = text === undefined ? 'Fire' : text;
dom.bind(this.__button, 'click', function(e) {
e.preventDefault();
_this.fire();
return false;
});
dom.addClass(this.__button, 'button');
this.domElement.appendChild(this.__button);
};
FunctionController.superclass = Controller;
common.extend(
FunctionController.prototype,
Controller.prototype,
{
fire: function() {
if (this.__onChange) {
this.__onChange.call(this);
}
if (this.__onFinishChange) {
this.__onFinishChange.call(this, this.getValue());
}
this.getValue().call(this.object);
}
}
);
return FunctionController;
})(dat.controllers.Controller,
dat.dom.dom,
dat.utils.common);
dat.controllers.BooleanController = (function (Controller, dom, common) {
/**
* @class Provides a checkbox input to alter the boolean property of an object.
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
*
* @member dat.controllers
*/
var BooleanController = function(object, property) {
BooleanController.superclass.call(this, object, property);
var _this = this;
this.__prev = this.getValue();
this.__checkbox = document.createElement('input');
this.__checkbox.setAttribute('type', 'checkbox');
dom.bind(this.__checkbox, 'change', onChange, false);
this.domElement.appendChild(this.__checkbox);
// Match original value
this.updateDisplay();
function onChange() {
_this.setValue(!_this.__prev);
}
};
BooleanController.superclass = Controller;
common.extend(
BooleanController.prototype,
Controller.prototype,
{
setValue: function(v) {
var toReturn = BooleanController.superclass.prototype.setValue.call(this, v);
if (this.__onFinishChange) {
this.__onFinishChange.call(this, this.getValue());
}
this.__prev = this.getValue();
return toReturn;
},
updateDisplay: function() {
if (this.getValue() === true) {
this.__checkbox.setAttribute('checked', 'checked');
this.__checkbox.checked = true;
} else {
this.__checkbox.checked = false;
}
return BooleanController.superclass.prototype.updateDisplay.call(this);
}
}
);
return BooleanController;
})(dat.controllers.Controller,
dat.dom.dom,
dat.utils.common);
dat.color.toString = (function (common) {
return function(color) {
if (color.a == 1 || common.isUndefined(color.a)) {
var s = color.hex.toString(16);
while (s.length < 6) {
s = '0' + s;
}
return '#' + s;
} else {
return 'rgba(' + Math.round(color.r) + ',' + Math.round(color.g) + ',' + Math.round(color.b) + ',' + color.a + ')';
}
}
})(dat.utils.common);
dat.color.interpret = (function (toString, common) {
var result, toReturn;
var interpret = function() {
toReturn = false;
var original = arguments.length > 1 ? common.toArray(arguments) : arguments[0];
common.each(INTERPRETATIONS, function(family) {
if (family.litmus(original)) {
common.each(family.conversions, function(conversion, conversionName) {
result = conversion.read(original);
if (toReturn === false && result !== false) {
toReturn = result;
result.conversionName = conversionName;
result.conversion = conversion;
return common.BREAK;
}
});
return common.BREAK;
}
});
return toReturn;
};
var INTERPRETATIONS = [
// Strings
{
litmus: common.isString,
conversions: {
THREE_CHAR_HEX: {
read: function(original) {
var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
if (test === null) return false;
return {
space: 'HEX',
hex: parseInt(
'0x' +
test[1].toString() + test[1].toString() +
test[2].toString() + test[2].toString() +
test[3].toString() + test[3].toString())
};
},
write: toString
},
SIX_CHAR_HEX: {
read: function(original) {
var test = original.match(/^#([A-F0-9]{6})$/i);
if (test === null) return false;
return {
space: 'HEX',
hex: parseInt('0x' + test[1].toString())
};
},
write: toString
},
CSS_RGB: {
read: function(original) {
var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
if (test === null) return false;
return {
space: 'RGB',
r: parseFloat(test[1]),
g: parseFloat(test[2]),
b: parseFloat(test[3])
};
},
write: toString
},
CSS_RGBA: {
read: function(original) {
var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\,\s*(.+)\s*\)/);
if (test === null) return false;
return {
space: 'RGB',
r: parseFloat(test[1]),
g: parseFloat(test[2]),
b: parseFloat(test[3]),
a: parseFloat(test[4])
};
},
write: toString
}
}
},
// Numbers
{
litmus: common.isNumber,
conversions: {
HEX: {
read: function(original) {
return {
space: 'HEX',
hex: original,
conversionName: 'HEX'
}
},
write: function(color) {
return color.hex;
}
}
}
},
// Arrays
{
litmus: common.isArray,
conversions: {
RGB_ARRAY: {
read: function(original) {
if (original.length != 3) return false;
return {
space: 'RGB',
r: original[0],
g: original[1],
b: original[2]
};
},
write: function(color) {
return [color.r, color.g, color.b];
}
},
RGBA_ARRAY: {
read: function(original) {
if (original.length != 4) return false;
return {
space: 'RGB',
r: original[0],
g: original[1],
b: original[2],
a: original[3]
};
},
write: function(color) {
return [color.r, color.g, color.b, color.a];
}
}
}
},
// Objects
{
litmus: common.isObject,
conversions: {
RGBA_OBJ: {
read: function(original) {
if (common.isNumber(original.r) &&
common.isNumber(original.g) &&
common.isNumber(original.b) &&
common.isNumber(original.a)) {
return {
space: 'RGB',
r: original.r,
g: original.g,
b: original.b,
a: original.a
}
}
return false;
},
write: function(color) {
return {
r: color.r,
g: color.g,
b: color.b,
a: color.a
}
}
},
RGB_OBJ: {
read: function(original) {
if (common.isNumber(original.r) &&
common.isNumber(original.g) &&
common.isNumber(original.b)) {
return {
space: 'RGB',
r: original.r,
g: original.g,
b: original.b
}
}
return false;
},
write: function(color) {
return {
r: color.r,
g: color.g,
b: color.b
}
}
},
HSVA_OBJ: {
read: function(original) {
if (common.isNumber(original.h) &&
common.isNumber(original.s) &&
common.isNumber(original.v) &&
common.isNumber(original.a)) {
return {
space: 'HSV',
h: original.h,
s: original.s,
v: original.v,
a: original.a
}
}
return false;
},
write: function(color) {
return {
h: color.h,
s: color.s,
v: color.v,
a: color.a
}
}
},
HSV_OBJ: {
read: function(original) {
if (common.isNumber(original.h) &&
common.isNumber(original.s) &&
common.isNumber(original.v)) {
return {
space: 'HSV',
h: original.h,
s: original.s,
v: original.v
}
}
return false;
},
write: function(color) {
return {
h: color.h,
s: color.s,
v: color.v
}
}
}
}
}
];
return interpret;
})(dat.color.toString,
dat.utils.common);
dat.GUI = dat.gui.GUI = (function (css, saveDialogueContents, styleSheet, controllerFactory, Controller, BooleanController, FunctionController, NumberControllerBox, NumberControllerSlider, OptionController, ColorController, requestAnimationFrame, CenteredDiv, dom, common) {
css.inject(styleSheet);
/** Outer-most className for GUI's */
var CSS_NAMESPACE = 'dg';
var HIDE_KEY_CODE = 72;
/** The only value shared between the JS and SCSS. Use caution. */
var CLOSE_BUTTON_HEIGHT = 20;
var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
var SUPPORTS_LOCAL_STORAGE = (function() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
})();
var SAVE_DIALOGUE;
/** Have we yet to create an autoPlace GUI? */
var auto_place_virgin = true;
/** Fixed position div that auto place GUI's go inside */
var auto_place_container;
/** Are we hiding the GUI's ? */
var hide = false;
/** GUI's which should be hidden */
var hideable_guis = [];
/**
* A lightweight controller library for JavaScript. It allows you to easily
* manipulate variables and fire functions on the fly.
* @class
*
* @member dat.gui
*
* @param {Object} [params]
* @param {String} [params.name] The name of this GUI.
* @param {Object} [params.load] JSON object representing the saved state of
* this GUI.
* @param {Boolean} [params.auto=true]
* @param {dat.gui.GUI} [params.parent] The GUI I'm nested in.
* @param {Boolean} [params.closed] If true, starts closed
*/
var GUI = function(params) {
var _this = this;
/**
* Outermost DOM Element
* @type DOMElement
*/
this.domElement = document.createElement('div');
this.__ul = document.createElement('ul');
this.domElement.appendChild(this.__ul);
dom.addClass(this.domElement, CSS_NAMESPACE);
/**
* Nested GUI's by name
* @ignore
*/
this.__folders = {};
this.__controllers = [];
/**
* List of objects I'm remembering for save, only used in top level GUI
* @ignore
*/
this.__rememberedObjects = [];
/**
* Maps the index of remembered objects to a map of controllers, only used
* in top level GUI.
*
* @private
* @ignore
*
* @example
* [
* {
* propertyName: Controller,
* anotherPropertyName: Controller
* },
* {
* propertyName: Controller
* }
* ]
*/
this.__rememberedObjectIndecesToControllers = [];
this.__listening = [];
params = params || {};
// Default parameters
params = common.defaults(params, {
autoPlace: true,
width: GUI.DEFAULT_WIDTH
});
params = common.defaults(params, {
resizable: params.autoPlace,
hideable: params.autoPlace
});
if (!common.isUndefined(params.load)) {
// Explicit preset
if (params.preset) params.load.preset = params.preset;
} else {
params.load = { preset: DEFAULT_DEFAULT_PRESET_NAME };
}
if (common.isUndefined(params.parent) && params.hideable) {
hideable_guis.push(this);
}
// Only root level GUI's are resizable.
params.resizable = common.isUndefined(params.parent) && params.resizable;
if (params.autoPlace && common.isUndefined(params.scrollable)) {
params.scrollable = true;
}
// params.scrollable = common.isUndefined(params.parent) && params.scrollable === true;
// Not part of params because I don't want people passing this in via
// constructor. Should be a 'remembered' value.
var use_local_storage =
SUPPORTS_LOCAL_STORAGE &&
localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
Object.defineProperties(this,
/** @lends dat.gui.GUI.prototype */
{
/**
* The parent <code>GUI</code>
* @type dat.gui.GUI
*/
parent: {
get: function() {
return params.parent;
}
},
scrollable: {
get: function() {
return params.scrollable;
}
},
/**
* Handles <code>GUI</code>'s element placement for you
* @type Boolean
*/
autoPlace: {
get: function() {
return params.autoPlace;
}
},
/**
* The identifier for a set of saved values
* @type String
*/
preset: {
get: function() {
if (_this.parent) {
return _this.getRoot().preset;
} else {
return params.load.preset;
}
},
set: function(v) {
if (_this.parent) {
_this.getRoot().preset = v;
} else {
params.load.preset = v;
}
setPresetSelectIndex(this);
_this.revert();
}
},
/**
* The width of <code>GUI</code> element
* @type Number
*/
width: {
get: function() {
return params.width;
},
set: function(v) {
params.width = v;
setWidth(_this, v);
}
},
/**
* The name of <code>GUI</code>. Used for folders. i.e
* a folder's name
* @type String
*/
name: {
get: function() {
return params.name;
},
set: function(v) {
// TODO Check for collisions among sibling folders
params.name = v;
if (title_row_name) {
title_row_name.innerHTML = params.name;
}
}
},
/**
* Whether the <code>GUI</code> is collapsed or not
* @type Boolean
*/
closed: {
get: function() {
return params.closed;
},
set: function(v) {
params.closed = v;
if (params.closed) {
dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
} else {
dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
}
// For browsers that aren't going to respect the CSS transition,
// Lets just check our height against the window height right off
// the bat.
this.onResize();
if (_this.__closeButton) {
_this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
}
}
},
/**
* Contains all presets
* @type Object
*/
load: {
get: function() {
return params.load;
}
},
/**
* Determines whether or not to use <a href="https://developer.mozilla.org/en/DOM/Storage#localStorage">localStorage</a> as the means for
* <code>remember</code>ing
* @type Boolean
*/
useLocalStorage: {
get: function() {
return use_local_storage;
},
set: function(bool) {
if (SUPPORTS_LOCAL_STORAGE) {
use_local_storage = bool;
if (bool) {
dom.bind(window, 'unload', saveToLocalStorage);
} else {
dom.unbind(window, 'unload', saveToLocalStorage);
}
localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
}
}
}
});
// Are we a root level GUI?
if (common.isUndefined(params.parent)) {
params.closed = false;
dom.addClass(this.domElement, GUI.CLASS_MAIN);
dom.makeSelectable(this.domElement, false);
// Are we supposed to be loading locally?
if (SUPPORTS_LOCAL_STORAGE) {
if (use_local_storage) {
_this.useLocalStorage = true;
var saved_gui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
if (saved_gui) {
params.load = JSON.parse(saved_gui);
}
}
}
this.__closeButton = document.createElement('div');
this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
this.domElement.appendChild(this.__closeButton);
dom.bind(this.__closeButton, 'click', function() {
_this.closed = !_this.closed;
});
// Oh, you're a nested GUI!
} else {
if (params.closed === undefined) {
params.closed = true;
}
var title_row_name = document.createTextNode(params.name);
dom.addClass(title_row_name, 'controller-name');
var title_row = addRow(_this, title_row_name);
var on_click_title = function(e) {
e.preventDefault();
_this.closed = !_this.closed;
return false;
};
dom.addClass(this.__ul, GUI.CLASS_CLOSED);
dom.addClass(title_row, 'title');
dom.bind(title_row, 'click', on_click_title);
if (!params.closed) {
this.closed = false;
}
}
if (params.autoPlace) {
if (common.isUndefined(params.parent)) {
if (auto_place_virgin) {
auto_place_container = document.createElement('div');
dom.addClass(auto_place_container, CSS_NAMESPACE);
dom.addClass(auto_place_container, GUI.CLASS_AUTO_PLACE_CONTAINER);
document.body.appendChild(auto_place_container);
auto_place_virgin = false;
}
// Put it in the dom for you.
auto_place_container.appendChild(this.domElement);
// Apply the auto styles
dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
}
// Make it not elastic.
if (!this.parent) setWidth(_this, params.width);
}
dom.bind(window, 'resize', function() { _this.onResize() });
dom.bind(this.__ul, 'webkitTransitionEnd', function() { _this.onResize(); });
dom.bind(this.__ul, 'transitionend', function() { _this.onResize() });
dom.bind(this.__ul, 'oTransitionEnd', function() { _this.onResize() });
this.onResize();
if (params.resizable) {
addResizeHandle(this);
}
function saveToLocalStorage() {
localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
}
var root = _this.getRoot();
function resetWidth() {
var root = _this.getRoot();
root.width += 1;
common.defer(function() {
root.width -= 1;
});
}
if (!params.parent) {
resetWidth();
}
};
GUI.toggleHide = function() {
hide = !hide;
common.each(hideable_guis, function(gui) {
gui.domElement.style.zIndex = hide ? -999 : 999;
gui.domElement.style.opacity = hide ? 0 : 1;
});
};
GUI.CLASS_AUTO_PLACE = 'a';
GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
GUI.CLASS_MAIN = 'main';
GUI.CLASS_CONTROLLER_ROW = 'cr';
GUI.CLASS_TOO_TALL = 'taller-than-window';
GUI.CLASS_CLOSED = 'closed';
GUI.CLASS_CLOSE_BUTTON = 'close-button';
GUI.CLASS_DRAG = 'drag';
GUI.DEFAULT_WIDTH = 245;
GUI.TEXT_CLOSED = 'Close Controls';
GUI.TEXT_OPEN = 'Open Controls';
dom.bind(window, 'keydown', function(e) {
if (document.activeElement.type !== 'text' &&
(e.which === HIDE_KEY_CODE || e.keyCode == HIDE_KEY_CODE)) {
GUI.toggleHide();
}
}, false);
common.extend(
GUI.prototype,
/** @lends dat.gui.GUI */
{
/**
* @param object
* @param property
* @returns {dat.controllers.Controller} The new controller that was added.
* @instance
*/
add: function(object, property) {
return add(
this,
object,
property,
{
factoryArgs: Array.prototype.slice.call(arguments, 2)
}
);
},
/**
* @param object
* @param property
* @returns {dat.controllers.ColorController} The new controller that was added.
* @instance
*/
addColor: function(object, property) {
return add(
this,
object,
property,
{
color: true
}
);
},
/**
* @param controller
* @instance
*/
remove: function(controller) {
// TODO listening?
this.__ul.removeChild(controller.__li);
this.__controllers.slice(this.__controllers.indexOf(controller), 1);
var _this = this;
common.defer(function() {
_this.onResize();
});
},
destroy: function() {
if (this.autoPlace) {
auto_place_container.removeChild(this.domElement);
}
},
/**
* @param name
* @returns {dat.gui.GUI} The new folder.
* @throws {Error} if this GUI already has a folder by the specified
* name
* @instance
*/
addFolder: function(name) {
// We have to prevent collisions on names in order to have a key
// by which to remember saved values
if (this.__folders[name] !== undefined) {
throw new Error('You already have a folder in this GUI by the' +
' name "' + name + '"');
}
var new_gui_params = { name: name, parent: this };
// We need to pass down the autoPlace trait so that we can
// attach event listeners to open/close folder actions to
// ensure that a scrollbar appears if the window is too short.
new_gui_params.autoPlace = this.autoPlace;
// Do we have saved appearance data for this folder?
if (this.load && // Anything loaded?
this.load.folders && // Was my parent a dead-end?
this.load.folders[name]) { // Did daddy remember me?
// Start me closed if I was closed
new_gui_params.closed = this.load.folders[name].closed;
// Pass down the loaded data
new_gui_params.load = this.load.folders[name];
}
var gui = new GUI(new_gui_params);
this.__folders[name] = gui;
var li = addRow(this, gui.domElement);
dom.addClass(li, 'folder');
return gui;
},
open: function() {
this.closed = false;
},
close: function() {
this.closed = true;
},
onResize: function() {
var root = this.getRoot();
if (root.scrollable) {
var top = dom.getOffset(root.__ul).top;
var h = 0;
common.each(root.__ul.childNodes, function(node) {
if (! (root.autoPlace && node === root.__save_row))
h += dom.getHeight(node);
});
if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
} else {
dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
root.__ul.style.height = 'auto';
}
}
if (root.__resize_handle) {
common.defer(function() {
root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
});
}
if (root.__closeButton) {
root.__closeButton.style.width = root.width + 'px';
}
},
/**
* Mark objects for saving. The order of these objects cannot change as
* the GUI grows. When remembering new objects, append them to the end
* of the list.
*
* @param {Object...} objects
* @throws {Error} if not called on a top level GUI.
* @instance
*/
remember: function() {
if (common.isUndefined(SAVE_DIALOGUE)) {
SAVE_DIALOGUE = new CenteredDiv();
SAVE_DIALOGUE.domElement.innerHTML = saveDialogueContents;
}
if (this.parent) {
throw new Error("You can only call remember on a top level GUI.");
}
var _this = this;
common.each(Array.prototype.slice.call(arguments), function(object) {
if (_this.__rememberedObjects.length == 0) {
addSaveMenu(_this);
}
if (_this.__rememberedObjects.indexOf(object) == -1) {
_this.__rememberedObjects.push(object);
}
});
if (this.autoPlace) {
// Set save row width
setWidth(this, this.width);
}
},
/**
* @returns {dat.gui.GUI} the topmost parent GUI of a nested GUI.
* @instance
*/
getRoot: function() {
var gui = this;
while (gui.parent) {
gui = gui.parent;
}
return gui;
},
/**
* @returns {Object} a JSON object representing the current state of
* this GUI as well as its remembered properties.
* @instance
*/
getSaveObject: function() {
var toReturn = this.load;
toReturn.closed = this.closed;
// Am I remembering any values?
if (this.__rememberedObjects.length > 0) {
toReturn.preset = this.preset;
if (!toReturn.remembered) {
toReturn.remembered = {};
}
toReturn.remembered[this.preset] = getCurrentPreset(this);
}
toReturn.folders = {};
common.each(this.__folders, function(element, key) {
toReturn.folders[key] = element.getSaveObject();
});
return toReturn;
},
save: function() {
if (!this.load.remembered) {
this.load.remembered = {};
}
this.load.remembered[this.preset] = getCurrentPreset(this);
markPresetModified(this, false);
},
saveAs: function(presetName) {
if (!this.load.remembered) {
// Retain default values upon first save
this.load.remembered = {};
this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
}
this.load.remembered[presetName] = getCurrentPreset(this);
this.preset = presetName;
addPresetOption(this, presetName, true);
},
revert: function(gui) {
common.each(this.__controllers, function(controller) {
// Make revert work on Default.
if (!this.getRoot().load.remembered) {
controller.setValue(controller.initialValue);
} else {
recallSavedValue(gui || this.getRoot(), controller);
}
}, this);
common.each(this.__folders, function(folder) {
folder.revert(folder);
});
if (!gui) {
markPresetModified(this.getRoot(), false);
}
},
listen: function(controller) {
var init = this.__listening.length == 0;
this.__listening.push(controller);
if (init) updateDisplays(this.__listening);
}
}
);
function add(gui, object, property, params) {
if (object[property] === undefined) {
throw new Error("Object " + object + " has no property \"" + property + "\"");
}
var controller;
if (params.color) {
controller = new ColorController(object, property);
} else {
var factoryArgs = [object,property].concat(params.factoryArgs);
controller = controllerFactory.apply(gui, factoryArgs);
}
if (params.before instanceof Controller) {
params.before = params.before.__li;
}
recallSavedValue(gui, controller);
dom.addClass(controller.domElement, 'c');
var name = document.createElement('span');
dom.addClass(name, 'property-name');
name.innerHTML = controller.property;
var container = document.createElement('div');
container.appendChild(name);
container.appendChild(controller.domElement);
var li = addRow(gui, container, params.before);
dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
dom.addClass(li, typeof controller.getValue());
augmentController(gui, li, controller);
gui.__controllers.push(controller);
return controller;
}
/**
* Add a row to the end of the GUI or before another row.
*
* @param gui
* @param [dom] If specified, inserts the dom content in the new row
* @param [liBefore] If specified, places the new row before another row
*/
function addRow(gui, dom, liBefore) {
var li = document.createElement('li');
if (dom) li.appendChild(dom);
if (liBefore) {
gui.__ul.insertBefore(li, params.before);
} else {
gui.__ul.appendChild(li);
}
gui.onResize();
return li;
}
function augmentController(gui, li, controller) {
controller.__li = li;
controller.__gui = gui;
common.extend(controller, {
options: function(options) {
if (arguments.length > 1) {
controller.remove();
return add(
gui,
controller.object,
controller.property,
{
before: controller.__li.nextElementSibling,
factoryArgs: [common.toArray(arguments)]
}
);
}
if (common.isArray(options) || common.isObject(options)) {
controller.remove();
return add(
gui,
controller.object,
controller.property,
{
before: controller.__li.nextElementSibling,
factoryArgs: [options]
}
);
}
},
name: function(v) {
controller.__li.firstElementChild.firstElementChild.innerHTML = v;
return controller;
},
listen: function() {
controller.__gui.listen(controller);
return controller;
},
remove: function() {
controller.__gui.remove(controller);
return controller;
}
});
// All sliders should be accompanied by a box.
if (controller instanceof NumberControllerSlider) {
var box = new NumberControllerBox(controller.object, controller.property,
{ min: controller.__min, max: controller.__max, step: controller.__step });
common.each(['updateDisplay', 'onChange', 'onFinishChange'], function(method) {
var pc = controller[method];
var pb = box[method];
controller[method] = box[method] = function() {
var args = Array.prototype.slice.call(arguments);
pc.apply(controller, args);
return pb.apply(box, args);
}
});
dom.addClass(li, 'has-slider');
controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
}
else if (controller instanceof NumberControllerBox) {
var r = function(returned) {
// Have we defined both boundaries?
if (common.isNumber(controller.__min) && common.isNumber(controller.__max)) {
// Well, then lets just replace this with a slider.
controller.remove();
return add(
gui,
controller.object,
controller.property,
{
before: controller.__li.nextElementSibling,
factoryArgs: [controller.__min, controller.__max, controller.__step]
});
}
return returned;
};
controller.min = common.compose(r, controller.min);
controller.max = common.compose(r, controller.max);
}
else if (controller instanceof BooleanController) {
dom.bind(li, 'click', function() {
dom.fakeEvent(controller.__checkbox, 'click');
});
dom.bind(controller.__checkbox, 'click', function(e) {
e.stopPropagation(); // Prevents double-toggle
})
}
else if (controller instanceof FunctionController) {
dom.bind(li, 'click', function() {
dom.fakeEvent(controller.__button, 'click');
});
dom.bind(li, 'mouseover', function() {
dom.addClass(controller.__button, 'hover');
});
dom.bind(li, 'mouseout', function() {
dom.removeClass(controller.__button, 'hover');
});
}
else if (controller instanceof ColorController) {
dom.addClass(li, 'color');
controller.updateDisplay = common.compose(function(r) {
li.style.borderLeftColor = controller.__color.toString();
return r;
}, controller.updateDisplay);
controller.updateDisplay();
}
controller.setValue = common.compose(function(r) {
if (gui.getRoot().__preset_select && controller.isModified()) {
markPresetModified(gui.getRoot(), true);
}
return r;
}, controller.setValue);
}
function recallSavedValue(gui, controller) {
// Find the topmost GUI, that's where remembered objects live.
var root = gui.getRoot();
// Does the object we're controlling match anything we've been told to
// remember?
var matched_index = root.__rememberedObjects.indexOf(controller.object);
// Why yes, it does!
if (matched_index != -1) {
// Let me fetch a map of controllers for thcommon.isObject.
var controller_map =
root.__rememberedObjectIndecesToControllers[matched_index];
// Ohp, I believe this is the first controller we've created for this
// object. Lets make the map fresh.
if (controller_map === undefined) {
controller_map = {};
root.__rememberedObjectIndecesToControllers[matched_index] =
controller_map;
}
// Keep track of this controller
controller_map[controller.property] = controller;
// Okay, now have we saved any values for this controller?
if (root.load && root.load.remembered) {
var preset_map = root.load.remembered;
// Which preset are we trying to load?
var preset;
if (preset_map[gui.preset]) {
preset = preset_map[gui.preset];
} else if (preset_map[DEFAULT_DEFAULT_PRESET_NAME]) {
// Uhh, you can have the default instead?
preset = preset_map[DEFAULT_DEFAULT_PRESET_NAME];
} else {
// Nada.
return;
}
// Did the loaded object remember thcommon.isObject?
if (preset[matched_index] &&
// Did we remember this particular property?
preset[matched_index][controller.property] !== undefined) {
// We did remember something for this guy ...
var value = preset[matched_index][controller.property];
// And that's what it is.
controller.initialValue = value;
controller.setValue(value);
}
}
}
}
function getLocalStorageHash(gui, key) {
// TODO how does this deal with multiple GUI's?
return document.location.href + '.' + key;
}
function addSaveMenu(gui) {
var div = gui.__save_row = document.createElement('li');
dom.addClass(gui.domElement, 'has-save');
gui.__ul.insertBefore(div, gui.__ul.firstChild);
dom.addClass(div, 'save-row');
var gears = document.createElement('span');
gears.innerHTML = '&nbsp;';
dom.addClass(gears, 'button gears');
// TODO replace with FunctionController
var button = document.createElement('span');
button.innerHTML = 'Save';
dom.addClass(button, 'button');
dom.addClass(button, 'save');
var button2 = document.createElement('span');
button2.innerHTML = 'New';
dom.addClass(button2, 'button');
dom.addClass(button2, 'save-as');
var button3 = document.createElement('span');
button3.innerHTML = 'Revert';
dom.addClass(button3, 'button');
dom.addClass(button3, 'revert');
var select = gui.__preset_select = document.createElement('select');
if (gui.load && gui.load.remembered) {
common.each(gui.load.remembered, function(value, key) {
addPresetOption(gui, key, key == gui.preset);
});
} else {
addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
}
dom.bind(select, 'change', function() {
for (var index = 0; index < gui.__preset_select.length; index++) {
gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
}
gui.preset = this.value;
});
div.appendChild(select);
div.appendChild(gears);
div.appendChild(button);
div.appendChild(button2);
div.appendChild(button3);
if (SUPPORTS_LOCAL_STORAGE) {
var saveLocally = document.getElementById('dg-save-locally');
var explain = document.getElementById('dg-local-explain');
saveLocally.style.display = 'block';
var localStorageCheckBox = document.getElementById('dg-local-storage');
if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
localStorageCheckBox.setAttribute('checked', 'checked');
}
function showHideExplain() {
explain.style.display = gui.useLocalStorage ? 'block' : 'none';
}
showHideExplain();
// TODO: Use a boolean controller, fool!
dom.bind(localStorageCheckBox, 'change', function() {
gui.useLocalStorage = !gui.useLocalStorage;
showHideExplain();
});
}
var newConstructorTextArea = document.getElementById('dg-new-constructor');
dom.bind(newConstructorTextArea, 'keydown', function(e) {
if (e.metaKey && (e.which === 67 || e.keyCode == 67)) {
SAVE_DIALOGUE.hide();
}
});
dom.bind(gears, 'click', function() {
newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
SAVE_DIALOGUE.show();
newConstructorTextArea.focus();
newConstructorTextArea.select();
});
dom.bind(button, 'click', function() {
gui.save();
});
dom.bind(button2, 'click', function() {
var presetName = prompt('Enter a new preset name.');
if (presetName) gui.saveAs(presetName);
});
dom.bind(button3, 'click', function() {
gui.revert();
});
// div.appendChild(button2);
}
function addResizeHandle(gui) {
gui.__resize_handle = document.createElement('div');
common.extend(gui.__resize_handle.style, {
width: '6px',
marginLeft: '-3px',
height: '200px',
cursor: 'ew-resize',
position: 'absolute'
// border: '1px solid blue'
});
var pmouseX;
dom.bind(gui.__resize_handle, 'mousedown', dragStart);
dom.bind(gui.__closeButton, 'mousedown', dragStart);
gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
function dragStart(e) {
e.preventDefault();
pmouseX = e.clientX;
dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
dom.bind(window, 'mousemove', drag);
dom.bind(window, 'mouseup', dragStop);
return false;
}
function drag(e) {
e.preventDefault();
gui.width += pmouseX - e.clientX;
gui.onResize();
pmouseX = e.clientX;
return false;
}
function dragStop() {
dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
dom.unbind(window, 'mousemove', drag);
dom.unbind(window, 'mouseup', dragStop);
}
}
function setWidth(gui, w) {
gui.domElement.style.width = w + 'px';
// Auto placed save-rows are position fixed, so we have to
// set the width manually if we want it to bleed to the edge
if (gui.__save_row && gui.autoPlace) {
gui.__save_row.style.width = w + 'px';
}if (gui.__closeButton) {
gui.__closeButton.style.width = w + 'px';
}
}
function getCurrentPreset(gui, useInitialValues) {
var toReturn = {};
// For each object I'm remembering
common.each(gui.__rememberedObjects, function(val, index) {
var saved_values = {};
// The controllers I've made for thcommon.isObject by property
var controller_map =
gui.__rememberedObjectIndecesToControllers[index];
// Remember each value for each property
common.each(controller_map, function(controller, property) {
saved_values[property] = useInitialValues ? controller.initialValue : controller.getValue();
});
// Save the values for thcommon.isObject
toReturn[index] = saved_values;
});
return toReturn;
}
function addPresetOption(gui, name, setSelected) {
var opt = document.createElement('option');
opt.innerHTML = name;
opt.value = name;
gui.__preset_select.appendChild(opt);
if (setSelected) {
gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
}
}
function setPresetSelectIndex(gui) {
for (var index = 0; index < gui.__preset_select.length; index++) {
if (gui.__preset_select[index].value == gui.preset) {
gui.__preset_select.selectedIndex = index;
}
}
}
function markPresetModified(gui, modified) {
var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
// console.log('mark', modified, opt);
if (modified) {
opt.innerHTML = opt.value + "*";
} else {
opt.innerHTML = opt.value;
}
}
function updateDisplays(controllerArray) {
if (controllerArray.length != 0) {
requestAnimationFrame(function() {
updateDisplays(controllerArray);
});
}
common.each(controllerArray, function(c) {
c.updateDisplay();
});
}
return GUI;
})(dat.utils.css,
"<div id=\"dg-save\" class=\"dg dialogue\">\n\n Here's the new load parameter for your <code>GUI</code>'s constructor:\n\n <textarea id=\"dg-new-constructor\"></textarea>\n\n <div id=\"dg-save-locally\">\n\n <input id=\"dg-local-storage\" type=\"checkbox\"/> Automatically save\n values to <code>localStorage</code> on exit.\n\n <div id=\"dg-local-explain\">The values saved to <code>localStorage</code> will\n override those passed to <code>dat.GUI</code>'s constructor. This makes it\n easier to work incrementally, but <code>localStorage</code> is fragile,\n and your friends may not see the same values you do.\n \n </div>\n \n </div>\n\n</div>",
".dg ul{list-style:none;margin:0;padding:0;width:100%;clear:both}.dg.ac{position:fixed;top:0;left:0;right:0;height:0;z-index:0}.dg:not(.ac) .main{overflow:hidden}.dg.main{-webkit-transition:opacity 0.1s linear;-o-transition:opacity 0.1s linear;-moz-transition:opacity 0.1s linear;transition:opacity 0.1s linear}.dg.main.taller-than-window{overflow-y:auto}.dg.main.taller-than-window .close-button{opacity:1;margin-top:-1px;border-top:1px solid #2c2c2c}.dg.main ul.closed .close-button{opacity:1 !important}.dg.main:hover .close-button,.dg.main .close-button.drag{opacity:1}.dg.main .close-button{-webkit-transition:opacity 0.1s linear;-o-transition:opacity 0.1s linear;-moz-transition:opacity 0.1s linear;transition:opacity 0.1s linear;border:0;position:absolute;line-height:19px;height:20px;cursor:pointer;text-align:center;background-color:#000}.dg.main .close-button:hover{background-color:#111}.dg.a{float:right;margin-right:15px;overflow-x:hidden}.dg.a.has-save ul{margin-top:27px}.dg.a.has-save ul.closed{margin-top:0}.dg.a .save-row{position:fixed;top:0;z-index:1002}.dg li{-webkit-transition:height 0.1s ease-out;-o-transition:height 0.1s ease-out;-moz-transition:height 0.1s ease-out;transition:height 0.1s ease-out}.dg li:not(.folder){cursor:auto;height:27px;line-height:27px;overflow:hidden;padding:0 4px 0 5px}.dg li.folder{padding:0;border-left:4px solid rgba(0,0,0,0)}.dg li.title{cursor:pointer;margin-left:-4px}.dg .closed li:not(.title),.dg .closed ul li,.dg .closed ul li > *{height:0;overflow:hidden;border:0}.dg .cr{clear:both;padding-left:3px;height:27px}.dg .property-name{cursor:default;float:left;clear:left;width:40%;overflow:hidden;text-overflow:ellipsis}.dg .c{float:left;width:60%}.dg .c input[type=text]{border:0;margin-top:4px;padding:3px;width:100%;float:right}.dg .has-slider input[type=text]{width:30%;margin-left:0}.dg .slider{float:left;width:66%;margin-left:-5px;margin-right:0;height:19px;margin-top:4px}.dg .slider-fg{height:100%}.dg .c input[type=checkbox]{margin-top:9px}.dg .c select{margin-top:5px}.dg .cr.function,.dg .cr.function .property-name,.dg .cr.function *,.dg .cr.boolean,.dg .cr.boolean *{cursor:pointer}.dg .selector{display:none;position:absolute;margin-left:-9px;margin-top:23px;z-index:10}.dg .c:hover .selector,.dg .selector.drag{display:block}.dg li.save-row{padding:0}.dg li.save-row .button{display:inline-block;padding:0px 6px}.dg.dialogue{background-color:#222;width:460px;padding:15px;font-size:13px;line-height:15px}#dg-new-constructor{padding:10px;color:#222;font-family:Monaco, monospace;font-size:10px;border:0;resize:none;box-shadow:inset 1px 1px 1px #888;word-wrap:break-word;margin:12px 0;display:block;width:440px;overflow-y:scroll;height:100px;position:relative}#dg-local-explain{display:none;font-size:11px;line-height:17px;border-radius:3px;background-color:#333;padding:8px;margin-top:10px}#dg-local-explain code{font-size:10px}#dat-gui-save-locally{display:none}.dg{color:#eee;font:11px 'Lucida Grande', sans-serif;text-shadow:0 -1px 0 #111}.dg.main::-webkit-scrollbar{width:5px;background:#1a1a1a}.dg.main::-webkit-scrollbar-corner{height:0;display:none}.dg.main::-webkit-scrollbar-thumb{border-radius:5px;background:#676767}.dg li:not(.folder){background:#1a1a1a;border-bottom:1px solid #2c2c2c}.dg li.save-row{line-height:25px;background:#dad5cb;border:0}.dg li.save-row select{margin-left:5px;width:108px}.dg li.save-row .button{margin-left:5px;margin-top:1px;border-radius:2px;font-size:9px;line-height:7px;padding:4px 4px 5px 4px;background:#c5bdad;color:#fff;text-shadow:0 1px 0 #b0a58f;box-shadow:0 -1px 0 #b0a58f;cursor:pointer}.dg li.save-row .button.gears{background:#c5bdad url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAANCAYAAAB/9ZQ7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQJJREFUeNpiYKAU/P//PwGIC/ApCABiBSAW+I8AClAcgKxQ4T9hoMAEUrxx2QSGN6+egDX+/vWT4e7N82AMYoPAx/evwWoYoSYbACX2s7KxCxzcsezDh3evFoDEBYTEEqycggWAzA9AuUSQQgeYPa9fPv6/YWm/Acx5IPb7ty/fw+QZblw67vDs8R0YHyQhgObx+yAJkBqmG5dPPDh1aPOGR/eugW0G4vlIoTIfyFcA+QekhhHJhPdQxbiAIguMBTQZrPD7108M6roWYDFQiIAAv6Aow/1bFwXgis+f2LUAynwoIaNcz8XNx3Dl7MEJUDGQpx9gtQ8YCueB+D26OECAAQDadt7e46D42QAAAABJRU5ErkJggg==) 2px 1px no-repeat;height:7px;width:8px}.dg li.save-row .button:hover{background-color:#bab19e;box-shadow:0 -1px 0 #b0a58f}.dg li.folder{border-bottom:0}.dg li.title{padding-left:16px;background:#000 url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlI+hKgFxoCgAOw==) 6px 10px no-repeat;cursor:pointer;border-bottom:1px solid rgba(255,255,255,0.2)}.dg .closed li.title{background-image:url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlGIWqMCbWAEAOw==)}.dg .cr.boolean{border-left:3px solid #806787}.dg .cr.function{border-left:3px solid #e61d5f}.dg .cr.number{border-left:3px solid #2fa1d6}.dg .cr.number input[type=text]{color:#2fa1d6}.dg .cr.string{border-left:3px solid #1ed36f}.dg .cr.string input[type=text]{color:#1ed36f}.dg .cr.function:hover,.dg .cr.boolean:hover{background:#111}.dg .c input[type=text]{background:#303030;outline:none}.dg .c input[type=text]:hover{background:#3c3c3c}.dg .c input[type=text]:focus{background:#494949;color:#fff}.dg .c .slider{background:#303030;cursor:ew-resize}.dg .c .slider-fg{background:#2fa1d6}.dg .c .slider:hover{background:#3c3c3c}.dg .c .slider:hover .slider-fg{background:#44abda}\n",
dat.controllers.factory = (function (OptionController, NumberControllerBox, NumberControllerSlider, StringController, FunctionController, BooleanController, common) {
return function(object, property) {
var initialValue = object[property];
// Providing options?
if (common.isArray(arguments[2]) || common.isObject(arguments[2])) {
return new OptionController(object, property, arguments[2]);
}
// Providing a map?
if (common.isNumber(initialValue)) {
if (common.isNumber(arguments[2]) && common.isNumber(arguments[3])) {
// Has min and max.
return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
} else {
return new NumberControllerBox(object, property, { min: arguments[2], max: arguments[3] });
}
}
if (common.isString(initialValue)) {
return new StringController(object, property);
}
if (common.isFunction(initialValue)) {
return new FunctionController(object, property, '');
}
if (common.isBoolean(initialValue)) {
return new BooleanController(object, property);
}
}
})(dat.controllers.OptionController,
dat.controllers.NumberControllerBox,
dat.controllers.NumberControllerSlider,
dat.controllers.StringController = (function (Controller, dom, common) {
/**
* @class Provides a text input to alter the string property of an object.
*
* @extends dat.controllers.Controller
*
* @param {Object} object The object to be manipulated
* @param {string} property The name of the property to be manipulated
*
* @member dat.controllers
*/
var StringController = function(object, property) {
StringController.superclass.call(this, object, property);
var _this = this;
this.__input = document.createElement('input');
this.__input.setAttribute('type', 'text');
dom.bind(this.__input, 'keyup', onChange);
dom.bind(this.__input, 'change', onChange);
dom.bind(this.__input, 'blur', onBlur);
dom.bind(this.__input, 'keydown', function(e) {
if (e.keyCode === 13) {
this.blur();
}
});
function onChange() {
_this.setValue(_this.__input.value);
}
function onBlur() {
if (_this.__onFinishChange) {
_this.__onFinishChange.call(_this, _this.getValue());
}
}
this.updateDisplay();
this.domElement.appendChild(this.__input);
};
StringController.superclass = Controller;
common.extend(
StringController.prototype,
Controller.prototype,
{
updateDisplay: function() {
// Stops the caret from moving on account of:
// keyup -> setValue -> updateDisplay
if (!dom.isActive(this.__input)) {
this.__input.value = this.getValue();
}
return StringController.superclass.prototype.updateDisplay.call(this);
}
}
);
return StringController;
})(dat.controllers.Controller,
dat.dom.dom,
dat.utils.common),
dat.controllers.FunctionController,
dat.controllers.BooleanController,
dat.utils.common),
dat.controllers.Controller,
dat.controllers.BooleanController,
dat.controllers.FunctionController,
dat.controllers.NumberControllerBox,
dat.controllers.NumberControllerSlider,
dat.controllers.OptionController,
dat.controllers.ColorController = (function (Controller, dom, Color, interpret, common) {
var ColorController = function(object, property) {
ColorController.superclass.call(this, object, property);
this.__color = new Color(this.getValue());
this.__temp = new Color(0);
var _this = this;
this.domElement = document.createElement('div');
dom.makeSelectable(this.domElement, false);
this.__selector = document.createElement('div');
this.__selector.className = 'selector';
this.__saturation_field = document.createElement('div');
this.__saturation_field.className = 'saturation-field';
this.__field_knob = document.createElement('div');
this.__field_knob.className = 'field-knob';
this.__field_knob_border = '2px solid ';
this.__hue_knob = document.createElement('div');
this.__hue_knob.className = 'hue-knob';
this.__hue_field = document.createElement('div');
this.__hue_field.className = 'hue-field';
this.__input = document.createElement('input');
this.__input.type = 'text';
this.__input_textShadow = '0 1px 1px ';
dom.bind(this.__input, 'keydown', function(e) {
if (e.keyCode === 13) { // on enter
onBlur.call(this);
}
});
dom.bind(this.__input, 'blur', onBlur);
dom.bind(this.__selector, 'mousedown', function(e) {
dom
.addClass(this, 'drag')
.bind(window, 'mouseup', function(e) {
dom.removeClass(_this.__selector, 'drag');
});
});
var value_field = document.createElement('div');
common.extend(this.__selector.style, {
width: '122px',
height: '102px',
padding: '3px',
backgroundColor: '#222',
boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
});
common.extend(this.__field_knob.style, {
position: 'absolute',
width: '12px',
height: '12px',
border: this.__field_knob_border + (this.__color.v < .5 ? '#fff' : '#000'),
boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
borderRadius: '12px',
zIndex: 1
});
common.extend(this.__hue_knob.style, {
position: 'absolute',
width: '15px',
height: '2px',
borderRight: '4px solid #fff',
zIndex: 1
});
common.extend(this.__saturation_field.style, {
width: '100px',
height: '100px',
border: '1px solid #555',
marginRight: '3px',
display: 'inline-block',
cursor: 'pointer'
});
common.extend(value_field.style, {
width: '100%',
height: '100%',
background: 'none'
});
linearGradient(value_field, 'top', 'rgba(0,0,0,0)', '#000');
common.extend(this.__hue_field.style, {
width: '15px',
height: '100px',
display: 'inline-block',
border: '1px solid #555',
cursor: 'ns-resize'
});
hueGradient(this.__hue_field);
common.extend(this.__input.style, {
outline: 'none',
// width: '120px',
textAlign: 'center',
// padding: '4px',
// marginBottom: '6px',
color: '#fff',
border: 0,
fontWeight: 'bold',
textShadow: this.__input_textShadow + 'rgba(0,0,0,0.7)'
});
dom.bind(this.__saturation_field, 'mousedown', fieldDown);
dom.bind(this.__field_knob, 'mousedown', fieldDown);
dom.bind(this.__hue_field, 'mousedown', function(e) {
setH(e);
dom.bind(window, 'mousemove', setH);
dom.bind(window, 'mouseup', unbindH);
});
function fieldDown(e) {
setSV(e);
// document.body.style.cursor = 'none';
dom.bind(window, 'mousemove', setSV);
dom.bind(window, 'mouseup', unbindSV);
}
function unbindSV() {
dom.unbind(window, 'mousemove', setSV);
dom.unbind(window, 'mouseup', unbindSV);
// document.body.style.cursor = 'default';
}
function onBlur() {
var i = interpret(this.value);
if (i !== false) {
_this.__color.__state = i;
_this.setValue(_this.__color.toOriginal());
} else {
this.value = _this.__color.toString();
}
}
function unbindH() {
dom.unbind(window, 'mousemove', setH);
dom.unbind(window, 'mouseup', unbindH);
}
this.__saturation_field.appendChild(value_field);
this.__selector.appendChild(this.__field_knob);
this.__selector.appendChild(this.__saturation_field);
this.__selector.appendChild(this.__hue_field);
this.__hue_field.appendChild(this.__hue_knob);
this.domElement.appendChild(this.__input);
this.domElement.appendChild(this.__selector);
this.updateDisplay();
function setSV(e) {
e.preventDefault();
var w = dom.getWidth(_this.__saturation_field);
var o = dom.getOffset(_this.__saturation_field);
var s = (e.clientX - o.left + document.body.scrollLeft) / w;
var v = 1 - (e.clientY - o.top + document.body.scrollTop) / w;
if (v > 1) v = 1;
else if (v < 0) v = 0;
if (s > 1) s = 1;
else if (s < 0) s = 0;
_this.__color.v = v;
_this.__color.s = s;
_this.setValue(_this.__color.toOriginal());
return false;
}
function setH(e) {
e.preventDefault();
var s = dom.getHeight(_this.__hue_field);
var o = dom.getOffset(_this.__hue_field);
var h = 1 - (e.clientY - o.top + document.body.scrollTop) / s;
if (h > 1) h = 1;
else if (h < 0) h = 0;
_this.__color.h = h * 360;
_this.setValue(_this.__color.toOriginal());
return false;
}
};
ColorController.superclass = Controller;
common.extend(
ColorController.prototype,
Controller.prototype,
{
updateDisplay: function() {
var i = interpret(this.getValue());
if (i !== false) {
var mismatch = false;
// Check for mismatch on the interpreted value.
common.each(Color.COMPONENTS, function(component) {
if (!common.isUndefined(i[component]) &&
!common.isUndefined(this.__color.__state[component]) &&
i[component] !== this.__color.__state[component]) {
mismatch = true;
return {}; // break
}
}, this);
// If nothing diverges, we keep our previous values
// for statefulness, otherwise we recalculate fresh
if (mismatch) {
common.extend(this.__color.__state, i);
}
}
common.extend(this.__temp.__state, this.__color.__state);
this.__temp.a = 1;
var flip = (this.__color.v < .5 || this.__color.s > .5) ? 255 : 0;
var _flip = 255 - flip;
common.extend(this.__field_knob.style, {
marginLeft: 100 * this.__color.s - 7 + 'px',
marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
backgroundColor: this.__temp.toString(),
border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip +')'
});
this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px'
this.__temp.s = 1;
this.__temp.v = 1;
linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toString());
common.extend(this.__input.style, {
backgroundColor: this.__input.value = this.__color.toString(),
color: 'rgb(' + flip + ',' + flip + ',' + flip +')',
textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip +',.7)'
});
}
}
);
var vendors = ['-moz-','-o-','-webkit-','-ms-',''];
function linearGradient(elem, x, a, b) {
elem.style.background = '';
common.each(vendors, function(vendor) {
elem.style.cssText += 'background: ' + vendor + 'linear-gradient('+x+', '+a+' 0%, ' + b + ' 100%); ';
});
}
function hueGradient(elem) {
elem.style.background = '';
elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);'
elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'
elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'
elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'
elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'
}
return ColorController;
})(dat.controllers.Controller,
dat.dom.dom,
dat.color.Color = (function (interpret, math, toString, common) {
var Color = function() {
this.__state = interpret.apply(this, arguments);
if (this.__state === false) {
throw 'Failed to interpret color arguments';
}
this.__state.a = this.__state.a || 1;
};
Color.COMPONENTS = ['r','g','b','h','s','v','hex','a'];
common.extend(Color.prototype, {
toString: function() {
return toString(this);
},
toOriginal: function() {
return this.__state.conversion.write(this);
}
});
defineRGBComponent(Color.prototype, 'r', 2);
defineRGBComponent(Color.prototype, 'g', 1);
defineRGBComponent(Color.prototype, 'b', 0);
defineHSVComponent(Color.prototype, 'h');
defineHSVComponent(Color.prototype, 's');
defineHSVComponent(Color.prototype, 'v');
Object.defineProperty(Color.prototype, 'a', {
get: function() {
return this.__state.a;
},
set: function(v) {
this.__state.a = v;
}
});
Object.defineProperty(Color.prototype, 'hex', {
get: function() {
if (!this.__state.space !== 'HEX') {
this.__state.hex = math.rgb_to_hex(this.r, this.g, this.b);
}
return this.__state.hex;
},
set: function(v) {
this.__state.space = 'HEX';
this.__state.hex = v;
}
});
function defineRGBComponent(target, component, componentHexIndex) {
Object.defineProperty(target, component, {
get: function() {
if (this.__state.space === 'RGB') {
return this.__state[component];
}
recalculateRGB(this, component, componentHexIndex);
return this.__state[component];
},
set: function(v) {
if (this.__state.space !== 'RGB') {
recalculateRGB(this, component, componentHexIndex);
this.__state.space = 'RGB';
}
this.__state[component] = v;
}
});
}
function defineHSVComponent(target, component) {
Object.defineProperty(target, component, {
get: function() {
if (this.__state.space === 'HSV')
return this.__state[component];
recalculateHSV(this);
return this.__state[component];
},
set: function(v) {
if (this.__state.space !== 'HSV') {
recalculateHSV(this);
this.__state.space = 'HSV';
}
this.__state[component] = v;
}
});
}
function recalculateRGB(color, component, componentHexIndex) {
if (color.__state.space === 'HEX') {
color.__state[component] = math.component_from_hex(color.__state.hex, componentHexIndex);
} else if (color.__state.space === 'HSV') {
common.extend(color.__state, math.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
} else {
throw 'Corrupted color state';
}
}
function recalculateHSV(color) {
var result = math.rgb_to_hsv(color.r, color.g, color.b);
common.extend(color.__state,
{
s: result.s,
v: result.v
}
);
if (!common.isNaN(result.h)) {
color.__state.h = result.h;
} else if (common.isUndefined(color.__state.h)) {
color.__state.h = 0;
}
}
return Color;
})(dat.color.interpret,
dat.color.math = (function () {
var tmpComponent;
return {
hsv_to_rgb: function(h, s, v) {
var hi = Math.floor(h / 60) % 6;
var f = h / 60 - Math.floor(h / 60);
var p = v * (1.0 - s);
var q = v * (1.0 - (f * s));
var t = v * (1.0 - ((1.0 - f) * s));
var c = [
[v, t, p],
[q, v, p],
[p, v, t],
[p, q, v],
[t, p, v],
[v, p, q]
][hi];
return {
r: c[0] * 255,
g: c[1] * 255,
b: c[2] * 255
};
},
rgb_to_hsv: function(r, g, b) {
var min = Math.min(r, g, b),
max = Math.max(r, g, b),
delta = max - min,
h, s;
if (max != 0) {
s = delta / max;
} else {
return {
h: NaN,
s: 0,
v: 0
};
}
if (r == max) {
h = (g - b) / delta;
} else if (g == max) {
h = 2 + (b - r) / delta;
} else {
h = 4 + (r - g) / delta;
}
h /= 6;
if (h < 0) {
h += 1;
}
return {
h: h * 360,
s: s,
v: max / 255
};
},
rgb_to_hex: function(r, g, b) {
var hex = this.hex_with_component(0, 2, r);
hex = this.hex_with_component(hex, 1, g);
hex = this.hex_with_component(hex, 0, b);
return hex;
},
component_from_hex: function(hex, componentIndex) {
return (hex >> (componentIndex * 8)) & 0xFF;
},
hex_with_component: function(hex, componentIndex, value) {
return value << (tmpComponent = componentIndex * 8) | (hex & ~ (0xFF << tmpComponent));
}
}
})(),
dat.color.toString,
dat.utils.common),
dat.color.interpret,
dat.utils.common),
dat.utils.requestAnimationFrame = (function () {
/**
* requirejs version of Paul Irish's RequestAnimationFrame
* http://paulirish.com/2011/requestanimationframe-for-smart-animating/
*/
return window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback, element) {
window.setTimeout(callback, 1000 / 60);
};
})(),
dat.dom.CenteredDiv = (function (dom, common) {
var CenteredDiv = function() {
this.backgroundElement = document.createElement('div');
common.extend(this.backgroundElement.style, {
backgroundColor: 'rgba(0,0,0,0.8)',
top: 0,
left: 0,
display: 'none',
zIndex: '1000',
opacity: 0,
WebkitTransition: 'opacity 0.2s linear'
});
dom.makeFullscreen(this.backgroundElement);
this.backgroundElement.style.position = 'fixed';
this.domElement = document.createElement('div');
common.extend(this.domElement.style, {
position: 'fixed',
display: 'none',
zIndex: '1001',
opacity: 0,
WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear'
});
document.body.appendChild(this.backgroundElement);
document.body.appendChild(this.domElement);
var _this = this;
dom.bind(this.backgroundElement, 'click', function() {
_this.hide();
});
};
CenteredDiv.prototype.show = function() {
var _this = this;
this.backgroundElement.style.display = 'block';
this.domElement.style.display = 'block';
this.domElement.style.opacity = 0;
// this.domElement.style.top = '52%';
this.domElement.style.webkitTransform = 'scale(1.1)';
this.layout();
common.defer(function() {
_this.backgroundElement.style.opacity = 1;
_this.domElement.style.opacity = 1;
_this.domElement.style.webkitTransform = 'scale(1)';
});
};
CenteredDiv.prototype.hide = function() {
var _this = this;
var hide = function() {
_this.domElement.style.display = 'none';
_this.backgroundElement.style.display = 'none';
dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
dom.unbind(_this.domElement, 'transitionend', hide);
dom.unbind(_this.domElement, 'oTransitionEnd', hide);
};
dom.bind(this.domElement, 'webkitTransitionEnd', hide);
dom.bind(this.domElement, 'transitionend', hide);
dom.bind(this.domElement, 'oTransitionEnd', hide);
this.backgroundElement.style.opacity = 0;
// this.domElement.style.top = '48%';
this.domElement.style.opacity = 0;
this.domElement.style.webkitTransform = 'scale(1.1)';
};
CenteredDiv.prototype.layout = function() {
this.domElement.style.left = window.innerWidth/2 - dom.getWidth(this.domElement) / 2 + 'px';
this.domElement.style.top = window.innerHeight/2 - dom.getHeight(this.domElement) / 2 + 'px';
};
function lockScroll(e) {
console.log(e);
}
return CenteredDiv;
})(dat.dom.dom,
dat.utils.common),
dat.dom.dom,
dat.utils.common);
},{}],48:[function(require,module,exports){
var EventEmitter = require('events').EventEmitter;
module.exports = function (elem) {
return new Ever(elem);
};
function Ever (elem) {
this.element = elem;
}
Ever.prototype = new EventEmitter;
Ever.prototype.on = function (name, cb, useCapture) {
if (!this._events) this._events = {};
if (!this._events[name]) this._events[name] = [];
this._events[name].push(cb);
this.element.addEventListener(name, cb, useCapture || false);
return this;
};
Ever.prototype.addListener = Ever.prototype.on;
Ever.prototype.removeListener = function (type, listener, useCapture) {
if (!this._events) this._events = {};
this.element.removeEventListener(type, listener, useCapture || false);
var xs = this.listeners(type);
var ix = xs.indexOf(listener);
if (ix >= 0) xs.splice(ix, 1);
return this;
};
Ever.prototype.removeAllListeners = function (type) {
var self = this;
function removeAll (t) {
var xs = self.listeners(t);
for (var i = 0; i < xs.length; i++) {
self.removeListener(t, xs[i]);
}
}
if (type) {
removeAll(type)
}
else if (self._events) {
for (var key in self._events) {
if (key) removeAll(key);
}
}
return EventEmitter.prototype.removeAllListeners.apply(self, arguments);
}
var initSignatures = require('./init.json');
Ever.prototype.emit = function (name, ev) {
if (typeof name === 'object') {
ev = name;
name = ev.type;
}
if (!isEvent(ev)) {
var type = Ever.typeOf(name);
var opts = ev || {};
if (opts.type === undefined) opts.type = name;
ev = document.createEvent(type + 's');
var init = typeof ev['init' + type] === 'function'
? 'init' + type : 'initEvent'
;
var sig = initSignatures[init];
var used = {};
var args = [];
for (var i = 0; i < sig.length; i++) {
var key = sig[i];
args.push(opts[key]);
used[key] = true;
}
ev[init].apply(ev, args);
// attach remaining unused options to the object
for (var key in opts) {
if (!used[key]) ev[key] = opts[key];
}
}
return this.element.dispatchEvent(ev);
};
function isEvent (ev) {
var s = Object.prototype.toString.call(ev);
return /\[object \S+Event\]/.test(s);
}
Ever.types = require('./types.json');
Ever.typeOf = (function () {
var types = {};
for (var key in Ever.types) {
var ts = Ever.types[key];
for (var i = 0; i < ts.length; i++) {
types[ts[i]] = key;
}
}
return function (name) {
return types[name] || 'Event';
};
})();;
},{"./init.json":49,"./types.json":50,"events":21}],49:[function(require,module,exports){
module.exports={
"initEvent" : [
"type",
"canBubble",
"cancelable"
],
"initUIEvent" : [
"type",
"canBubble",
"cancelable",
"view",
"detail"
],
"initMouseEvent" : [
"type",
"canBubble",
"cancelable",
"view",
"detail",
"screenX",
"screenY",
"clientX",
"clientY",
"ctrlKey",
"altKey",
"shiftKey",
"metaKey",
"button",
"relatedTarget"
],
"initMutationEvent" : [
"type",
"canBubble",
"cancelable",
"relatedNode",
"prevValue",
"newValue",
"attrName",
"attrChange"
]
}
},{}],50:[function(require,module,exports){
module.exports={
"MouseEvent" : [
"click",
"mousedown",
"mouseup",
"mouseover",
"mousemove",
"mouseout"
],
"KeyBoardEvent" : [
"keydown",
"keyup",
"keypress"
],
"MutationEvent" : [
"DOMSubtreeModified",
"DOMNodeInserted",
"DOMNodeRemoved",
"DOMNodeRemovedFromDocument",
"DOMNodeInsertedIntoDocument",
"DOMAttrModified",
"DOMCharacterDataModified"
],
"HTMLEvent" : [
"load",
"unload",
"abort",
"error",
"select",
"change",
"submit",
"reset",
"focus",
"blur",
"resize",
"scroll"
],
"UIEvent" : [
"DOMFocusIn",
"DOMFocusOut",
"DOMActivate"
]
}
},{}],51:[function(require,module,exports){
'use strict';
var vkey = require('vkey');
var createDatgui = require('dat-gui')
module.exports = function(game, opts) {
return new BindingsUI(game, opts);
};
module.exports.pluginInfo = {
loadAfter: ['voxel-debug', 'voxel-plugins-ui'], // optional to load after and reuse same gui
clientOnly: true
};
function BindingsUI(game, opts) {
this.game = game;
opts = opts || {};
this.kb = opts.kb || (game && game.buttons); // might be undefined
// try to latch on to an existing datgui, otherwise make our own
this.gui = opts.gui;
if (!this.gui) {
if (game && game.plugins) {
if (game.plugins.get('voxel-debug')) this.gui = game.plugins.get('voxel-debug').gui;
else if (game.plugins.get('voxel-plugins-ui')) this.gui = game.plugins.get('voxel-plugins-ui').gui;
}
}
if (!this.gui) this.gui = new createDatgui.GUI();
this.hideKeys = opts.hideKeys || ['ime-', 'launch-', 'browser-']; // too long
this.folder = this.gui.addFolder('keys');
// clean up the valid key listing TODO: refactor with game-shell? it does almost the same
this.vkey2code = {};
this.vkeyBracket2Bare = {};
this.vkeyBare2Bracket = {};
this.keyListing = [];
for (var code in vkey) {
var keyName = vkey[code];
this.vkey2code[keyName] = code;
var keyNameBare = filtered_vkey(keyName);
this.vkeyBracket2Bare[keyName] = keyNameBare;
this.vkeyBare2Bracket[keyNameBare] = keyName;
if (!this.shouldHideKey(keyNameBare))
this.keyListing.push(keyNameBare);
}
this.enable();
}
// cleanup key name - based on https://github.com/mikolalysenko/game-shell/blob/master/shell.js
// TODO: refactor with game-shell? and voxel-engine?
var filtered_vkey = function(k) {
if(k.charAt(0) === '<' && k.charAt(k.length-1) === '>') {
k = k.substring(1, k.length-1)
}
k = k.replace(/\s/g, "-")
return k
}
BindingsUI.prototype.enable = function() {
this.populate();
if (this.game.shell) {
this.game.shell.on('bind', this.onBind = this.populate.bind(this));
this.game.shell.on('unbind', this.onUnbind = this.populate.bind(this));
}
}
BindingsUI.prototype.disable = function() {
if (this.game.shell) {
this.game.shell.removeListener('bind', this.onBind);
this.game.shell.removeListener('unbind', this.onUnbind);
}
}
BindingsUI.prototype.populate = function() {
// get keybindings
this.binding2Key = {};
if (this.kb && this.kb.bindings) {
// voxel-engine with kb-bindings - stores key -> binding
for (var key in this.kb.bindings) {
var binding = this.kb.bindings[key];
this.binding2Key[binding] = this.vkeyBracket2Bare[key] || key;
this.addBinding(binding);
}
} else if (this.game.shell && this.game.shell.bindings) {
// game-shell - stores binding -> key(s)
// first, remove all items, since this may be called multiple times
if (this.addedItems) {
for (var i = 0; i < this.addedItems.length; i += 1) {
this.folder.remove(this.addedItems[i]);
}
}
// then add everything
this.addedItems = [];
for (var binding in this.game.shell.bindings) {
var key = this.game.shell.bindings[binding];
if (Array.isArray(key)) {
key = key[0]; // TODO: support multiple keys. for now, only taking first
}
this.binding2Key[binding] = this.vkeyBracket2Bare[key] || key;
var item = this.addBinding(binding);
this.addedItems.push(item);
}
}
}
BindingsUI.prototype.shouldHideKey = function(name) {
for (var i = 0; i < this.hideKeys.length; ++i) {
if (name.indexOf(this.hideKeys[i]) === 0) return true;
}
return false;
};
BindingsUI.prototype.addBinding = function (binding) {
var item = this.folder.add(this.binding2Key, binding, this.keyListing);
item.onChange(updateBinding(this, binding));
return item;
};
function updateBinding(self, binding) {
return function(newKeyNameBare) {
//if (self.vkey2code[newKeyName] === undefined) // invalid vkey
var newKeyName = self.vkeyBare2Bracket[newKeyNameBare];
self.removeBindings(binding);
if (self.kb && self.kb.bindings) {
self.kb.bindings[newKeyName] = binding;
} else {
self.game.shell.bind(binding, newKeyName);
}
};
}
// remove all keys bound to given binding
BindingsUI.prototype.removeBindings = function(binding) {
if (this.kb && this.kb.bindings) {
for (var key in this.kb.bindings) {
var thisBinding = this.kb.bindings[key];
if (thisBinding === binding) {
delete this.kb.bindings[key];
}
}
} else {
this.game.shell.unbind(binding);
}
};
},{"dat-gui":52,"vkey":55}],52:[function(require,module,exports){
arguments[4][45][0].apply(exports,arguments)
},{"./vendor/dat.color":53,"./vendor/dat.gui":54,"dup":45}],53:[function(require,module,exports){
arguments[4][46][0].apply(exports,arguments)
},{"dup":46}],54:[function(require,module,exports){
arguments[4][47][0].apply(exports,arguments)
},{"dup":47}],55:[function(require,module,exports){
var ua = typeof window !== 'undefined' ? window.navigator.userAgent : ''
, isOSX = /OS X/.test(ua)
, isOpera = /Opera/.test(ua)
, maybeFirefox = !/like Gecko/.test(ua) && !isOpera
var i, output = module.exports = {
0: isOSX ? '<menu>' : '<UNK>'
, 1: '<mouse 1>'
, 2: '<mouse 2>'
, 3: '<break>'
, 4: '<mouse 3>'
, 5: '<mouse 4>'
, 6: '<mouse 5>'
, 8: '<backspace>'
, 9: '<tab>'
, 12: '<clear>'
, 13: '<enter>'
, 16: '<shift>'
, 17: '<control>'
, 18: '<alt>'
, 19: '<pause>'
, 20: '<caps-lock>'
, 21: '<ime-hangul>'
, 23: '<ime-junja>'
, 24: '<ime-final>'
, 25: '<ime-kanji>'
, 27: '<escape>'
, 28: '<ime-convert>'
, 29: '<ime-nonconvert>'
, 30: '<ime-accept>'
, 31: '<ime-mode-change>'
, 27: '<escape>'
, 32: '<space>'
, 33: '<page-up>'
, 34: '<page-down>'
, 35: '<end>'
, 36: '<home>'
, 37: '<left>'
, 38: '<up>'
, 39: '<right>'
, 40: '<down>'
, 41: '<select>'
, 42: '<print>'
, 43: '<execute>'
, 44: '<snapshot>'
, 45: '<insert>'
, 46: '<delete>'
, 47: '<help>'
, 91: '<meta>' // meta-left -- no one handles left and right properly, so we coerce into one.
, 92: '<meta>' // meta-right
, 93: isOSX ? '<meta>' : '<menu>' // chrome,opera,safari all report this for meta-right (osx mbp).
, 95: '<sleep>'
, 106: '<num-*>'
, 107: '<num-+>'
, 108: '<num-enter>'
, 109: '<num-->'
, 110: '<num-.>'
, 111: '<num-/>'
, 144: '<num-lock>'
, 145: '<scroll-lock>'
, 160: '<shift-left>'
, 161: '<shift-right>'
, 162: '<control-left>'
, 163: '<control-right>'
, 164: '<alt-left>'
, 165: '<alt-right>'
, 166: '<browser-back>'
, 167: '<browser-forward>'
, 168: '<browser-refresh>'
, 169: '<browser-stop>'
, 170: '<browser-search>'
, 171: '<browser-favorites>'
, 172: '<browser-home>'
// ff/osx reports '<volume-mute>' for '-'
, 173: isOSX && maybeFirefox ? '-' : '<volume-mute>'
, 174: '<volume-down>'
, 175: '<volume-up>'
, 176: '<next-track>'
, 177: '<prev-track>'
, 178: '<stop>'
, 179: '<play-pause>'
, 180: '<launch-mail>'
, 181: '<launch-media-select>'
, 182: '<launch-app 1>'
, 183: '<launch-app 2>'
, 186: ';'
, 187: '='
, 188: ','
, 189: '-'
, 190: '.'
, 191: '/'
, 192: '`'
, 219: '['
, 220: '\\'
, 221: ']'
, 222: "'"
, 223: '<meta>'
, 224: '<meta>' // firefox reports meta here.
, 226: '<alt-gr>'
, 229: '<ime-process>'
, 231: isOpera ? '`' : '<unicode>'
, 246: '<attention>'
, 247: '<crsel>'
, 248: '<exsel>'
, 249: '<erase-eof>'
, 250: '<play>'
, 251: '<zoom>'
, 252: '<no-name>'
, 253: '<pa-1>'
, 254: '<clear>'
}
for(i = 58; i < 65; ++i) {
output[i] = String.fromCharCode(i)
}
// 0-9
for(i = 48; i < 58; ++i) {
output[i] = (i - 48)+''
}
// A-Z
for(i = 65; i < 91; ++i) {
output[i] = String.fromCharCode(i)
}
// num0-9
for(i = 96; i < 106; ++i) {
output[i] = '<num-'+(i - 96)+'>'
}
// F1-F24
for(i = 112; i < 136; ++i) {
output[i] = 'F'+(i-111)
}
},{}],56:[function(require,module,exports){
// Generated by CoffeeScript 1.7.0
(function() {
var APDialog, APPlugin, ModalDialog, createSelector,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
ModalDialog = require('voxel-modal-dialog');
createSelector = require('artpacks-ui');
module.exports = function(game, opts) {
return new APPlugin(game, opts);
};
module.exports.pluginInfo = {
clientOnly: true,
loadAfter: ['voxel-keys', 'voxel-stitch']
};
APPlugin = (function() {
function APPlugin(game, opts) {
var bindKey, _ref, _ref1, _ref2;
this.game = game;
if ((_ref = this.getArtpacks()) != null) {
_ref;
} else {
throw new Error('voxel-artpacks requires game.materials as voxel-texture-shader, or voxel-stitch');
};
this.keys = (function() {
if ((_ref1 = this.game.plugins.get('voxel-keys')) != null) {
return _ref1;
} else {
throw new Error('voxel-artpacks requires voxel-keys plugin');
}
}).call(this);
bindKey = (_ref2 = opts.bindKey) != null ? _ref2 : (this.game.shell ? 'P' : false);
if (bindKey) {
this.game.shell.bind('packs', bindKey);
}
this.dialog = new APDialog(this, this.game);
this.enable();
}
APPlugin.prototype.enable = function() {
return this.keys.down.on('packs', this.onDown = this.dialog.open.bind(this.dialog));
};
APPlugin.prototype.disable = function() {
if (this.onDown != null) {
return this.keys.down.removeListener('packs', this.onDown);
}
};
APPlugin.prototype.getArtpacks = function() {
var _ref, _ref1, _ref2, _ref3;
return (_ref = (_ref1 = this.game.materials) != null ? _ref1.artPacks : void 0) != null ? _ref : (_ref2 = this.game.plugins) != null ? (_ref3 = _ref2.get('voxel-stitch')) != null ? _ref3.artpacks : void 0 : void 0;
};
return APPlugin;
})();
APDialog = (function(_super) {
__extends(APDialog, _super);
function APDialog(plugin, game) {
var contents, refreshButton, selector;
this.plugin = plugin;
this.game = game;
contents = [];
contents.push(document.createTextNode('Drag packs below to change priority, or drop a .zip to load new pack:'));
selector = createSelector(this.plugin.getArtpacks());
selector.container.style.margin = '5px';
contents.push(selector.container);
refreshButton = document.createElement('button');
refreshButton.textContent = 'Preview';
refreshButton.style.width = '100%';
refreshButton.addEventListener('click', (function(_this) {
return function(ev) {
var i, old_names, stitcher;
stitcher = _this.game.plugins.get('voxel-stitch');
if (stitcher != null) {
refreshButton.disabled = true;
stitcher.on('addedAll', function() {
return refreshButton.disabled = false;
});
return stitcher.stitch();
} else {
old_names = _this.game.materials.names;
_this.game.texture_opts.game = self.game;
i = 0;
_this.game.materials = _this.game.texture_modules[i](_this.game.texture_opts);
_this.game.materials.load(old_names);
return _this.game.showAllChunks();
}
};
})(this));
contents.push(refreshButton);
APDialog.__super__.constructor.call(this, game, {
contents: contents,
escapeKeys: [192, 80]
});
}
return APDialog;
})(ModalDialog);
}).call(this);
},{"artpacks-ui":57,"voxel-modal-dialog":58}],57:[function(require,module,exports){
// Generated by CoffeeScript 1.7.0
(function() {
var APSelector;
module.exports = function(artPacks) {
return new APSelector(artPacks);
};
APSelector = (function() {
function APSelector(artPacks, opts) {
var _ref;
this.artPacks = artPacks;
this.container = document.createElement('div');
this.draggingIndex = void 0;
if (opts == null) {
opts = {};
}
this.logoSize = (_ref = opts.logoSize) != null ? _ref : 64;
this.enable();
}
APSelector.prototype.enable = function() {
this.refresh();
this.artPacks.on('refresh', this.refresh.bind(this));
document.addEventListener('dragover', this.onDocDragOver.bind(this));
return document.addEventListener('drop', this.onDocDrop.bind(this));
};
APSelector.prototype.disable = function() {};
APSelector.prototype.refresh = function() {
var i, iReverse, logo, node, pack, _i, _len, _ref, _results;
while (this.container.firstChild) {
this.container.removeChild(this.container.firstChild);
}
_ref = this.artPacks.packs.slice(0).reverse();
_results = [];
for (iReverse = _i = 0, _len = _ref.length; _i < _len; iReverse = ++_i) {
pack = _ref[iReverse];
i = this.artPacks.packs.length - 1 - iReverse;
if (pack == null) {
continue;
}
node = document.createElement('div');
node.setAttribute('draggable', 'true');
node.setAttribute('style', 'border: 1px solid black; -webkit-user-select: none; -moz-user-select: none; cursor: move; padding: 10px; display: flex; align-items: center;');
node.addEventListener('dragstart', this.onDragStart.bind(this, node, i), false);
node.addEventListener('dragend', this.onDragEnd.bind(this, node, i), false);
node.addEventListener('dragenter', this.onDragEnter.bind(this, node, i), false);
node.addEventListener('dragleave', this.onDragLeave.bind(this, node, i), false);
node.addEventListener('dragover', this.onDragOver.bind(this, node, i), false);
node.addEventListener('drop', this.onDrop.bind(this, node, i), false);
logo = new Image();
logo.src = pack.getPackLogo();
logo.width = logo.height = this.logoSize;
logo.style.paddingRight = '5px';
node.appendChild(logo);
node.appendChild(document.createTextNode(pack.getDescription()));
_results.push(this.container.appendChild(node));
}
return _results;
};
APSelector.prototype.onDragStart = function(node, i, ev) {
this.draggingIndex = i;
node.style.opacity = '0.4';
ev.dataTransfer.effectAllowed = 'move';
return ev.dataTransfer.setData('text/plain', '' + i);
};
APSelector.prototype.onDragEnd = function(node, i) {
this.draggingIndex = void 0;
return node.style.opacity = '';
};
APSelector.prototype.onDragEnter = function(node, i) {
if (i === this.draggingIndex) {
return;
}
return node.style.border = '1px dashed black';
};
APSelector.prototype.onDragLeave = function(node, i) {
if (i === this.draggingIndex) {
return;
}
return node.style.border = '1px solid black';
};
APSelector.prototype.onDragOver = function(node, i, ev) {
ev.preventDefault();
return ev.dataTransfer.dropEffect = 'move';
};
APSelector.prototype.onDrop = function(node, i, ev) {
ev.stopPropagation();
ev.preventDefault();
if (ev.dataTransfer.files.length !== 0) {
return this.addDroppedFiles(ev.dataTransfer.files, i);
} else {
this.draggingIndex = +ev.dataTransfer.getData('text/plain');
return this.artPacks.swap(this.draggingIndex, i);
}
};
APSelector.prototype.addDroppedFiles = function(files, at) {
var file, reader, _i, _len, _results;
if (at == null) {
at = void 0;
}
_results = [];
for (_i = 0, _len = files.length; _i < _len; _i++) {
file = files[_i];
reader = new FileReader();
reader.addEventListener('load', (function(_this) {
return function(readEvent) {
if (readEvent.total !== readEvent.loaded) {
return;
}
return _this.artPacks.addPack(readEvent.currentTarget.result, file.name);
};
})(this));
_results.push(reader.readAsArrayBuffer(file));
}
return _results;
};
APSelector.prototype.onDocDragOver = function(ev) {
ev.preventDefault();
ev.stopPropagation();
return ev.dataTransfer.dropEffect = 'move';
};
APSelector.prototype.onDocDrop = function(ev) {
if (ev.dataTransfer.files.length !== 0) {
ev.stopPropagation();
ev.preventDefault();
return this.addDroppedFiles(ev.dataTransfer.files);
}
};
return APSelector;
})();
}).call(this);
},{}],58:[function(require,module,exports){
// Generated by CoffeeScript 1.7.0
(function() {
var Modal, ModalDialog,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Modal = require('voxel-modal');
ModalDialog = (function(_super) {
__extends(ModalDialog, _super);
function ModalDialog(game, opts) {
var content, _i, _len, _ref;
this.game = game;
if (opts == null) {
opts = {};
}
if (opts.contents == null) {
opts.contents = [];
}
if (typeof document !== "undefined" && document !== null) {
this.aligner = document.createElement('div');
this.aligner.setAttribute('class', 'voxel-modal-dialog-aligner');
this.aligner.setAttribute('style', 'display: flex; align-items: center; justify-content: center; top: 0px; left: 0px; width: 100%; height: 90%; position: fixed; pointer-events: none;');
this.box = document.createElement('div');
this.box.setAttribute('class', 'voxel-modal-dialog');
this.box.style.border = '6px outset gray';
this.box.style.visibility = 'hidden';
this.box.style.zIndex = 1;
this.box.style.pointerEvents = 'auto';
this.box.style.backgroundImage = 'linear-gradient(rgba(255,255,255,0.5) 0%, rgba(255,255,255,0.5) 100%)';
_ref = opts.contents;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
content = _ref[_i];
this.box.appendChild(content);
}
this.aligner.appendChild(this.box);
document.body.appendChild(this.aligner);
}
opts.element = this.box;
ModalDialog.__super__.constructor.call(this, game, opts);
}
return ModalDialog;
})(Modal);
module.exports = ModalDialog;
}).call(this);
},{"voxel-modal":59}],59:[function(require,module,exports){
/*jshint globalstrict: true*/
'use strict';
module.exports = Modal;
var ever = require('ever');
function Modal(game, opts)
{
this.game = game;
opts = opts || {};
this.element = opts.element;
if (!this.element) throw new Error('voxel-modal requires "element" option');
// shortcut to close:
// ` (backquote) -- NOT escape due to pointer-lock https://github.com/deathcap/voxel-modal/issues/1
// if you don't have "`", alternative is to click the game canvas (closes automatically on attain)
this.escapeKeys = opts.escapeKeys || [192];
this.isOpen = false;
}
Modal.prototype.open = function() {
if (this.isOpen) return;
var self = this;
if (this.game.shell) {
// exit pointer lock so user can interact with the modal element
this.game.shell.pointerLock = false;
// but re-"want" it so clicking the canvas (outside the modal) will
// activate pointer lock (misleading assignment; requires user interaction)
this.game.shell.pointerLock = true;
// when user successfully acquires pointer lock by clicking the game-shell
// canvas, get out of the way
// TODO: ask game-shell to emit an event for us
var self = this;
ever(document).on('pointerlockchange', self.onPointerLockChange = function() {
if (document.pointerLockElement) {
// pointer lock was acquired - close ourselves, resume gameplay
self.close();
ever(document).removeListener('pointerlockchange', self.onPointerLockChange); // can't seem to use .once with ever (TypeError document removeListener)
}
});
// webkit prefix for older browsers (< Chrome 40)
ever(document).on('webkitpointerlockchange', self.onWKPointerLockChange = function() {
if (document.webkitPointerLockElement) {
self.close();
ever(document).removeListener('webkitpointerlockchange', self.onWKPointerLockChange);
}
});
// moz prefix for Firefox
ever(document).on('mozpointerlockchange', self.onMPointerLockChange = function() {
if (document.mozPointerLockElement) {
self.close();
ever(document).removeListener('mozpointerlockchange', self.onMPointerLockChange);
}
});
} else if (this.game.interact) {
this.game.interact.release();
this.game.interact.on('attain', this.onAttain = function() {
// clicked game, beyond dialog TODO: game-shell needs this, too!
self.close();
});
} else {
throw new Error('voxel-modal requires game-shell or interact');
}
ever(document.body).on('keydown', this.onKeydown = function(ev) {
if (self.escapeKeys.indexOf(ev.keyCode) !== -1) {
self.close();
ev.preventDefault();
}
});
this.element.style.visibility = '';
this.isOpen = true;
};
Modal.prototype.close = function() {
if (!this.isOpen) return;
ever(document.body).removeListener('keydown', this.onKeydown);
this.element.style.visibility = 'hidden';
// resume game interaction
if (this.game.shell) {
this.game.shell.pointerLock = true;
} else if (this.game.interact) {
this.game.interact.removeListener('attain', this.onAttain);
this.game.interact.request();
}
this.isOpen = false;
};
Modal.prototype.toggle = function() {
if (this.isOpen)
this.close();
else
this.open();
};
},{"ever":48}],60:[function(require,module,exports){
'use strict';
module.exports = function(game, opts) {
return new BackgroundMusicPlugin(game, opts);
};
module.exports.pluginInfo = {
clientOnly: true,
loadAfter: ['voxel-sfx']
};
function BackgroundMusicPlugin(game, opts) {
this.game = game;
this.artPacks = this.game.materials.artPacks;
this.canPlay = opts.canPlay || true;
this.enable();
}
BackgroundMusicPlugin.prototype.enable = function() {
var self = this;
self.voxelSfx = game.plugins.get('voxel-sfx');
if(!this.voxelSfx) throw new Error('voxel-background-music requires voxel-sfx')
if(self.canPlay){
self.game.materials.artPacks.on('loadedAll', this.loaded = function(){
self.voxelSfx.play('random/background', true, 0.7);
});
console.log("PLAYING BACKGROUND")
}
}
BackgroundMusicPlugin.prototype.disable = function() {
var self = this;
self.voxelSfx.pause('random/background');
}
},{}],61:[function(require,module,exports){
'use strict';
module.exports = function(game, opts) {
return new BlockData(game, opts);
};
function BlockData(game, opts) {
this.game = game;
this.enable();
}
BlockData.prototype.enable = function() {
var self = this;
this.game.on('setBlock', this.onSetBlock = function(target) {
// clear blockdata when blocks change
self.clear.apply(self, target);
});
};
BlockData.prototype.disable = function() {
this.game.removeListener('setBlock', this.onSetBlock);
};
// API
// Get the blockdataMap for the chunk at given world coordinates
// Returns undefined if the chunk doesn't exist
// Initializes blockdataMap to {} if it doesn't exist (but the chunk does), _unless_ noCreate true
BlockData.prototype.getForChunk = function(x, y, z, noCreate) {
var chunkIndex = this.game.voxels.chunkAtCoordinates(x, y, z).join('|');
var chunk = this.game.voxels.chunks[chunkIndex];
if (!chunk)
return undefined;
if (chunk.blockdata === undefined && !noCreate)
chunk.blockdata = {};
return chunk.blockdata;
};
BlockData.prototype.coordsToKey = function(x, y, z) {
// TODO: should we translate global world coords to local chunk coords?
return [x, y, z].join(',');
};
BlockData.prototype.get = function(x, y, z) {
var blockdataMap = this.getForChunk(x, y, z);
if (blockdataMap === undefined) return undefined;
return blockdataMap[this.coordsToKey(x, y, z)];
};
BlockData.prototype.set = function(x, y, z, data) {
var blockdataMap = this.getForChunk(x, y, z);
if (blockdataMap === undefined) return undefined;
blockdataMap[this.coordsToKey(x, y, z)] = data;
};
BlockData.prototype.clear = function(x, y, z) {
var blockdataMap = this.getForChunk(x, y, z, true); // don't create for chunk if doesn't exist (read-only)
if (blockdataMap === undefined) return undefined;
delete blockdataMap[this.coordsToKey(x, y,z)];
};
},{}],62:[function(require,module,exports){
var BucketPlugin, ItemPile, ucfirst;
ItemPile = require('itempile');
ucfirst = require('ucfirst');
module.exports = function(game, opts) {
return new BucketPlugin(game, opts);
};
module.exports.pluginInfo = {
loadAfter: ['voxel-registry', 'voxel-fluid']
};
BucketPlugin = (function() {
function BucketPlugin(game1, opts1) {
var base, base1, base2, ref, ref1;
this.game = game1;
this.opts = opts1;
this.registry = (function() {
if ((ref = this.game.plugins.get('voxel-registry')) != null) {
return ref;
} else {
throw new Error('voxel-bucket requires "voxel-registry" plugin');
}
}).call(this);
this.fluidPlugin = (function() {
if ((ref1 = this.game.plugins.get('voxel-fluid')) != null) {
return ref1;
} else {
throw new Error('voxel-bucket requires "voxel-fluid" plugin');
}
}).call(this);
this.fluidBuckets = {};
if ((base = this.opts).registerBlocks == null) {
base.registerBlocks = true;
}
if ((base1 = this.opts).registerItems == null) {
base1.registerItems = true;
}
if ((base2 = this.opts).registerRecipes == null) {
base2.registerRecipes = true;
}
this.enable();
}
BucketPlugin.prototype.enable = function() {
var bucketName, fluid, i, len, ref, ref1;
if (this.opts.registerItems) {
this.registry.registerItem('bucket', {
itemTexture: 'i/bucket_empty',
onUse: this.pickupFluid.bind(this),
displayName: 'Empty Bucket',
creativeTab: 'fluids'
});
ref = this.fluidPlugin.getFluidNames();
for (i = 0, len = ref.length; i < len; i++) {
fluid = ref[i];
bucketName = "bucket" + (ucfirst(fluid));
this.registry.registerItem(bucketName, {
itemTexture: "i/bucket_" + fluid,
fluid: fluid,
containerItem: 'bucket',
onUse: this.placeFluid.bind(this, fluid),
displayName: (ucfirst(fluid)) + " Bucket",
creativeTab: 'fluids'
});
this.fluidBuckets[fluid] = bucketName;
}
}
if (this.opts.registerRecipes) {
this.recipes = (function() {
if ((ref1 = this.game.plugins.get('voxel-recipes')) != null) {
return ref1;
} else {
throw new Error('voxel-bucket requires voxel-recipes plugin when opts.registerRecipes enabled');
}
}).call(this);
return this.recipes.registerPositional([['ingotIron', void 0, 'ingotIron'], ['ingotIron', 'ingotIron', 'ingotIron'], [void 0, void 0, void 0]], new ItemPile('bucket'));
}
};
BucketPlugin.prototype.disable = function() {};
BucketPlugin.prototype.pickupFluid = function(held, target) {
var flowing, fluid, fluidBucket, name, props;
console.log('pickupFluid', held, target);
if (!target) {
return;
}
name = this.registry.getBlockName(target.value);
props = this.registry.getBlockProps(name);
if (props == null) {
return;
}
fluid = props.fluid;
if (!fluid) {
return;
}
flowing = props.flowing;
if (flowing) {
return;
}
fluidBucket = this.fluidBuckets[fluid];
if (!fluidBucket) {
return;
}
this.game.setBlock(target.voxel, 0);
return new ItemPile(fluidBucket);
};
BucketPlugin.prototype.placeFluid = function(fluid, held, target) {
var fluidIndex;
console.log('placeFluid', fluid, held, target);
if (!target) {
return;
}
fluidIndex = this.registry.getBlockIndex(fluid);
if (fluidIndex == null) {
return;
}
this.game.setBlock(target.adjacent, fluidIndex);
return new ItemPile('bucket');
};
return BucketPlugin;
})();
},{"itempile":63,"ucfirst":68}],63:[function(require,module,exports){
"use strict";
var _slicedToArray = function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } };
var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
var deepEqual = require("deep-equal");
var cloneObject = require("clone");
var ItemPile = (function () {
function ItemPile(item) {
var count = arguments[1] === undefined ? 1 : arguments[1];
var tags = arguments[2] === undefined ? {} : arguments[2];
_classCallCheck(this, ItemPile);
this.item = typeof item === "string" ? ItemPile.itemFromString(item) : item;
this.count = count;
this.tags = tags;
}
_prototypeProperties(ItemPile, {
maxPileSize: {
// maximum size items should pile
get: function () {
return 64;
},
configurable: true
},
itemFromString: {
// convert item<->string; change these to use non-string items
value: function itemFromString(s) {
if (s instanceof ItemPile) {
return s;
}return !s ? "" : s;
},
writable: true,
configurable: true
},
itemToString: {
value: function itemToString(item) {
return "" + item;
},
writable: true,
configurable: true
},
fromString: {
value: function fromString(s) {
var a = s.match(/^([^:]+):([^ ]+) ?(.*)/); // assumptions: positive integral count, item name no spaces
if (!a) {
return undefined;
}
var _a = _slicedToArray(a, 4);
var _ = _a[0];
var countStr = _a[1];
var itemStr = _a[2];
var tagsStr = _a[3];
var count = undefined;
if (countStr === "Infinity") {
count = Infinity;
} else {
count = parseInt(countStr, 10);
}
var item = ItemPile.itemFromString(itemStr);
var tags = undefined;
if (tagsStr && tagsStr.length) {
tags = JSON.parse(tagsStr);
} else {
tags = {};
}
return new ItemPile(item, count, tags);
},
writable: true,
configurable: true
},
fromArray: {
value: function fromArray(_ref) {
var _ref2 = _slicedToArray(_ref, 3);
var item = _ref2[0];
var count = _ref2[1];
var tags = _ref2[2];
return new ItemPile(item, count, tags);
},
writable: true,
configurable: true
},
fromArrayIfArray: {
value: function fromArrayIfArray(a) {
if (Array.isArray(a)) {
return ItemPile.fromArray(a);
} else {
return a;
}
},
writable: true,
configurable: true
}
}, {
clone: {
value: function clone() {
return new ItemPile(this.item, this.count, cloneObject(this.tags, false));
},
writable: true,
configurable: true
},
hasTags: {
value: function hasTags() {
return Object.keys(this.tags).length !== 0; // not "{}"
},
writable: true,
configurable: true
},
matchesType: {
value: function matchesType(itemPile) {
return this.item === itemPile.item;
},
writable: true,
configurable: true
},
matchesTypeAndCount: {
value: function matchesTypeAndCount(itemPile) {
return this.item === itemPile.item && this.count === itemPile.count;
},
writable: true,
configurable: true
},
matchesTypeAndTags: {
value: function matchesTypeAndTags(itemPile) {
return this.item === itemPile.item && deepEqual(this.tags, itemPile.tags, { strict: true });
},
writable: true,
configurable: true
},
matchesAll: {
value: function matchesAll(itemPile) {
return this.matchesTypeAndCount(itemPile) && deepEqual(this.tags, itemPile.tags, { strict: true });
},
writable: true,
configurable: true
},
canPileWith: {
// can this pile be merged with another?
value: function canPileWith(itemPile) {
if (itemPile.item !== this.item) {
return false;
}if (itemPile.count === 0 || this.count === 0) {
return true;
} // (special case: can always merge with 0-size pile of same item, regardless of tags - for placeholder slots)
if (itemPile.hasTags() || this.hasTags()) {
return false;
} // any tag data makes unpileable
return true;
},
writable: true,
configurable: true
},
mergePile: {
// combine two piles if possible, altering both this and argument pile
// returns count of items that didn't fit
value: function mergePile(itemPile) {
if (!this.canPileWith(itemPile)) {
return false;
}itemPile.count = this.increase(itemPile.count);
return itemPile.count;
},
writable: true,
configurable: true
},
increase: {
// increase count by argument, returning number of items that didn't fit
value: function increase(n) {
var _tryAdding = this.tryAdding(n);
var _tryAdding2 = _slicedToArray(_tryAdding, 2);
var newCount = _tryAdding2[0];
var excessCount = _tryAdding2[1];
this.count = newCount;
return excessCount;
},
writable: true,
configurable: true
},
decrease: {
// decrease count by argument, returning number of items removed
value: function decrease(n) {
var _trySubtracting = this.trySubtracting(n);
var _trySubtracting2 = _slicedToArray(_trySubtracting, 2);
var removedCount = _trySubtracting2[0];
var remainingCount = _trySubtracting2[1];
this.count = remainingCount;
return removedCount;
},
writable: true,
configurable: true
},
tryAdding: {
// try combining count of items up to max pile size, returns [newCount, excessCount]
value: function tryAdding(n) {
// special case: infinite incoming count sets pile to infinite, even though >maxPileSize
// TODO: option to disable infinite piles? might want to add only up to 64 etc. (ref GH-2)
if (n === Infinity) {
return [Infinity, 0];
}var sum = this.count + n;
if (sum > ItemPile.maxPileSize && this.count !== Infinity) {
// (special case: infinite destination piles never overflow)
return [ItemPile.maxPileSize, sum - ItemPile.maxPileSize]; // overflowing pile
} else {
return [sum, 0]; // added everything they wanted
}
},
writable: true,
configurable: true
},
trySubtracting: {
// try removing a finite count of items, returns [removedCount, remainingCount]
value: function trySubtracting(n) {
var difference = this.count - n;
if (difference < 0) {
return [this.count, n - this.count]; // didn't have enough
} else {
return [n, this.count - n]; // had enough, some remain
}
},
writable: true,
configurable: true
},
splitPile: {
// remove count of argument items, returning new pile of those items which were split off
value: function splitPile(n) {
if (n === 0) {
return false;
}if (n < 0) {
// negative count = all but n
n = this.count + n;
} else if (n < 1) {
// fraction = fraction
n = Math.ceil(this.count * n);
}
if (n > this.count) {
return false;
}if (n !== Infinity) this.count -= n; // (subtract, but avoid Infinity - Infinity = NaN)
return new ItemPile(this.item, n, cloneObject(this.tags, false));
},
writable: true,
configurable: true
},
toString: {
value: function toString() {
if (this.hasTags()) {
return "" + this.count + ":" + this.item + " " + JSON.stringify(this.tags);
} else {
return "" + this.count + ":" + this.item;
}
},
writable: true,
configurable: true
}
});
return ItemPile;
})();
module.exports = ItemPile;
},{"clone":64,"deep-equal":65}],64:[function(require,module,exports){
(function (global,Buffer){
'use strict';
var clone = (function(global) {
/**
* Clones (copies) an Object using deep copying.
*
* This function supports circular references by default, but if you are certain
* there are no circular references in your object, you can save some CPU time
* by calling clone(obj, false).
*
* Caution: if `circular` is false and `parent` contains circular references,
* your program may enter an infinite loop and crash.
*
* @param `parent` - the object to be cloned
* @param `circular` - set to true if the object to be cloned may contain
* circular references. (optional - true by default)
* @param `depth` - set to a number if the object is only to be cloned to
* a particular depth. (optional - defaults to Infinity)
* @param `prototype` - sets the prototype to be used when cloning an object.
* (optional - defaults to parent prototype).
*/
function clone(parent, circular, depth, prototype) {
var filter;
if (typeof circular === 'object') {
depth = circular.depth;
prototype = circular.prototype;
filter = circular.filter;
circular = circular.circular
}
// maintain two arrays for circular references, where corresponding parents
// and children have the same index
var allParents = [];
var allChildren = [];
var useBuffer = typeof Buffer != 'undefined';
if (typeof circular == 'undefined')
circular = true;
if (typeof depth == 'undefined')
depth = Infinity;
// recurse this function so we don't reset allParents and allChildren
function _clone(parent, depth) {
// cloning null always returns null
if (parent === null)
return null;
if (depth == 0)
return parent;
var child;
var proto;
if (typeof parent != 'object') {
return parent;
}
if (isArray(parent)) {
child = [];
} else if (isRegExp(parent)) {
child = new RegExp(parent.source, clone.getRegExpFlags(parent));
if (parent.lastIndex) child.lastIndex = parent.lastIndex;
} else if (isDate(parent)) {
child = new Date(parent.getTime());
} else if (useBuffer && Buffer.isBuffer(parent)) {
child = new Buffer(parent.length);
parent.copy(child);
return child;
} else {
if (typeof prototype == 'undefined') {
proto = Object.getPrototypeOf(parent);
child = Object.create(proto);
}
else {
child = Object.create(prototype);
proto = prototype;
}
}
if (circular) {
var index = allParents.indexOf(parent);
if (index != -1) {
return allChildren[index];
}
allParents.push(parent);
allChildren.push(child);
}
for (var i in parent) {
var attrs;
if (proto) {
attrs = Object.getOwnPropertyDescriptor(proto, i);
}
if (attrs && attrs.set == null) {
continue;
}
child[i] = _clone(parent[i], depth - 1);
}
return child;
}
return _clone(parent, depth);
}
/**
* Simple flat clone using prototype, accepts only objects, usefull for property
* override on FLAT configuration object (no nested props).
*
* USE WITH CAUTION! This may not behave as you wish if you do not know how this
* works.
*/
clone.clonePrototype = function(parent) {
if (parent === null)
return null;
var c = function () {};
c.prototype = parent;
return new c();
};
function getRegExpFlags(re) {
var flags = '';
re.global && (flags += 'g');
re.ignoreCase && (flags += 'i');
re.multiline && (flags += 'm');
return flags;
}
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function isDate(o) {
return typeof o === 'object' && objectToString(o) === '[object Date]';
}
function isArray(o) {
return typeof o === 'object' && objectToString(o) === '[object Array]';
}
function isRegExp(o) {
return typeof o === 'object' && objectToString(o) === '[object RegExp]';
}
if (global.TESTING) clone.getRegExpFlags = getRegExpFlags;
if (global.TESTING) clone.objectToString = objectToString;
if (global.TESTING) clone.isDate = isDate;
if (global.TESTING) clone.isArray = isArray;
if (global.TESTING) clone.isRegExp = isRegExp;
return clone;
})( typeof(global) === 'object' ? global :
typeof(window) === 'object' ? window : this);
if (module && module.exports)
module.exports = clone;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
},{"buffer":17}],65:[function(require,module,exports){
var pSlice = Array.prototype.slice;
var objectKeys = require('./lib/keys.js');
var isArguments = require('./lib/is_arguments.js');
var deepEqual = module.exports = function (actual, expected, opts) {
if (!opts) opts = {};
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (actual instanceof Date && expected instanceof Date) {
return actual.getTime() === expected.getTime();
// 7.3. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if (typeof actual != 'object' && typeof expected != 'object') {
return opts.strict ? actual === expected : actual == expected;
// 7.4. For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected, opts);
}
}
function isUndefinedOrNull(value) {
return value === null || value === undefined;
}
function isBuffer (x) {
if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false;
if (typeof x.copy !== 'function' || typeof x.slice !== 'function') {
return false;
}
if (x.length > 0 && typeof x[0] !== 'number') return false;
return true;
}
function objEquiv(a, b, opts) {
var i, key;
if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
return false;
// an identical 'prototype' property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
if (isArguments(a)) {
if (!isArguments(b)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return deepEqual(a, b, opts);
}
if (isBuffer(a)) {
if (!isBuffer(b)) {
return false;
}
if (a.length !== b.length) return false;
for (i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
try {
var ka = objectKeys(a),
kb = objectKeys(b);
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!deepEqual(a[key], b[key], opts)) return false;
}
return typeof a === typeof b;
}
},{"./lib/is_arguments.js":66,"./lib/keys.js":67}],66:[function(require,module,exports){
var supportsArgumentsClass = (function(){
return Object.prototype.toString.call(arguments)
})() == '[object Arguments]';
exports = module.exports = supportsArgumentsClass ? supported : unsupported;
exports.supported = supported;
function supported(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
};
exports.unsupported = unsupported;
function unsupported(object){
return object &&
typeof object == 'object' &&
typeof object.length == 'number' &&
Object.prototype.hasOwnProperty.call(object, 'callee') &&
!Object.prototype.propertyIsEnumerable.call(object, 'callee') ||
false;
};
},{}],67:[function(require,module,exports){
exports = module.exports = typeof Object.keys === 'function'
? Object.keys : shim;
exports.shim = shim;
function shim (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
},{}],68:[function(require,module,exports){
'use strict';
module.exports = function(s) {
return s.substr(0, 1).toUpperCase() + s.substring(1);
};
},{}],69:[function(require,module,exports){
var Inventory = require('inventory');
module.exports = function(game, opts) {
return new Carry(game, opts);
};
function Carry(game, opts) {
opts = opts || {};
opts.inventoryWidth = opts.inventoryWidth || 10;
opts.inventoryRows = opts.inventoryRows || 5;
this.inventory = new Inventory(opts.inventoryWidth, opts.inventoryRows);
}
},{"inventory":70}],70:[function(require,module,exports){
var EventEmitter, Inventory, ItemPile, deepEqual,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
deepEqual = require('deep-equal');
ItemPile = require('itempile');
EventEmitter = (require('events')).EventEmitter;
module.exports = Inventory = (function(superClass) {
extend(Inventory, superClass);
function Inventory(xSize, ySize, opts) {
var size;
if (xSize == null) {
xSize = 10;
}
if (ySize == null) {
ySize = 1;
}
if (xSize <= 0) {
throw new Error("inventory invalid xSize: " + xSize);
}
if (ySize <= 0) {
throw new Error("inventory invalid xSize: " + ySize);
}
size = xSize * ySize;
this.array = new Array(size);
this.width = xSize;
this.height = ySize;
}
Inventory.prototype.changed = function() {
return this.emit('changed');
};
Inventory.prototype.give = function(itemPile) {
var excess, i, j, k, ref, ref1;
excess = itemPile.count;
for (i = j = 0, ref = this.array.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
if ((this.array[i] != null) && this.array[i].canPileWith(itemPile)) {
excess = this.array[i].mergePile(itemPile);
}
if (itemPile.count === 0) {
break;
}
}
for (i = k = 0, ref1 = this.array.length; 0 <= ref1 ? k < ref1 : k > ref1; i = 0 <= ref1 ? ++k : --k) {
if (this.array[i] == null) {
this.array[i] = itemPile.clone();
this.array[i].count = 0;
excess = this.array[i].mergePile(itemPile);
if (this.array[i].count === 0) {
this.array[i] = void 0;
}
}
if (itemPile.count === 0) {
break;
}
}
this.changed();
return excess;
};
Inventory.prototype.take = function(itemPile) {
var given, i, j, n, ref;
for (i = j = 0, ref = this.array.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
if ((this.array[i] != null) && this.array[i].matchesTypeAndTags(itemPile)) {
n = Math.min(itemPile.count, this.array[i].count);
itemPile.count -= n;
given = this.takeAt(i, n);
}
}
return this.changed();
};
Inventory.prototype.takeAt = function(position, count) {
var ret;
if (!this.array[position]) {
return false;
}
ret = this.array[position].splitPile(count);
if (this.array[position].count === 0) {
this.array[position] = void 0;
}
this.changed();
return ret;
};
Inventory.prototype.toString = function() {
var a, i, itemPile, j, len, ref;
a = [];
ref = this.array;
for (i = j = 0, len = ref.length; j < len; i = ++j) {
itemPile = ref[i];
if (itemPile == null) {
a.push('');
} else {
a.push("" + itemPile);
}
}
return a.join('\t');
};
Inventory.fromString = function(s) {
var items, ret, strings;
strings = s.split('\t');
items = (function() {
var j, len, results;
results = [];
for (j = 0, len = strings.length; j < len; j++) {
s = strings[j];
results.push(ItemPile.fromString(s));
}
return results;
})();
ret = new Inventory(items.length);
ret.array = items;
return ret;
};
Inventory.prototype.size = function() {
return this.array.length;
};
Inventory.prototype.get = function(i) {
return this.array[i];
};
Inventory.prototype.set = function(i, itemPile) {
this.array[i] = itemPile;
return this.changed();
};
Inventory.prototype.clear = function() {
var i, j, ref, results;
results = [];
for (i = j = 0, ref = this.size(); 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
results.push(this.set(i, void 0));
}
return results;
};
Inventory.prototype.transferTo = function(dest) {
var i, j, ref, results;
results = [];
for (i = j = 0, ref = this.size(); 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
dest.set(i, this.get(i));
results.push(this.set(i, void 0));
}
return results;
};
return Inventory;
})(EventEmitter);
},{"deep-equal":71,"events":21,"itempile":74}],71:[function(require,module,exports){
arguments[4][65][0].apply(exports,arguments)
},{"./lib/is_arguments.js":72,"./lib/keys.js":73,"dup":65}],72:[function(require,module,exports){
arguments[4][66][0].apply(exports,arguments)
},{"dup":66}],73:[function(require,module,exports){
arguments[4][67][0].apply(exports,arguments)
},{"dup":67}],74:[function(require,module,exports){
"use strict";
var _slicedToArray = function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } };
var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
var deepEqual = require("deep-equal");
var cloneObject = require("clone");
var ItemPile = (function () {
function ItemPile(item) {
var count = arguments[1] === undefined ? 1 : arguments[1];
var tags = arguments[2] === undefined ? {} : arguments[2];
_classCallCheck(this, ItemPile);
this.item = typeof item === "string" ? ItemPile.itemFromString(item) : item;
this.count = count;
this.tags = tags;
}
_prototypeProperties(ItemPile, {
maxPileSize: {
// maximum size items should pile
get: function () {
return 64;
},
configurable: true
},
itemFromString: {
// convert item<->string; change these to use non-string items
value: function itemFromString(s) {
if (s instanceof ItemPile) {
return s;
}return !s ? "" : s;
},
writable: true,
configurable: true
},
itemToString: {
value: function itemToString(item) {
return "" + item;
},
writable: true,
configurable: true
},
fromString: {
value: function fromString(s) {
var a = s.match(/^([^:]+):([^ ]+) ?(.*)/); // assumptions: positive integral count, item name no spaces
if (!a) {
return undefined;
}
var _a = _slicedToArray(a, 4);
var _ = _a[0];
var countStr = _a[1];
var itemStr = _a[2];
var tagsStr = _a[3];
var count = undefined;
if (countStr === "Infinity") {
count = Infinity;
} else {
count = parseInt(countStr, 10);
}
var item = ItemPile.itemFromString(itemStr);
var tags = undefined;
if (tagsStr && tagsStr.length) {
tags = JSON.parse(tagsStr);
} else {
tags = {};
}
return new ItemPile(item, count, tags);
},
writable: true,
configurable: true
},
fromArray: {
value: function fromArray(_ref) {
var _ref2 = _slicedToArray(_ref, 3);
var item = _ref2[0];
var count = _ref2[1];
var tags = _ref2[2];
return new ItemPile(item, count, tags);
},
writable: true,
configurable: true
},
fromArrayIfArray: {
value: function fromArrayIfArray(a) {
if (Array.isArray(a)) {
return ItemPile.fromArray(a);
} else {
return a;
}
},
writable: true,
configurable: true
}
}, {
clone: {
value: function clone() {
return new ItemPile(this.item, this.count, cloneObject(this.tags, false));
},
writable: true,
configurable: true
},
hasTags: {
value: function hasTags() {
return Object.keys(this.tags).length !== 0; // not "{}"
},
writable: true,
configurable: true
},
matchesType: {
value: function matchesType(itemPile) {
return this.item === itemPile.item;
},
writable: true,
configurable: true
},
matchesTypeAndCount: {
value: function matchesTypeAndCount(itemPile) {
return this.item === itemPile.item && this.count === itemPile.count;
},
writable: true,
configurable: true
},
matchesTypeAndTags: {
value: function matchesTypeAndTags(itemPile) {
return this.item === itemPile.item && deepEqual(this.tags, itemPile.tags, { strict: true });
},
writable: true,
configurable: true
},
matchesAll: {
value: function matchesAll(itemPile) {
return this.matchesTypeAndCount(itemPile) && deepEqual(this.tags, itemPile.tags, { strict: true });
},
writable: true,
configurable: true
},
canPileWith: {
// can this pile be merged with another?
value: function canPileWith(itemPile) {
if (itemPile.item !== this.item) {
return false;
}if (itemPile.count === 0 || this.count === 0) {
return true;
} // (special case: can always merge with 0-size pile of same item, regardless of tags - for placeholder slots)
if (itemPile.hasTags() || this.hasTags()) {
return false;
} // any tag data makes unpileable
return true;
},
writable: true,
configurable: true
},
mergePile: {
// combine two piles if possible, altering both this and argument pile
// returns count of items that didn't fit
value: function mergePile(itemPile) {
if (!this.canPileWith(itemPile)) {
return false;
}itemPile.count = this.increase(itemPile.count);
return itemPile.count;
},
writable: true,
configurable: true
},
increase: {
// increase count by argument, returning number of items that didn't fit
value: function increase(n) {
var _tryAdding = this.tryAdding(n);
var _tryAdding2 = _slicedToArray(_tryAdding, 2);
var newCount = _tryAdding2[0];
var excessCount = _tryAdding2[1];
this.count = newCount;
return excessCount;
},
writable: true,
configurable: true
},
decrease: {
// decrease count by argument, returning number of items removed
value: function decrease(n) {
var _trySubtracting = this.trySubtracting(n);
var _trySubtracting2 = _slicedToArray(_trySubtracting, 2);
var removedCount = _trySubtracting2[0];
var remainingCount = _trySubtracting2[1];
this.count = remainingCount;
return removedCount;
},
writable: true,
configurable: true
},
tryAdding: {
// try combining count of items up to max pile size, returns [newCount, excessCount]
value: function tryAdding(n) {
// special case: infinite incoming count sets pile to infinite, even though >maxPileSize
// TODO: option to disable infinite piles? might want to add only up to 64 etc. (ref GH-2)
if (n === Infinity) {
return [Infinity, 0];
}var sum = this.count + n;
if (sum > ItemPile.maxPileSize && this.count !== Infinity) {
// (special case: infinite destination piles never overflow)
return [ItemPile.maxPileSize, sum - ItemPile.maxPileSize]; // overflowing pile
} else {
return [sum, 0]; // added everything they wanted
}
},
writable: true,
configurable: true
},
trySubtracting: {
// try removing a finite count of items, returns [removedCount, remainingCount]
value: function trySubtracting(n) {
var difference = this.count - n;
if (difference < 0) {
return [this.count, n - this.count]; // didn't have enough
} else {
return [n, this.count - n]; // had enough, some remain
}
},
writable: true,
configurable: true
},
splitPile: {
// remove count of argument items, returning new pile of those items which were split off
value: function splitPile(n) {
if (n === 0) {
return false;
}if (n < 0) {
// negative count = all but n
n = this.count + n;
} else if (n < 1) {
// fraction = fraction
n = Math.ceil(this.count * n);
}
if (n > this.count) {
return false;
}if (n !== Infinity) this.count -= n; // (subtract, but avoid Infinity - Infinity = NaN)
return new ItemPile(this.item, n, cloneObject(this.tags, false));
},
writable: true,
configurable: true
},
toString: {
value: function toString() {
if (this.hasTags()) {
return "" + this.count + ":" + this.item + " " + JSON.stringify(this.tags);
} else {
return "" + this.count + ":" + this.item;
}
},
writable: true,
configurable: true
}
});
return ItemPile;
})();
module.exports = ItemPile;
},{"clone":75,"deep-equal":71}],75:[function(require,module,exports){
arguments[4][64][0].apply(exports,arguments)
},{"buffer":17,"dup":64}],76:[function(require,module,exports){
var Chest, ChestDialog, Inventory, InventoryDialog, InventoryWindow, ItemPile,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
InventoryDialog = (require('voxel-inventory-dialog')).InventoryDialog;
Inventory = require('inventory');
InventoryWindow = require('inventory-window');
ItemPile = require('itempile');
module.exports = function(game, opts) {
return new Chest(game, opts);
};
module.exports.pluginInfo = {
loadAfter: ['voxel-blockdata', 'voxel-registry', 'voxel-recipes', 'voxel-carry']
};
Chest = (function() {
function Chest(game1, opts) {
var ref, ref1, ref2, ref3;
this.game = game1;
this.playerInventory = (function() {
var ref1, ref2, ref3;
if ((ref = (ref1 = (ref2 = game.plugins) != null ? (ref3 = ref2.get('voxel-carry')) != null ? ref3.inventory : void 0 : void 0) != null ? ref1 : opts.playerInventory) != null) {
return ref;
} else {
throw new Error('voxel-chest requires "voxel-carry" plugin or "playerInventory" set to inventory instance');
}
})();
this.registry = (ref1 = game.plugins) != null ? ref1.get('voxel-registry') : void 0;
this.recipes = (ref2 = game.plugins) != null ? ref2.get('voxel-recipes') : void 0;
this.blockdata = (ref3 = game.plugins) != null ? ref3.get('voxel-blockdata') : void 0;
if (opts.registerBlock == null) {
opts.registerBlock = this.registry != null;
}
if (opts.registerRecipe == null) {
opts.registerRecipe = this.recipes != null;
}
if (this.game.isClient) {
this.chestDialog = new ChestDialog(game, this.playerInventory, this.registry, this.blockdata);
}
this.opts = opts;
this.enable();
}
Chest.prototype.enable = function() {
if (this.opts.registerBlock) {
this.registry.registerBlock('chest', {
texture: ['door_wood_lower', 'piston_top_normal', 'bookshelf'],
onInteract: (function(_this) {
return function(target) {
_this.chestDialog.open(target);
return true;
};
})(this)
});
}
if (this.opts.registerRecipe) {
return this.recipes.registerPositional([['wood.plank', 'wood.plank', 'wood.plank'], ['wood.plank', void 0, 'wood.plank'], ['wood.plank', 'wood.plank', 'wood.plank']], new ItemPile('chest', 1));
}
};
Chest.prototype.disable = function() {};
return Chest;
})();
ChestDialog = (function(superClass) {
extend(ChestDialog, superClass);
function ChestDialog(game1, playerInventory, registry, blockdata) {
var chestCont;
this.game = game1;
this.playerInventory = playerInventory;
this.registry = registry;
this.blockdata = blockdata;
this.chestInventory = new Inventory(10, 3);
this.chestInventory.on('changed', (function(_this) {
return function() {
return _this.updateBlockdata();
};
})(this));
this.chestIW = new InventoryWindow({
inventory: this.chestInventory,
registry: this.registry
});
this.chestIW.linkedInventory = this.playerInventory;
chestCont = this.chestIW.createContainer();
ChestDialog.__super__.constructor.call(this, game, {
playerLinkedInventory: this.chestInventory,
upper: [chestCont]
});
}
ChestDialog.prototype.loadBlockdata = function(x, y, z) {
var bd, i, itemPile, j, len, newInventory, ref;
if (this.blockdata == null) {
console.log('voxel-blockdata not loaded, voxel-chest persistence disabled');
return;
}
bd = this.blockdata.get(x, y, z);
console.log('activeBlockdata=', JSON.stringify(bd));
if (bd != null) {
console.log('load existing at ', x, y, z);
newInventory = Inventory.fromString(bd.inventory);
console.log('newInventory=' + JSON.stringify(newInventory));
ref = newInventory.array;
for (i = j = 0, len = ref.length; j < len; i = ++j) {
itemPile = ref[i];
console.log('load chest', i, itemPile);
this.chestInventory.set(i, itemPile);
}
} else {
console.log('new empty inventory at ', x, y, z);
bd = {
inventory: this.chestInventory.toString()
};
this.blockdata.set(x, y, z, bd);
}
this.activeBlockdata = bd;
return console.log('activeBlockdata 2=', JSON.stringify(this.activeBlockdata));
};
ChestDialog.prototype.open = function(target) {
var ref, x, y, z;
this.chestInventory.clear();
ref = target.voxel, x = ref[0], y = ref[1], z = ref[2];
this.loadBlockdata(x, y, z);
return ChestDialog.__super__.open.call(this);
};
ChestDialog.prototype.updateBlockdata = function() {
console.log('update with activeBlockdata=', JSON.stringify(this.activeBlockdata));
if (this.activeBlockdata == null) {
return;
}
console.log('chestInventory=', this.chestInventory.toString());
return this.activeBlockdata.inventory = this.chestInventory.toString();
};
ChestDialog.prototype.close = function() {
delete this.activeBlockdata;
return ChestDialog.__super__.close.call(this);
};
return ChestDialog;
})(InventoryDialog);
},{"inventory":83,"inventory-window":77,"itempile":87,"voxel-inventory-dialog":92}],77:[function(require,module,exports){
(function (global){
var CubeIcon, EventEmitter, InventoryWindow, createTooltip, ever, touchup,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty,
modulo = function(a, b) { return (+a % (b = +b) + b) % b; };
EventEmitter = (require('events')).EventEmitter;
ever = require('ever');
createTooltip = require('ftooltip');
CubeIcon = require('cube-icon');
touchup = require('touchup');
module.exports = InventoryWindow = (function(superClass) {
extend(InventoryWindow, superClass);
function InventoryWindow(opts) {
var ref, ref1, ref10, ref11, ref12, ref13, ref14, ref15, ref16, ref17, ref18, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9;
if (opts == null) {
opts = {};
}
this.inventory = (function() {
if ((ref = opts.inventory) != null) {
return ref;
} else {
throw 'inventory-window requires "inventory" option set to Inventory instance';
}
})();
this.linkedInventory = opts.linkedInventory;
this.getTexture = (ref1 = (ref2 = opts.getTexture) != null ? ref2 : InventoryWindow.defaultGetTexture) != null ? ref1 : global.InventoryWindow_defaultGetTexture;
this.registry = opts.registry;
if ((this.getTexture == null) && (this.registry == null)) {
throw 'inventory-window: required "getTexture" or "registry" option missing';
}
this.getMaxDamage = (ref3 = (ref4 = opts.getMaxDamage) != null ? ref4 : InventoryWindow.defaultGetMaxDamage) != null ? ref3 : global.InventoryWindow_defaultGetMaxDamage;
this.inventorySize = (ref5 = opts.inventorySize) != null ? ref5 : this.inventory.size();
this.width = (ref6 = opts.width) != null ? ref6 : this.inventory.width;
this.textureScale = (ref7 = opts.textureScale) != null ? ref7 : 5;
this.textureScaleAlgorithm = 'nearest-neighbor';
this.textureSrcPx = (ref8 = opts.textureSrcPx) != null ? ref8 : 16;
this.textureSize = (ref9 = opts.textureSize) != null ? ref9 : this.textureSrcPx * this.textureScale;
this.getTooltip = (ref10 = (ref11 = opts.getTooltip) != null ? ref11 : InventoryWindow.defaultGetTooltip) != null ? ref10 : global.InventoryWindow_defaultGetTooltip;
this.tooltips = (ref12 = opts.tooltips) != null ? ref12 : true;
this.borderSize = (ref13 = opts.borderSize) != null ? ref13 : 4;
this.progressThickness = (ref14 = opts.progressThickness) != null ? ref14 : 10;
this.secondaryMouseButton = (ref15 = opts.secondaryMouseButton) != null ? ref15 : 2;
this.allowDrop = (ref16 = opts.allowDrop) != null ? ref16 : true;
this.allowPickup = (ref17 = opts.allowPickup) != null ? ref17 : true;
this.allowDragPaint = (ref18 = opts.allowDragPaint) != null ? ref18 : true;
this.progressColorsThresholds = opts.progressColorsThresholds != null ? opts.progressColorsThresholds : opts.progressColorsThresholds = [0.20, 0.40, Infinity];
this.progressColors = opts.progressColors != null ? opts.progressColors : opts.progressColors = ['red', 'orange', 'green'];
this.slotNodes = [];
this.container = void 0;
this.selectedIndex = void 0;
this.enable();
}
InventoryWindow.prototype.enable = function() {
if (typeof document !== "undefined" && document !== null) {
ever(document).on('mousemove', (function(_this) {
return function(ev) {
if (!global.InventoryWindow_heldNode) {
return;
}
return _this.positionAtMouse(global.InventoryWindow_heldNode, ev);
};
})(this));
ever(document).on('mouseup', (function(_this) {
return function(ev) {
return global.InventoryWindow_mouseButtonDown = void 0;
};
})(this));
}
return this.inventory.on('changed', (function(_this) {
return function() {
return _this.refresh();
};
})(this));
};
InventoryWindow.prototype.createContainer = function() {
var container, i, j, node, ref, slotItem, widthpx;
if (typeof document === "undefined" || document === null) {
return;
}
container = document.createElement('div');
for (i = j = 0, ref = this.inventorySize; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
slotItem = this.inventory.get(i);
node = this.createSlotNode(slotItem);
this.setBorderStyle(node, i);
this.bindSlotNodeEvent(node, i);
this.slotNodes.push(node);
container.appendChild(node);
}
widthpx = this.width * (this.textureSize + this.borderSize * 2) + 2 * this.borderSize;
container.setAttribute('style', "display: block; float: left; width: " + widthpx + "px; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none;");
return this.container = container;
};
InventoryWindow.prototype.bindSlotNodeEvent = function(node, index) {
ever(node).on('mousedown', (function(_this) {
return function(ev) {
return _this.clickSlot(index, ev);
};
})(this));
return ever(node).on('mouseover', (function(_this) {
return function(ev) {
if (!_this.allowDragPaint) {
return;
}
if (!_this.allowDrop) {
return;
}
if (global.InventoryWindow_heldItemPile == null) {
return;
}
if (global.InventoryWindow_mouseButtonDown !== _this.secondaryMouseButton) {
return;
}
_this.dropOneHeld(index);
_this.createHeldNode(global.InventoryWindow_heldItemPile, ev);
return _this.refreshSlotNode(index);
};
})(this));
};
InventoryWindow.prototype.createSlotNode = function(itemPile) {
var div;
div = document.createElement('div');
div.setAttribute('style', "display: inline-block; float: inherit; margin: 0; padding: 0; width: " + this.textureSize + "px; height: " + this.textureSize + "px; font-size: 20pt; background-size: 100% auto; image-rendering: -moz-crisp-edges; image-rendering: -o-crisp-edges; image-rendering: -webkit-optimize-contrast; image-rendering: crisp-edges; -ms-interpolation-mode: nearest-neighbor;");
this.populateSlotNode(div, itemPile);
return div;
};
InventoryWindow.prototype.populateSlotNode = function(div, itemPile, isSelected) {
var cube, cubeNode, img, maxDamage, progress, progressColor, progressNode, ref, setImage, src, text, textBox, tooltip, tooltipNode, tooltipText;
src = void 0;
text = '';
progress = void 0;
progressColor = void 0;
if (itemPile != null) {
if (this.registry != null) {
src = this.registry.getItemPileTexture(itemPile);
} else if (this.getTexture != null) {
src = this.getTexture(itemPile);
} else {
throw 'inventory-window textures not specified, set global.InventoryWindow_defaultGetTexture or pass "getTexture" or "registry" option';
}
text = itemPile.count;
if (text === 1) {
text = '';
}
if (text === Infinity) {
text = '\u221e';
}
if (((ref = itemPile.tags) != null ? ref.damage : void 0) != null) {
if (this.registry != null) {
maxDamage = this.registry.getItemProps(itemPile.item).maxDamage;
} else if (this.getMaxDamage != null) {
maxDamage = this.getMaxDamage(itemPile);
} else {
maxDamage = 100;
}
progress = (maxDamage - itemPile.tags.damage) / maxDamage;
progressColor = this.getProgressBarColor(progress);
}
}
setImage = function(src) {
var newImage;
if (typeof src === 'string') {
newImage = 'url(' + src + ')';
} else {
newImage = '';
}
if (global.InventoryWindow_resolvedImageURLs == null) {
global.InventoryWindow_resolvedImageURLs = {};
}
if (global.InventoryWindow_resolvedImageURLs[newImage] !== div.style.backgroundImage) {
div.style.backgroundImage = newImage;
return global.InventoryWindow_resolvedImageURLs[newImage] = div.style.backgroundImage;
}
};
if ((this.textureScaleAlgorithm != null) && typeof src === 'string') {
if (global.InventoryWindow_cachedScaledImages == null) {
global.InventoryWindow_cachedScaledImages = {};
}
if (global.InventoryWindow_cachedScaledImages[src]) {
setImage(global.InventoryWindow_cachedScaledImages[src]);
} else {
img = new Image();
img.onload = (function(_this) {
return function() {
var scaled;
scaled = touchup.scale(img, _this.textureScale, _this.textureScale, _this.textureScaleAlgorithm);
global.InventoryWindow_cachedScaledImages[src] = scaled;
return setImage(scaled);
};
})(this);
img.src = src;
}
} else {
setImage(src);
}
cubeNode = div.children[0];
if (cubeNode == null) {
cubeNode = document.createElement('div');
cubeNode.setAttribute('style', 'position: relative; z-index: 0;');
div.appendChild(cubeNode);
}
while (cubeNode.firstChild) {
cubeNode.removeChild(cubeNode.firstChild);
}
if (Array.isArray(src) || typeof src === 'object') {
cube = new CubeIcon({
images: src
});
cubeNode.appendChild(cube.container);
}
textBox = div.children[1];
if (textBox == null) {
textBox = document.createElement('div');
textBox.setAttribute('style', 'position: absolute; text-shadow: 1px 1px #eee, -1px -1px #333;');
div.appendChild(textBox);
}
if (textBox.textContent !== text) {
textBox.textContent = text;
}
progressNode = div.children[2];
if (progressNode == null) {
progressNode = document.createElement('div');
progressNode.setAttribute('style', "width: 0%; top: " + (this.textureSize - this.borderSize * 2) + "px; position: relative; visibility: hidden;");
div.appendChild(progressNode);
}
if (progressColor != null) {
progressNode.style.borderTop = this.progressThickness + "px solid " + progressColor;
}
if (progress != null) {
progressNode.style.width = (progress * 100) + '%';
}
progressNode.style.visibility = progress != null ? '' : 'hidden';
if (this.tooltips) {
tooltipNode = div.children[3];
if (tooltipNode == null) {
tooltipNode = document.createTextNode('not set');
tooltip = createTooltip(div, tooltipNode);
div.appendChild(tooltip.div);
}
if (itemPile != null) {
if (this.registry != null) {
tooltipText = this.registry.getItemDisplayName(itemPile.item);
} else if (this.getTooltip != null) {
tooltipText = this.getTooltip(itemPile);
}
} else {
tooltipText = '';
}
return tooltipNode.textContent = tooltipText;
}
};
InventoryWindow.prototype.getProgressBarColor = function(progress) {
var i, j, len, ref, threshold;
ref = this.progressColorsThresholds;
for (i = j = 0, len = ref.length; j < len; i = ++j) {
threshold = ref[i];
if (progress <= threshold) {
return this.progressColors[i];
}
}
return this.progressColors.slice(-1)[0];
};
InventoryWindow.prototype.setBorderStyle = function(node, index) {
var height, kind, x, y;
x = modulo(index, this.width);
y = Math.floor(index / this.width);
height = this.inventorySize / this.width;
if (index === this.selectedIndex) {
kind = 'dotted';
} else {
kind = 'solid';
}
node.style.border = this.borderSize + "px " + kind + " black";
if (y === 0) {
node.style.borderTop = (this.borderSize * 2) + "px " + kind + " black";
}
if (y === height - 1) {
node.style.borderBottom = (this.borderSize * 2) + "px " + kind + " black";
}
if (x === 0) {
node.style.borderLeft = (this.borderSize * 2) + "px " + kind + " black";
}
if (x === this.width - 1) {
return node.style.borderRight = (this.borderSize * 2) + "px " + kind + " black";
}
};
InventoryWindow.prototype.setSelected = function(index) {
this.selectedIndex = index;
return this.refresh();
};
InventoryWindow.prototype.getSelected = function(index) {
return this.selectedIndex;
};
InventoryWindow.prototype.refreshSlotNode = function(index) {
this.populateSlotNode(this.slotNodes[index], this.inventory.get(index));
return this.setBorderStyle(this.slotNodes[index], index);
};
InventoryWindow.prototype.refresh = function() {
var i, j, ref, results;
results = [];
for (i = j = 0, ref = this.inventorySize; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
results.push(this.refreshSlotNode(i));
}
return results;
};
InventoryWindow.prototype.positionAtMouse = function(node, mouseEvent) {
var ref, ref1, x, y;
x = (ref = mouseEvent.x) != null ? ref : mouseEvent.clientX;
y = (ref1 = mouseEvent.y) != null ? ref1 : mouseEvent.clientY;
x -= this.textureSize / 2;
y -= this.textureSize / 2;
node.style.left = x + 'px';
return node.style.top = y + 'px';
};
InventoryWindow.prototype.createHeldNode = function(itemPile, ev) {
var style;
if (global.InventoryWindow_heldNode) {
this.removeHeldNode();
}
if (!itemPile || itemPile.count === 0) {
global.InventoryWindow_heldItemPile = void 0;
return;
}
global.InventoryWindow_heldItemPile = itemPile;
global.InventoryWindow_heldNode = this.createSlotNode(global.InventoryWindow_heldItemPile);
global.InventoryWindow_heldNode.setAttribute('style', style = global.InventoryWindow_heldNode.getAttribute('style') + "position: absolute; user-select: none; -moz-user-select: none; -webkit-user-select: none; pointer-events: none; z-index: 10;");
this.positionAtMouse(global.InventoryWindow_heldNode, ev);
return document.body.appendChild(global.InventoryWindow_heldNode);
};
InventoryWindow.prototype.removeHeldNode = function() {
global.InventoryWindow_heldNode.parentNode.removeChild(global.InventoryWindow_heldNode);
global.InventoryWindow_heldNode = void 0;
return global.InventoryWindow_heldItemPile = void 0;
};
InventoryWindow.prototype.dropOneHeld = function(index) {
var oneHeld, tmp;
if (this.inventory.get(index)) {
oneHeld = global.InventoryWindow_heldItemPile.splitPile(1);
if (this.inventory.get(index).mergePile(oneHeld) === false) {
global.InventoryWindow_heldItemPile.increase(1);
tmp = global.InventoryWindow_heldItemPile;
global.InventoryWindow_heldItemPile = this.inventory.get(index);
return this.inventory.set(index, tmp);
} else {
return this.inventory.changed();
}
} else {
return this.inventory.set(index, global.InventoryWindow_heldItemPile.splitPile(1));
}
};
InventoryWindow.prototype.clickSlot = function(index, ev) {
var itemPile, ref, ref1, shiftDown, tmp;
itemPile = this.inventory.get(index);
console.log('clickSlot', index, itemPile);
global.InventoryWindow_mouseButtonDown = ev.button;
shiftDown = ev.shiftKey;
if (ev.button !== this.secondaryMouseButton) {
if (!global.InventoryWindow_heldItemPile || !this.allowDrop) {
if (!this.allowPickup) {
return;
}
if (global.InventoryWindow_heldItemPile != null) {
if (this.inventory.get(index) != null) {
if (!global.InventoryWindow_heldItemPile.canPileWith(this.inventory.get(index))) {
return;
}
global.InventoryWindow_heldItemPile.mergePile(this.inventory.get(index));
}
} else {
if (!shiftDown) {
global.InventoryWindow_heldItemPile = this.inventory.get(index);
this.inventory.set(index, void 0);
} else if (this.linkedInventory && (this.inventory.get(index) != null)) {
this.linkedInventory.give(this.inventory.get(index));
if (this.inventory.get(index).count === 0) {
this.inventory.set(index, void 0);
}
this.inventory.changed();
}
}
this.emit('pickup');
} else {
if (this.inventory.get(index)) {
if (this.inventory.get(index).mergePile(global.InventoryWindow_heldItemPile) === false) {
tmp = global.InventoryWindow_heldItemPile;
global.InventoryWindow_heldItemPile = this.inventory.get(index);
this.inventory.set(index, tmp);
} else {
this.inventory.changed();
}
} else {
this.inventory.set(index, global.InventoryWindow_heldItemPile);
global.InventoryWindow_heldItemPile = void 0;
}
}
} else {
if (!global.InventoryWindow_heldItemPile) {
if (!this.allowPickup) {
return;
}
global.InventoryWindow_heldItemPile = (ref = this.inventory.get(index)) != null ? ref.splitPile(0.5) : void 0;
if (((ref1 = this.inventory.get(index)) != null ? ref1.count : void 0) === 0) {
this.inventory.set(index, void 0);
}
this.inventory.changed();
this.emit('pickup');
} else {
if (!this.allowDrop) {
return;
}
this.dropOneHeld(index);
}
}
this.createHeldNode(global.InventoryWindow_heldItemPile, ev);
return this.refreshSlotNode(index);
};
return InventoryWindow;
})(EventEmitter);
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"cube-icon":78,"events":21,"ever":48,"ftooltip":80,"touchup":82}],78:[function(require,module,exports){
var CubeIcon, expandName;
expandName = require('cube-side-array');
module.exports = function(opts) {
return new CubeIcon(opts);
};
CubeIcon = (function() {
function CubeIcon(opts) {
var ch, cubeH, cubeW, cw, dz, face, faceFilters, faceName, faceTransforms, i, j, len, ref, ref1, ref2, ref3, ref4, ref5, ref6, rotateX, rotateY, s, scale, shiftX, shiftY, showFaces;
if (opts == null) {
opts = {};
}
showFaces = (ref = opts.showFaces) != null ? ref : ['left', 'top', 'front'];
if (opts.images != null) {
ref1 = expandName(opts.images, 'KRLTBF'), opts.back = ref1[0], opts.right = ref1[1], opts.left = ref1[2], opts.top = ref1[3], opts.bottom = ref1[4], opts.front = ref1[5];
}
if (opts.side != null) {
opts.left = opts.front = opts.side;
}
rotateX = (ref2 = opts.rotateX) != null ? ref2 : -30;
rotateY = (ref3 = opts.rotateY) != null ? ref3 : 45;
scale = (ref4 = opts.scale) != null ? ref4 : 3.55;
s = (ref5 = opts.size) != null ? ref5 : 16;
this.container = document.createElement('div');
cw = ch = 90;
cubeW = Math.floor(ch / (1 - Math.sin(rotateX * Math.PI / 180)) - 2);
cubeH = Math.ceil(cw / (1 + Math.cos(rotateY * Math.PI / 180)) + 1);
shiftX = cw - s * scale - 5;
shiftY = ch - s * scale + 5;
this.container.setAttribute('style', "-webkit-transform: rotateX(" + rotateX + "deg) rotateY(" + rotateY + "deg) translateX(" + shiftX + "px) translateY(" + shiftY + "px) scale3d(" + scale + "," + scale + "," + scale + "); transform: rotateX(" + rotateX + "deg) rotateY(" + rotateY + "deg) translateX(" + shiftX + "px) translateY(" + shiftY + "px) scale3d(" + scale + "," + scale + "," + scale + "); -webkit-transform-origin: 0 0; transform-origin: 0 0; position: relative; -webkit-transform-style: preserve-3d; transform-style: preserve-3d;");
dz = s / 2;
faceTransforms = {
front: "rotateY( 0deg ) translateZ( " + dz + "px )",
back: "rotateX( 180deg ) translateZ( " + dz + "px )",
right: "rotateY( 90deg ) translateZ( " + dz + "px )",
left: "rotateY( -90deg ) translateZ( " + dz + "px )",
top: "rotateX( 90deg ) translateZ( " + dz + "px )",
bottom: "rotateX( -90deg ) translateZ( " + dz + "px )"
};
faceFilters = (ref6 = opts.faceFilters) != null ? ref6 : {
front: 'brightness(60%)',
left: 'brightness(100%)',
top: 'brightness(150%)'
};
for (i = j = 0, len = showFaces.length; j < len; i = ++j) {
faceName = showFaces[i];
face = document.createElement('div');
face.setAttribute('style', "-webkit-transform-style: preserve-3d; transform-style: preserve-3d; -webkit-transform: " + faceTransforms[faceName] + "; transform: " + faceTransforms[faceName] + "; position: absolute; border: 0.5px solid black; width: " + s + "px; height: " + s + "px;");
face.style.backgroundImage = 'url(' + opts[faceName] + ')';
if (faceFilters[faceName]) {
face.style.webkitFilter = faceFilters[faceName];
face.style.filter = faceFilters[faceName];
}
this.container.style.webkitTransition = '-webkit-transform 1s';
this.container.style.transition = ' transform 1s';
this.container.appendChild(face);
}
}
return CubeIcon;
})();
},{"cube-side-array":79}],79:[function(require,module,exports){
'use strict';
var expandName = function(name, order) {
var array = new Array(6);
// from voxel-mesher/ao-mesher -- also seen: 'KFTBLR' (voxel-texture), 'FKTBRL' (Mozilla's WebGL cube demo)
order = order || 'RTFLBK';
if (order.length !== 6) {
throw new Error('expandName invalid order length: ' + order);
}
var back = order.indexOf('K');
var front = order.indexOf('F');
var top = order.indexOf('T');
var bottom = order.indexOf('B');
var left = order.indexOf('L');
var right = order.indexOf('R');
if (back < 0 || front < 0 || top < 0 || bottom < 0 || left < 0 || right < 0) {
throw new Error('expandName invalid order: ' + order);
}
if (!name || name.length === 0) {
// empty
array[back] = array[front] = array[top] = array[bottom] = array[left] = array[right] = undefined;
} else if (name.top) {
// explicit names
array[back] = name.back;
array[front] = name.front;
array[top] = name.top;
array[bottom] = name.bottom;
array[left] = name.left;
array[right] = name.right;
} else if (!Array.isArray(name)) {
// scalar is all
array[back] = array[front] = array[top] = array[bottom] = array[left] = array[right] = name;
} else if (name.length === 1) {
// 0 is all
array[back] = array[front] = array[top] = array[bottom] = array[left] = array[right] = name[0];
} else if (name.length === 2) {
// 0 is top/bottom, 1 is sides
array[back] = array[front] = array[left] = array[right] = name[1];
array[top] = array[bottom] = name[0];
} else if (name.length === 3) {
// 0 is top, 1 is bottom, 2 is sides
array[back] = array[front] = array[left] = array[right] = name[2];
array[top] = name[0];
array[bottom] = name[1];
} else if (name.length === 4) {
// 0 is top, 1 is bottom, 2 is front/back, 3 is left/right
array[back] = array[front] = name[2];
array[top] = name[0];
array[bottom] = name[1];
array[left] = array[right] = name[3];
} else if (name.length === 5) {
// 0 is top, 1 is bottom, 2 is front, 3 is back, 4 is left/right
array[back] = name[3];
array[front] = name[2];
array[top] = name[0];
array[bottom] = name[1];
array[left] = array[right] = name[4];
} else if (name.length === 6) {
throw new Error('expandName('+name+'): 6-element array support removed, use objects instead ({back:, front:, top:, bottom:, left:, right:...})');
} else {
throw new Error('expandName('+name+'): invalid side count array length '+name.length);
}
return array;
};
module.exports = expandName;
},{}],80:[function(require,module,exports){
(function (global){
'use strict';
var toarray = require('toarray');
module.exports = function(node, opts) {
return new Tooltip(node, opts);
};
function Tooltip(node, opts) {
this.node = node;
if (typeof opts === 'string' || Array.isArray(opts) || opts instanceof Element || opts instanceof DocumentFragment || opts instanceof Text) {
// shortcut
opts = {info: opts};
}
this.info = toarray(opts.info) || [];
this.style = opts.style || [
'position: fixed;',
'background-color: black;',
'pointer-events: none;',
'color: white;',
'z-index: 20;',
'visibility: hidden;',
opts.extraStyle || '',
].join('\n');
this.cachedDivHeights = [];
this.enable();
}
Tooltip.prototype.enable = function() {
this.create();
this.node.addEventListener('mouseenter', this.onMouseenter = this.show.bind(this));
this.node.addEventListener('mouseleave', this.onMouseleave = this.hide.bind(this));
};
Tooltip.prototype.disable = function() {
this.node.removeEventListener('mouseenter', this.onMouseenter);
this.node.removeEventListener('mouseleave', this.onMouseleave);
if (this.div) {
this.div.parentNode.removeChild(this.div);
delete this.div;
}
};
Tooltip.prototype.create = function() {
this.div = document.createElement('div');
this.div.setAttribute('style', this.style);
var stringLines = 0;
for (var i = 0; i < this.info.length; i += 1) {
var line = this.info[i];
if (typeof line === 'string') {
this.div.appendChild(document.createTextNode(line));
stringLines += 1;
} else if (line instanceof Element || line instanceof DocumentFragment || line instanceof Text) {
this.div.appendChild(line);
if (line instanceof Text) stringLines += 1;
} else {
this.div.appendChild(document.createTextNode(''+line));
}
}
document.body.appendChild(this.div);
// cache clientHeight calculation because it is very slow
if (stringLines === this.info.length) {
// and cache string-only tooltip heights for even better performance (should be all the same)
if (!global.ftooltip_cachedDivHeights) global.ftooltip_cachedDivHeights = [];
this.divHeight = global.ftooltip_cachedDivHeights[stringLines] || this.div.clientHeight;
global.ftooltip_cachedDivHeights[stringLines] = this.divHeight;
} else {
this.divHeight = this.div.clientHeight;
}
this.div.style.display = 'none';
}
Tooltip.prototype.show = function(ev) {
this.div.style.display = 'block';
this.div.style.visibility = '';
this.move(ev.x, ev.y);
this.node.addEventListener('mousemove', this.onMousemove = this.track.bind(this));
};
Tooltip.prototype.track = function(ev) {
this.move(ev.x, ev.y);
}
Tooltip.prototype.move = function(x, y) {
this.div.style.left = x + 'px';
this.div.style.top = (y - this.divHeight) + 'px';
};
Tooltip.prototype.hide = function() {
this.div.style.display = 'none';
this.div.style.visibility = 'hidden';
this.node.removeEventListener('mousemove', this.onMousemove);
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"toarray":81}],81:[function(require,module,exports){
module.exports = function(item) {
if(item === undefined) return [];
return Object.prototype.toString.call(item) === "[object Array]" ? item : [item];
}
},{}],82:[function(require,module,exports){
// Generated by CoffeeScript 1.7.0
(function() {
var createCanvas, crop, overallSize, overlay, repeat, scale;
createCanvas = function(w, h) {
var canvas, context;
canvas = document.createElement('canvas');
canvas.setAttribute('width', w);
canvas.setAttribute('height', h);
context = canvas.getContext('2d');
return [canvas, context];
};
repeat = function(sourceImage, timesX, timesY) {
var canvas, context, destH, destW, pattern, _ref;
destW = sourceImage.width * timesX;
destH = sourceImage.height * timesY;
_ref = createCanvas(destW, destH), canvas = _ref[0], context = _ref[1];
pattern = context.createPattern(sourceImage, 'repeat');
context.fillStyle = pattern;
context.fillRect(0, 0, destW, destH);
return canvas.toDataURL();
};
scale = function(sourceImage, scaleX, scaleY, algorithm) {
var canvas, context, destH, destW, _ref;
destW = sourceImage.width * scaleX;
destH = sourceImage.width * scaleY;
_ref = createCanvas(destW, destH), canvas = _ref[0], context = _ref[1];
if (algorithm === 'nearest-neighbor') {
context.imageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.mozImageSmoothingEnabled = false;
}
context.drawImage(sourceImage, 0, 0, destW, destH);
return canvas.toDataURL();
};
crop = function(sourceImage, ox, oy, ow, oh) {
var canvas, context, destH, destW, sh, sw, sx, sy, _ref;
sx = ox || 0;
sy = oy || 0;
destW = sourceImage.width - (ow || 0) - sx;
destH = sourceImage.height - (oh || 0) - sy;
sw = destW;
sh = destH;
_ref = createCanvas(destW, destH), canvas = _ref[0], context = _ref[1];
console.log(sx, sy, sw, sh, 0, 0, destW, destH);
context.drawImage(sourceImage, sx, sy, sw, sh, 0, 0, destW, destH);
return canvas.toDataURL();
};
overallSize = function(sourceImages) {
var destH, destW, sourceImage, _i, _len;
destW = destH = 0;
for (_i = 0, _len = sourceImages.length; _i < _len; _i++) {
sourceImage = sourceImages[_i];
if (sourceImage.width > destW) {
destW = sourceImage.width;
}
if (sourceImage.height > destH) {
destH = sourceImage.height;
}
}
return [destW, destH];
};
overlay = function(sourceImages, operation, alpha) {
var canvas, context, destH, destW, sourceImage, _i, _len, _ref, _ref1;
_ref = overallSize(sourceImages), destW = _ref[0], destH = _ref[1];
_ref1 = createCanvas(destW, destH), canvas = _ref1[0], context = _ref1[1];
context.globalAlpha = alpha != null ? alpha : 1.0;
context.globalCompositeOperation = operation != null ? operation : 'source-over';
for (_i = 0, _len = sourceImages.length; _i < _len; _i++) {
sourceImage = sourceImages[_i];
context.drawImage(sourceImage, 0, 0);
}
return canvas.toDataURL();
};
module.exports = {
repeat: repeat,
scale: scale,
crop: crop,
overlay: overlay
};
}).call(this);
},{}],83:[function(require,module,exports){
var EventEmitter, Inventory, ItemPile, deepEqual,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
deepEqual = require('deep-equal');
ItemPile = require('itempile');
EventEmitter = (require('events')).EventEmitter;
module.exports = Inventory = (function(superClass) {
extend(Inventory, superClass);
function Inventory(xSize, ySize, opts) {
var size;
if (xSize == null) {
xSize = 10;
}
if (ySize == null) {
ySize = 1;
}
if (xSize <= 0) {
throw new Error("inventory invalid xSize: " + xSize);
}
if (ySize <= 0) {
throw new Error("inventory invalid xSize: " + ySize);
}
size = xSize * ySize;
this.array = new Array(size);
this.width = xSize;
this.height = ySize;
}
Inventory.prototype.changed = function() {
return this.emit('changed');
};
Inventory.prototype.give = function(itemPile) {
var excess, i, j, k, ref, ref1;
excess = itemPile.count;
for (i = j = 0, ref = this.array.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
if ((this.array[i] != null) && this.array[i].canPileWith(itemPile)) {
excess = this.array[i].mergePile(itemPile);
}
if (itemPile.count === 0) {
break;
}
}
for (i = k = 0, ref1 = this.array.length; 0 <= ref1 ? k < ref1 : k > ref1; i = 0 <= ref1 ? ++k : --k) {
if (this.array[i] == null) {
this.array[i] = itemPile.clone();
this.array[i].count = 0;
excess = this.array[i].mergePile(itemPile);
if (this.array[i].count === 0) {
this.array[i] = void 0;
}
}
if (itemPile.count === 0) {
break;
}
}
this.changed();
return excess;
};
Inventory.prototype.take = function(itemPile) {
var given, i, j, n, ref;
for (i = j = 0, ref = this.array.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
if ((this.array[i] != null) && this.array[i].matchesTypeAndTags(itemPile)) {
n = Math.min(itemPile.count, this.array[i].count);
itemPile.count -= n;
given = this.takeAt(i, n);
}
}
return this.changed();
};
Inventory.prototype.takeAt = function(position, count) {
var ret;
if (!this.array[position]) {
return false;
}
ret = this.array[position].splitPile(count);
if (this.array[position].count === 0) {
this.array[position] = void 0;
}
this.changed();
return ret;
};
Inventory.prototype.toString = function() {
var a, i, itemPile, j, len, ref;
a = [];
ref = this.array;
for (i = j = 0, len = ref.length; j < len; i = ++j) {
itemPile = ref[i];
if (itemPile == null) {
a.push('');
} else {
a.push("" + itemPile);
}
}
return a.join('\t');
};
Inventory.fromString = function(s) {
var items, ret, strings;
strings = s.split('\t');
items = (function() {
var j, len, results;
results = [];
for (j = 0, len = strings.length; j < len; j++) {
s = strings[j];
results.push(ItemPile.fromString(s));
}
return results;
})();
ret = new Inventory(items.length);
ret.array = items;
return ret;
};
Inventory.prototype.size = function() {
return this.array.length;
};
Inventory.prototype.get = function(i) {
return this.array[i];
};
Inventory.prototype.set = function(i, itemPile) {
this.array[i] = itemPile;
return this.changed();
};
Inventory.prototype.clear = function() {
var i, j, ref, results;
results = [];
for (i = j = 0, ref = this.size(); 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
results.push(this.set(i, void 0));
}
return results;
};
Inventory.prototype.transferTo = function(dest) {
var i, j, ref, results;
results = [];
for (i = j = 0, ref = this.size(); 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
dest.set(i, this.get(i));
results.push(this.set(i, void 0));
}
return results;
};
return Inventory;
})(EventEmitter);
},{"deep-equal":84,"events":21,"itempile":87}],84:[function(require,module,exports){
arguments[4][65][0].apply(exports,arguments)
},{"./lib/is_arguments.js":85,"./lib/keys.js":86,"dup":65}],85:[function(require,module,exports){
arguments[4][66][0].apply(exports,arguments)
},{"dup":66}],86:[function(require,module,exports){
arguments[4][67][0].apply(exports,arguments)
},{"dup":67}],87:[function(require,module,exports){
"use strict";
var _slicedToArray = function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } };
var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
var deepEqual = require("deep-equal");
var cloneObject = require("clone");
var ItemPile = (function () {
function ItemPile(item) {
var count = arguments[1] === undefined ? 1 : arguments[1];
var tags = arguments[2] === undefined ? {} : arguments[2];
_classCallCheck(this, ItemPile);
this.item = typeof item === "string" ? ItemPile.itemFromString(item) : item;
this.count = count;
this.tags = tags;
}
_prototypeProperties(ItemPile, {
maxPileSize: {
// maximum size items should pile
get: function () {
return 64;
},
configurable: true
},
itemFromString: {
// convert item<->string; change these to use non-string items
value: function itemFromString(s) {
if (s instanceof ItemPile) {
return s;
}return !s ? "" : s;
},
writable: true,
configurable: true
},
itemToString: {
value: function itemToString(item) {
return "" + item;
},
writable: true,
configurable: true
},
fromString: {
value: function fromString(s) {
var a = s.match(/^([^:]+):([^ ]+) ?(.*)/); // assumptions: positive integral count, item name no spaces
if (!a) {
return undefined;
}
var _a = _slicedToArray(a, 4);
var _ = _a[0];
var countStr = _a[1];
var itemStr = _a[2];
var tagsStr = _a[3];
var count = undefined;
if (countStr === "Infinity") {
count = Infinity;
} else {
count = parseInt(countStr, 10);
}
var item = ItemPile.itemFromString(itemStr);
var tags = undefined;
if (tagsStr && tagsStr.length) {
tags = JSON.parse(tagsStr);
} else {
tags = {};
}
return new ItemPile(item, count, tags);
},
writable: true,
configurable: true
},
fromArray: {
value: function fromArray(_ref) {
var _ref2 = _slicedToArray(_ref, 3);
var item = _ref2[0];
var count = _ref2[1];
var tags = _ref2[2];
return new ItemPile(item, count, tags);
},
writable: true,
configurable: true
},
fromArrayIfArray: {
value: function fromArrayIfArray(a) {
if (Array.isArray(a)) {
return ItemPile.fromArray(a);
} else {
return a;
}
},
writable: true,
configurable: true
}
}, {
clone: {
value: function clone() {
return new ItemPile(this.item, this.count, cloneObject(this.tags, false));
},
writable: true,
configurable: true
},
hasTags: {
value: function hasTags() {
return Object.keys(this.tags).length !== 0; // not "{}"
},
writable: true,
configurable: true
},
matchesType: {
value: function matchesType(itemPile) {
return this.item === itemPile.item;
},
writable: true,
configurable: true
},
matchesTypeAndCount: {
value: function matchesTypeAndCount(itemPile) {
return this.item === itemPile.item && this.count === itemPile.count;
},
writable: true,
configurable: true
},
matchesTypeAndTags: {
value: function matchesTypeAndTags(itemPile) {
return this.item === itemPile.item && deepEqual(this.tags, itemPile.tags, { strict: true });
},
writable: true,
configurable: true
},
matchesAll: {
value: function matchesAll(itemPile) {
return this.matchesTypeAndCount(itemPile) && deepEqual(this.tags, itemPile.tags, { strict: true });
},
writable: true,
configurable: true
},
canPileWith: {
// can this pile be merged with another?
value: function canPileWith(itemPile) {
if (itemPile.item !== this.item) {
return false;
}if (itemPile.count === 0 || this.count === 0) {
return true;
} // (special case: can always merge with 0-size pile of same item, regardless of tags - for placeholder slots)
if (itemPile.hasTags() || this.hasTags()) {
return false;
} // any tag data makes unpileable
return true;
},
writable: true,
configurable: true
},
mergePile: {
// combine two piles if possible, altering both this and argument pile
// returns count of items that didn't fit
value: function mergePile(itemPile) {
if (!this.canPileWith(itemPile)) {
return false;
}itemPile.count = this.increase(itemPile.count);
return itemPile.count;
},
writable: true,
configurable: true
},
increase: {
// increase count by argument, returning number of items that didn't fit
value: function increase(n) {
var _tryAdding = this.tryAdding(n);
var _tryAdding2 = _slicedToArray(_tryAdding, 2);
var newCount = _tryAdding2[0];
var excessCount = _tryAdding2[1];
this.count = newCount;
return excessCount;
},
writable: true,
configurable: true
},
decrease: {
// decrease count by argument, returning number of items removed
value: function decrease(n) {
var _trySubtracting = this.trySubtracting(n);
var _trySubtracting2 = _slicedToArray(_trySubtracting, 2);
var removedCount = _trySubtracting2[0];
var remainingCount = _trySubtracting2[1];
this.count = remainingCount;
return removedCount;
},
writable: true,
configurable: true
},
tryAdding: {
// try combining count of items up to max pile size, returns [newCount, excessCount]
value: function tryAdding(n) {
// special case: infinite incoming count sets pile to infinite, even though >maxPileSize
// TODO: option to disable infinite piles? might want to add only up to 64 etc. (ref GH-2)
if (n === Infinity) {
return [Infinity, 0];
}var sum = this.count + n;
if (sum > ItemPile.maxPileSize && this.count !== Infinity) {
// (special case: infinite destination piles never overflow)
return [ItemPile.maxPileSize, sum - ItemPile.maxPileSize]; // overflowing pile
} else {
return [sum, 0]; // added everything they wanted
}
},
writable: true,
configurable: true
},
trySubtracting: {
// try removing a finite count of items, returns [removedCount, remainingCount]
value: function trySubtracting(n) {
var difference = this.count - n;
if (difference < 0) {
return [this.count, n - this.count]; // didn't have enough
} else {
return [n, this.count - n]; // had enough, some remain
}
},
writable: true,
configurable: true
},
splitPile: {
// remove count of argument items, returning new pile of those items which were split off
value: function splitPile(n) {
if (n === 0) {
return false;
}if (n < 0) {
// negative count = all but n
n = this.count + n;
} else if (n < 1) {
// fraction = fraction
n = Math.ceil(this.count * n);
}
if (n > this.count) {
return false;
}if (n !== Infinity) this.count -= n; // (subtract, but avoid Infinity - Infinity = NaN)
return new ItemPile(this.item, n, cloneObject(this.tags, false));
},
writable: true,
configurable: true
},
toString: {
value: function toString() {
if (this.hasTags()) {
return "" + this.count + ":" + this.item + " " + JSON.stringify(this.tags);
} else {
return "" + this.count + ":" + this.item;
}
},
writable: true,
configurable: true
}
});
return ItemPile;
})();
module.exports = ItemPile;
},{"clone":88,"deep-equal":89}],88:[function(require,module,exports){
arguments[4][64][0].apply(exports,arguments)
},{"buffer":17,"dup":64}],89:[function(require,module,exports){
arguments[4][65][0].apply(exports,arguments)
},{"./lib/is_arguments.js":90,"./lib/keys.js":91,"dup":65}],90:[function(require,module,exports){
arguments[4][66][0].apply(exports,arguments)
},{"dup":66}],91:[function(require,module,exports){
arguments[4][67][0].apply(exports,arguments)
},{"dup":67}],92:[function(require,module,exports){
var Inventory, InventoryDialog, InventoryWindow, ItemPile, ModalDialog,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Inventory = require('inventory');
InventoryWindow = require('inventory-window');
ItemPile = require('itempile');
ModalDialog = require('voxel-modal-dialog');
module.exports = function(game, opts) {
return new InventoryDialog(game, opts);
};
module.exports.pluginInfo = {
'loadAfter': ['voxel-recipes', 'voxel-carry', 'voxel-registry']
};
module.exports.InventoryDialog = InventoryDialog = (function(superClass) {
extend(InventoryDialog, superClass);
function InventoryDialog(game1, opts) {
var contents, element, i, len, ref, ref1, ref2, ref3;
this.game = game1;
if (!this.game.isClient) {
return;
}
this.registry = (function() {
var ref1;
if ((ref = (ref1 = game.plugins) != null ? ref1.get('voxel-registry') : void 0) != null) {
return ref;
} else {
throw new Error('voxel-inventory-dialog requires "voxel-registry" plugin');
}
})();
this.playerInventory = (function() {
var ref2, ref3, ref4;
if ((ref1 = (ref2 = (ref3 = game.plugins) != null ? (ref4 = ref3.get('voxel-carry')) != null ? ref4.inventory : void 0 : void 0) != null ? ref2 : opts.playerInventory) != null) {
return ref1;
} else {
throw new Error('voxel-inventory-dialog requires "voxel-carry" plugin or playerInventory" set to inventory instance');
}
})();
this.playerIW = new InventoryWindow({
inventory: this.playerInventory,
registry: this.registry,
linkedInventory: opts.playerLinkedInventory
});
this.upper = document.createElement('div');
ref3 = (ref2 = opts.upper) != null ? ref2 : [];
for (i = 0, len = ref3.length; i < len; i++) {
element = ref3[i];
this.upper.appendChild(element);
}
contents = [];
contents.push(this.upper);
contents.push(document.createElement('br'));
contents.push(this.playerIW.createContainer());
InventoryDialog.__super__.constructor.call(this, game, {
contents: contents,
escapeKeys: [192, 69]
});
}
InventoryDialog.prototype.enable = function() {};
InventoryDialog.prototype.disable = function() {};
return InventoryDialog;
})(ModalDialog);
},{"inventory":83,"inventory-window":77,"itempile":87,"voxel-modal-dialog":93}],93:[function(require,module,exports){
arguments[4][58][0].apply(exports,arguments)
},{"dup":58,"voxel-modal":94}],94:[function(require,module,exports){
arguments[4][59][0].apply(exports,arguments)
},{"dup":59,"ever":48}],95:[function(require,module,exports){
'use strict';
var createBuffer = require('gl-buffer');
var createVAO = require('gl-vao');
var createSimpleShader = require('simple-3d-shader');
module.exports = function(game, opts) {
return new BorderPlugin(game, opts);
};
module.exports.pluginInfo = {
loadAfter: ['voxel-mesher', 'voxel-shader', 'voxel-keys'],
clientOnly: true
};
function BorderPlugin(game, opts) {
this.game = game;
this.shell = game.shell;
this.mesherPlugin = game.plugins.get('voxel-mesher');
if (!this.mesherPlugin) throw new Error('voxel-chunkborder requires voxel-mesher');
this.shaderPlugin = game.plugins.get('voxel-shader');
if (!this.shaderPlugin) throw new Error('voxel-chunkborder requires voxel-shader');
this.keysPlugin = game.plugins.get('voxel-keys'); // optional
this.showBorders = opts.showBorder !== undefined ? opts.showBorders : false; // also changed at runtime
this.colorVector = opts.color !== undefined ? opts.color : [0,0,1]; // blue, RGB TODO: convert from hex?
this.enable();
}
BorderPlugin.prototype.enable = function() {
this.shell.bind('chunkborder', 'F9');
if (this.keysPlugin) this.keysPlugin.down.on('chunkborder', this.onToggle = this.toggle.bind(this));
this.shell.on('gl-init', this.onInit = this.shaderInit.bind(this));
this.shell.on('gl-render', this.onRender = this.render.bind(this));
this.mesherPlugin.on('meshed', this.onMeshed = this.createBorderMesh.bind(this));
};
BorderPlugin.prototype.disable = function() {
this.mesherPlugin.removeListener('meshed', this.onMeshed);
this.shell.removeListener('gl-render', this.onRender);
this.shell.removeListener('gl-init', this.onInit);
this.shell.unbind('chunkborder');
if (this.keysPlugin) this.keysPlugin.down.removeListener('chunkborder', this.onToggle);
};
BorderPlugin.prototype.toggle = function(ev) {
if (ev && ev.shiftKey) return; // skip since voxel-wireframe wants Shift+F9
this.showBorders = !this.showBorders;
};
BorderPlugin.prototype.shaderInit = function() {
this.borderShader = createSimpleShader(this.shell.gl);
};
BorderPlugin.prototype.render = function() {
if (this.showBorders) {
var gl = this.shell.gl;
//gl.disable(gl.DEPTH_TEST); // TODO: ? if disable, too noisy, see through everything. maybe show differently?
this.borderShader.bind();
this.borderShader.attributes.position.location = 0;
this.borderShader.uniforms.projection = this.shaderPlugin.projectionMatrix;
this.borderShader.uniforms.view = this.shaderPlugin.viewMatrix;
this.borderShader.attributes.color = this.colorVector;
for (var chunkIndex in this.game.voxels.meshes) {
var mesh = this.game.voxels.meshes[chunkIndex];
this.borderShader.uniforms.model = mesh.modelMatrix;
var borderVAO = mesh.vertexArrayObjects.chunkborder;
borderVAO.bind();
borderVAO.draw(gl.LINES, borderVAO.length);
borderVAO.unbind();
}
}
};
// Create the mesh around each chunk
// useful references:
// https://github.com/deathcap/voxel-wireframe
// https://github.com/hughsk/indexed-geometry-demo
// https://github.com/deathcap/avatar
BorderPlugin.prototype.createBorderMesh = function(mesh, gl, _vert_data, voxels) {
var w = this.game.chunkSize;
var borderVertexArray = new Uint8Array([
0,0,0,
0,0,w,
0,w,0,
0,w,w,
w,0,0,
w,0,w,
w,w,0,
w,w,w
]);
var indexArray = new Uint16Array([
0,1, 0,2, 2,3, 3,1,
0,4, 4,5, 5,1,
5,7, 7,3,
7,6, 6,2,
6,4
]);
var borderVertexCount = indexArray.length;
var borderBuf = createBuffer(gl, borderVertexArray);
var indexBuf = createBuffer(gl, indexArray, gl.ELEMENT_ARRAY_BUFFER);
var borderVAO = createVAO(gl, [
{ buffer: borderBuf,
type: gl.UNSIGNED_BYTE,
size: 3
}], indexBuf);
borderVAO.length = borderVertexCount
mesh.vertexArrayObjects.chunkborder = borderVAO
};
},{"gl-buffer":96,"gl-vao":114,"simple-3d-shader":115}],96:[function(require,module,exports){
"use strict"
var pool = require("typedarray-pool")
var ops = require("ndarray-ops")
var ndarray = require("ndarray")
var webglew = require("webglew")
var SUPPORTED_TYPES = [
"uint8",
"uint8_clamped",
"uint16",
"uint32",
"int8",
"int16",
"int32",
"float32" ]
function GLBuffer(gl, type, handle, length, usage) {
this.gl = gl
this.type = type
this.handle = handle
this.length = length
this.usage = usage
}
var proto = GLBuffer.prototype
proto.bind = function() {
this.gl.bindBuffer(this.type, this.handle)
}
proto.unbind = function() {
this.gl.bindBuffer(this.type, null)
}
proto.dispose = function() {
this.gl.deleteBuffer(this.handle)
}
function updateTypeArray(gl, type, len, usage, data, offset) {
var dataLen = data.length * data.BYTES_PER_ELEMENT
if(offset < 0) {
gl.bufferData(type, data, usage)
return dataLen
}
if(dataLen + offset > len) {
throw new Error("gl-buffer: If resizing buffer, must not specify offset")
}
gl.bufferSubData(type, offset, data)
return len
}
function makeScratchTypeArray(array, dtype) {
var res = pool.malloc(array.length, dtype)
var n = array.length
for(var i=0; i<n; ++i) {
res[i] = array[i]
}
return res
}
function isPacked(shape, stride) {
var n = 1
for(var i=stride.length-1; i>=0; --i) {
if(stride[i] !== n) {
return false
}
n *= shape[i]
}
return true
}
proto.update = function(array, offset) {
if(typeof offset !== "number") {
offset = -1
}
this.bind()
if(typeof array === "object" && typeof array.shape !== "undefined") { //ndarray
var dtype = array.dtype
if(SUPPORTED_TYPES.indexOf(dtype) < 0) {
dtype = "float32"
}
if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) {
var wgl = webglew(this.gl)
var ext = wgl.OES_element_index_uint
if(ext && dtype !== "uint16") {
dtype = "uint32"
} else {
dtype = "uint16"
}
}
if(dtype === array.dtype && isPacked(array.shape, array.stride)) {
if(array.offset === 0 && array.data.length === array.shape[0]) {
this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data, offset)
} else {
this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data.subarray(array.offset, array.shape[0]), offset)
}
} else {
var tmp = pool.malloc(array.size, dtype)
var ndt = ndarray(tmp, array.shape)
ops.assign(ndt, array)
if(offset < 0) {
this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp, offset)
} else {
this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp.subarray(0, array.size), offset)
}
pool.free(tmp)
}
} else if(Array.isArray(array)) { //Vanilla array
var t
if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) {
t = makeScratchTypeArray(array, "uint16")
} else {
t = makeScratchTypeArray(array, "float32")
}
if(offset < 0) {
this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t, offset)
} else {
this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t.subarray(0, array.length), offset)
}
pool.free(t)
} else if(typeof array === "object" && typeof array.length === "number") { //Typed array
this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array, offset)
} else if(typeof array === "number" || array === undefined) { //Number/default
if(offset >= 0) {
throw new Error("gl-buffer: Cannot specify offset when resizing buffer")
}
array = array | 0
if(array <= 0) {
array = 1
}
this.gl.bufferData(this.type, array|0, this.usage)
this.length = array
} else { //Error, case should not happen
throw new Error("gl-buffer: Invalid data type")
}
}
function createBuffer(gl, data, type, usage) {
webglew(gl)
type = type || gl.ARRAY_BUFFER
usage = usage || gl.DYNAMIC_DRAW
if(type !== gl.ARRAY_BUFFER && type !== gl.ELEMENT_ARRAY_BUFFER) {
throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER")
}
if(usage !== gl.DYNAMIC_DRAW && usage !== gl.STATIC_DRAW && usage !== gl.STREAM_DRAW) {
throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW")
}
var handle = gl.createBuffer()
var result = new GLBuffer(gl, type, handle, 0, usage)
result.update(data)
return result
}
module.exports = createBuffer
},{"ndarray":102,"ndarray-ops":97,"typedarray-pool":106,"webglew":108}],97:[function(require,module,exports){
"use strict"
var compile = require("cwise-compiler")
var EmptyProc = {
body: "",
args: [],
thisVars: [],
localVars: []
}
function fixup(x) {
if(!x) {
return EmptyProc
}
for(var i=0; i<x.args.length; ++i) {
var a = x.args[i]
if(i === 0) {
x.args[i] = {name: a, lvalue:true, rvalue: !!x.rvalue, count:x.count||1 }
} else {
x.args[i] = {name: a, lvalue:false, rvalue:true, count: 1}
}
}
if(!x.thisVars) {
x.thisVars = []
}
if(!x.localVars) {
x.localVars = []
}
return x
}
function pcompile(user_args) {
return compile({
args: user_args.args,
pre: fixup(user_args.pre),
body: fixup(user_args.body),
post: fixup(user_args.proc),
funcName: user_args.funcName
})
}
function makeOp(user_args) {
var args = []
for(var i=0; i<user_args.args.length; ++i) {
args.push("a"+i)
}
var wrapper = new Function("P", [
"return function ", user_args.funcName, "_ndarrayops(", args.join(","), ") {P(", args.join(","), ");return a0}"
].join(""))
return wrapper(pcompile(user_args))
}
var assign_ops = {
add: "+",
sub: "-",
mul: "*",
div: "/",
mod: "%",
band: "&",
bor: "|",
bxor: "^",
lshift: "<<",
rshift: ">>",
rrshift: ">>>"
}
;(function(){
for(var id in assign_ops) {
var op = assign_ops[id]
exports[id] = makeOp({
args: ["array","array","array"],
body: {args:["a","b","c"],
body: "a=b"+op+"c"},
funcName: id
})
exports[id+"eq"] = makeOp({
args: ["array","array"],
body: {args:["a","b"],
body:"a"+op+"=b"},
rvalue: true,
funcName: id+"eq"
})
exports[id+"s"] = makeOp({
args: ["array", "array", "scalar"],
body: {args:["a","b","s"],
body:"a=b"+op+"s"},
funcName: id+"s"
})
exports[id+"seq"] = makeOp({
args: ["array","scalar"],
body: {args:["a","s"],
body:"a"+op+"=s"},
rvalue: true,
funcName: id+"seq"
})
}
})();
var unary_ops = {
not: "!",
bnot: "~",
neg: "-",
recip: "1.0/"
}
;(function(){
for(var id in unary_ops) {
var op = unary_ops[id]
exports[id] = makeOp({
args: ["array", "array"],
body: {args:["a","b"],
body:"a="+op+"b"},
funcName: id
})
exports[id+"eq"] = makeOp({
args: ["array"],
body: {args:["a"],
body:"a="+op+"a"},
rvalue: true,
count: 2,
funcName: id+"eq"
})
}
})();
var binary_ops = {
and: "&&",
or: "||",
eq: "===",
neq: "!==",
lt: "<",
gt: ">",
leq: "<=",
geq: ">="
}
;(function() {
for(var id in binary_ops) {
var op = binary_ops[id]
exports[id] = makeOp({
args: ["array","array","array"],
body: {args:["a", "b", "c"],
body:"a=b"+op+"c"},
funcName: id
})
exports[id+"s"] = makeOp({
args: ["array","array","scalar"],
body: {args:["a", "b", "s"],
body:"a=b"+op+"s"},
funcName: id+"s"
})
exports[id+"eq"] = makeOp({
args: ["array", "array"],
body: {args:["a", "b"],
body:"a=a"+op+"b"},
rvalue:true,
count:2,
funcName: id+"eq"
})
exports[id+"seq"] = makeOp({
args: ["array", "scalar"],
body: {args:["a","s"],
body:"a=a"+op+"s"},
rvalue:true,
count:2,
funcName: id+"seq"
})
}
})();
var math_unary = [
"abs",
"acos",
"asin",
"atan",
"ceil",
"cos",
"exp",
"floor",
"log",
"round",
"sin",
"sqrt",
"tan"
]
;(function() {
for(var i=0; i<math_unary.length; ++i) {
var f = math_unary[i]
exports[f] = makeOp({
args: ["array", "array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b"], body:"a=this_f(b)", thisVars:["this_f"]},
funcName: f
})
exports[f+"eq"] = makeOp({
args: ["array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args: ["a"], body:"a=this_f(a)", thisVars:["this_f"]},
rvalue: true,
count: 2,
funcName: f+"eq"
})
}
})();
var math_comm = [
"max",
"min",
"atan2",
"pow"
]
;(function(){
for(var i=0; i<math_comm.length; ++i) {
var f= math_comm[i]
exports[f] = makeOp({
args:["array", "array", "array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b","c"], body:"a=this_f(b,c)", thisVars:["this_f"]},
funcName: f
})
exports[f+"s"] = makeOp({
args:["array", "array", "scalar"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b","c"], body:"a=this_f(b,c)", thisVars:["this_f"]},
funcName: f+"s"
})
exports[f+"eq"] = makeOp({ args:["array", "array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b"], body:"a=this_f(a,b)", thisVars:["this_f"]},
rvalue: true,
count: 2,
funcName: f+"eq"
})
exports[f+"seq"] = makeOp({ args:["array", "scalar"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b"], body:"a=this_f(a,b)", thisVars:["this_f"]},
rvalue:true,
count:2,
funcName: f+"seq"
})
}
})();
var math_noncomm = [
"atan2",
"pow"
]
;(function(){
for(var i=0; i<math_noncomm.length; ++i) {
var f= math_noncomm[i]
exports[f+"op"] = makeOp({
args:["array", "array", "array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b","c"], body:"a=this_f(c,b)", thisVars:["this_f"]},
funcName: f+"op"
})
exports[f+"ops"] = makeOp({
args:["array", "array", "scalar"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b","c"], body:"a=this_f(c,b)", thisVars:["this_f"]},
funcName: f+"ops"
})
exports[f+"opeq"] = makeOp({ args:["array", "array"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b"], body:"a=this_f(b,a)", thisVars:["this_f"]},
rvalue: true,
count: 2,
funcName: f+"opeq"
})
exports[f+"opseq"] = makeOp({ args:["array", "scalar"],
pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
body: {args:["a","b"], body:"a=this_f(b,a)", thisVars:["this_f"]},
rvalue:true,
count:2,
funcName: f+"opseq"
})
}
})();
exports.any = compile({
args:["array"],
pre: EmptyProc,
body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "if(a){return true}", localVars: [], thisVars: []},
post: {args:[], localVars:[], thisVars:[], body:"return false"},
funcName: "any"
})
exports.all = compile({
args:["array"],
pre: EmptyProc,
body: {args:[{name:"x", lvalue:false, rvalue:true, count:1}], body: "if(!x){return false}", localVars: [], thisVars: []},
post: {args:[], localVars:[], thisVars:[], body:"return true"},
funcName: "all"
})
exports.sum = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s+=a", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
funcName: "sum"
})
exports.prod = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=1"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s*=a", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
funcName: "prod"
})
exports.norm2squared = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
funcName: "norm2squared"
})
exports.norm2 = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return Math.sqrt(this_s)"},
funcName: "norm2"
})
exports.norminf = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:4}], body:"if(-a>this_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
funcName: "norminf"
})
exports.norm1 = compile({
args:["array"],
pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
body: {args:[{name:"a", lvalue:false, rvalue:true, count:3}], body: "this_s+=a<0?-a:a", localVars: [], thisVars: ["this_s"]},
post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
funcName: "norm1"
})
exports.sup = compile({
args: [ "array" ],
pre:
{ body: "this_h=-Infinity",
args: [],
thisVars: [ "this_h" ],
localVars: [] },
body:
{ body: "if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",
args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ],
thisVars: [ "this_h" ],
localVars: [] },
post:
{ body: "return this_h",
args: [],
thisVars: [ "this_h" ],
localVars: [] }
})
exports.inf = compile({
args: [ "array" ],
pre:
{ body: "this_h=Infinity",
args: [],
thisVars: [ "this_h" ],
localVars: [] },
body:
{ body: "if(_inline_1_arg0_<this_h)this_h=_inline_1_arg0_",
args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ],
thisVars: [ "this_h" ],
localVars: [] },
post:
{ body: "return this_h",
args: [],
thisVars: [ "this_h" ],
localVars: [] }
})
exports.argmin = compile({
args:["index","array","shape"],
pre:{
body:"{this_v=Infinity;this_i=_inline_0_arg2_.slice(0)}",
args:[
{name:"_inline_0_arg0_",lvalue:false,rvalue:false,count:0},
{name:"_inline_0_arg1_",lvalue:false,rvalue:false,count:0},
{name:"_inline_0_arg2_",lvalue:false,rvalue:true,count:1}
],
thisVars:["this_i","this_v"],
localVars:[]},
body:{
body:"{if(_inline_1_arg1_<this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",
args:[
{name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2},
{name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}],
thisVars:["this_i","this_v"],
localVars:["_inline_1_k"]},
post:{
body:"{return this_i}",
args:[],
thisVars:["this_i"],
localVars:[]}
})
exports.argmax = compile({
args:["index","array","shape"],
pre:{
body:"{this_v=-Infinity;this_i=_inline_0_arg2_.slice(0)}",
args:[
{name:"_inline_0_arg0_",lvalue:false,rvalue:false,count:0},
{name:"_inline_0_arg1_",lvalue:false,rvalue:false,count:0},
{name:"_inline_0_arg2_",lvalue:false,rvalue:true,count:1}
],
thisVars:["this_i","this_v"],
localVars:[]},
body:{
body:"{if(_inline_1_arg1_>this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",
args:[
{name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2},
{name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}],
thisVars:["this_i","this_v"],
localVars:["_inline_1_k"]},
post:{
body:"{return this_i}",
args:[],
thisVars:["this_i"],
localVars:[]}
})
exports.random = makeOp({
args: ["array"],
pre: {args:[], body:"this_f=Math.random", thisVars:["this_f"]},
body: {args: ["a"], body:"a=this_f()", thisVars:["this_f"]},
funcName: "random"
})
exports.assign = makeOp({
args:["array", "array"],
body: {args:["a", "b"], body:"a=b"},
funcName: "assign" })
exports.assigns = makeOp({
args:["array", "scalar"],
body: {args:["a", "b"], body:"a=b"},
funcName: "assigns" })
exports.equals = compile({
args:["array", "array"],
pre: EmptyProc,
body: {args:[{name:"x", lvalue:false, rvalue:true, count:1},
{name:"y", lvalue:false, rvalue:true, count:1}],
body: "if(x!==y){return false}",
localVars: [],
thisVars: []},
post: {args:[], localVars:[], thisVars:[], body:"return true"},
funcName: "equals"
})
},{"cwise-compiler":98}],98:[function(require,module,exports){
"use strict"
var createThunk = require("./lib/thunk.js")
function Procedure() {
this.argTypes = []
this.shimArgs = []
this.arrayArgs = []
this.scalarArgs = []
this.offsetArgs = []
this.offsetArgIndex = []
this.indexArgs = []
this.shapeArgs = []
this.funcName = ""
this.pre = null
this.body = null
this.post = null
this.debug = false
}
function compileCwise(user_args) {
//Create procedure
var proc = new Procedure()
//Parse blocks
proc.pre = user_args.pre
proc.body = user_args.body
proc.post = user_args.post
//Parse arguments
var proc_args = user_args.args.slice(0)
proc.argTypes = proc_args
for(var i=0; i<proc_args.length; ++i) {
var arg_type = proc_args[i]
if(arg_type === "array") {
proc.arrayArgs.push(i)
proc.shimArgs.push("array" + i)
if(i < proc.pre.args.length && proc.pre.args[i].count>0) {
throw new Error("cwise: pre() block may not reference array args")
}
if(i < proc.post.args.length && proc.post.args[i].count>0) {
throw new Error("cwise: post() block may not reference array args")
}
} else if(arg_type === "scalar") {
proc.scalarArgs.push(i)
proc.shimArgs.push("scalar" + i)
} else if(arg_type === "index") {
proc.indexArgs.push(i)
if(i < proc.pre.args.length && proc.pre.args[i].count > 0) {
throw new Error("cwise: pre() block may not reference array index")
}
if(i < proc.body.args.length && proc.body.args[i].lvalue) {
throw new Error("cwise: body() block may not write to array index")
}
if(i < proc.post.args.length && proc.post.args[i].count > 0) {
throw new Error("cwise: post() block may not reference array index")
}
} else if(arg_type === "shape") {
proc.shapeArgs.push(i)
if(i < proc.pre.args.length && proc.pre.args[i].lvalue) {
throw new Error("cwise: pre() block may not write to array shape")
}
if(i < proc.body.args.length && proc.body.args[i].lvalue) {
throw new Error("cwise: body() block may not write to array shape")
}
if(i < proc.post.args.length && proc.post.args[i].lvalue) {
throw new Error("cwise: post() block may not write to array shape")
}
} else if(typeof arg_type === "object" && arg_type.offset) {
proc.argTypes[i] = "offset"
proc.offsetArgs.push({ array: arg_type.array, offset:arg_type.offset })
proc.offsetArgIndex.push(i)
} else {
throw new Error("cwise: Unknown argument type " + proc_args[i])
}
}
//Make sure at least one array argument was specified
if(proc.arrayArgs.length <= 0) {
throw new Error("cwise: No array arguments specified")
}
//Make sure arguments are correct
if(proc.pre.args.length > proc_args.length) {
throw new Error("cwise: Too many arguments in pre() block")
}
if(proc.body.args.length > proc_args.length) {
throw new Error("cwise: Too many arguments in body() block")
}
if(proc.post.args.length > proc_args.length) {
throw new Error("cwise: Too many arguments in post() block")
}
//Check debug flag
proc.debug = !!user_args.printCode || !!user_args.debug
//Retrieve name
proc.funcName = user_args.funcName || "cwise"
//Read in block size
proc.blockSize = user_args.blockSize || 64
return createThunk(proc)
}
module.exports = compileCwise
},{"./lib/thunk.js":100}],99:[function(require,module,exports){
"use strict"
var uniq = require("uniq")
function innerFill(order, proc, body) {
var dimension = order.length
, nargs = proc.arrayArgs.length
, has_index = proc.indexArgs.length>0
, code = []
, vars = []
, idx=0, pidx=0, i, j
for(i=0; i<dimension; ++i) {
vars.push(["i",i,"=0"].join(""))
}
//Compute scan deltas
for(j=0; j<nargs; ++j) {
for(i=0; i<dimension; ++i) {
pidx = idx
idx = order[i]
if(i === 0) {
vars.push(["d",j,"s",i,"=t",j,"p",idx].join(""))
} else {
vars.push(["d",j,"s",i,"=(t",j,"p",idx,"-s",pidx,"*t",j,"p",pidx,")"].join(""))
}
}
}
code.push("var " + vars.join(","))
//Scan loop
for(i=dimension-1; i>=0; --i) {
idx = order[i]
code.push(["for(i",i,"=0;i",i,"<s",idx,";++i",i,"){"].join(""))
}
//Push body of inner loop
code.push(body)
//Advance scan pointers
for(i=0; i<dimension; ++i) {
pidx = idx
idx = order[i]
for(j=0; j<nargs; ++j) {
code.push(["p",j,"+=d",j,"s",i].join(""))
}
if(has_index) {
if(i > 0) {
code.push(["index[",pidx,"]-=s",pidx].join(""))
}
code.push(["++index[",idx,"]"].join(""))
}
code.push("}")
}
return code.join("\n")
}
function outerFill(matched, order, proc, body) {
var dimension = order.length
, nargs = proc.arrayArgs.length
, blockSize = proc.blockSize
, has_index = proc.indexArgs.length > 0
, code = []
for(var i=0; i<nargs; ++i) {
code.push(["var offset",i,"=p",i].join(""))
}
//Generate matched loops
for(var i=matched; i<dimension; ++i) {
code.push(["for(var j"+i+"=SS[", order[i], "]|0;j", i, ">0;){"].join(""))
code.push(["if(j",i,"<",blockSize,"){"].join(""))
code.push(["s",order[i],"=j",i].join(""))
code.push(["j",i,"=0"].join(""))
code.push(["}else{s",order[i],"=",blockSize].join(""))
code.push(["j",i,"-=",blockSize,"}"].join(""))
if(has_index) {
code.push(["index[",order[i],"]=j",i].join(""))
}
}
for(var i=0; i<nargs; ++i) {
var indexStr = ["offset"+i]
for(var j=matched; j<dimension; ++j) {
indexStr.push(["j",j,"*t",i,"p",order[j]].join(""))
}
code.push(["p",i,"=(",indexStr.join("+"),")"].join(""))
}
code.push(innerFill(order, proc, body))
for(var i=matched; i<dimension; ++i) {
code.push("}")
}
return code.join("\n")
}
//Count the number of compatible inner orders
function countMatches(orders) {
var matched = 0, dimension = orders[0].length
while(matched < dimension) {
for(var j=1; j<orders.length; ++j) {
if(orders[j][matched] !== orders[0][matched]) {
return matched
}
}
++matched
}
return matched
}
//Processes a block according to the given data types
function processBlock(block, proc, dtypes) {
var code = block.body
var pre = []
var post = []
for(var i=0; i<block.args.length; ++i) {
var carg = block.args[i]
if(carg.count <= 0) {
continue
}
var re = new RegExp(carg.name, "g")
var ptrStr = ""
var arrNum = proc.arrayArgs.indexOf(i)
switch(proc.argTypes[i]) {
case "offset":
var offArgIndex = proc.offsetArgIndex.indexOf(i)
var offArg = proc.offsetArgs[offArgIndex]
arrNum = offArg.array
ptrStr = "+q" + offArgIndex
case "array":
ptrStr = "p" + arrNum + ptrStr
var localStr = "l" + i
var arrStr = "a" + arrNum
if(carg.count === 1) {
if(dtypes[arrNum] === "generic") {
if(carg.lvalue) {
pre.push(["var ", localStr, "=", arrStr, ".get(", ptrStr, ")"].join(""))
code = code.replace(re, localStr)
post.push([arrStr, ".set(", ptrStr, ",", localStr,")"].join(""))
} else {
code = code.replace(re, [arrStr, ".get(", ptrStr, ")"].join(""))
}
} else {
code = code.replace(re, [arrStr, "[", ptrStr, "]"].join(""))
}
} else if(dtypes[arrNum] === "generic") {
pre.push(["var ", localStr, "=", arrStr, ".get(", ptrStr, ")"].join(""))
code = code.replace(re, localStr)
if(carg.lvalue) {
post.push([arrStr, ".set(", ptrStr, ",", localStr,")"].join(""))
}
} else {
pre.push(["var ", localStr, "=", arrStr, "[", ptrStr, "]"].join(""))
code = code.replace(re, localStr)
if(carg.lvalue) {
post.push([arrStr, "[", ptrStr, "]=", localStr].join(""))
}
}
break
case "scalar":
code = code.replace(re, "Y" + proc.scalarArgs.indexOf(i))
break
case "index":
code = code.replace(re, "index")
break
case "shape":
code = code.replace(re, "shape")
break
}
}
return [pre.join("\n"), code, post.join("\n")].join("\n").trim()
}
function typeSummary(dtypes) {
var summary = new Array(dtypes.length)
var allEqual = true
for(var i=0; i<dtypes.length; ++i) {
var t = dtypes[i]
var digits = t.match(/\d+/)
if(!digits) {
digits = ""
} else {
digits = digits[0]
}
if(t.charAt(0) === 0) {
summary[i] = "u" + t.charAt(1) + digits
} else {
summary[i] = t.charAt(0) + digits
}
if(i > 0) {
allEqual = allEqual && summary[i] === summary[i-1]
}
}
if(allEqual) {
return summary[0]
}
return summary.join("")
}
//Generates a cwise operator
function generateCWiseOp(proc, typesig) {
//Compute dimension
var dimension = typesig[1].length|0
var orders = new Array(proc.arrayArgs.length)
var dtypes = new Array(proc.arrayArgs.length)
//First create arguments for procedure
var arglist = ["SS"]
var code = ["'use strict'"]
var vars = []
for(var j=0; j<dimension; ++j) {
vars.push(["s", j, "=SS[", j, "]"].join(""))
}
for(var i=0; i<proc.arrayArgs.length; ++i) {
arglist.push("a"+i)
arglist.push("t"+i)
arglist.push("p"+i)
dtypes[i] = typesig[2*i]
orders[i] = typesig[2*i+1]
for(var j=0; j<dimension; ++j) {
vars.push(["t",i,"p",j,"=t",i,"[",j,"]"].join(""))
}
}
for(var i=0; i<proc.scalarArgs.length; ++i) {
arglist.push("Y" + i)
}
if(proc.shapeArgs.length > 0) {
vars.push("shape=SS.slice(0)")
}
if(proc.indexArgs.length > 0) {
var zeros = new Array(dimension)
for(var i=0; i<dimension; ++i) {
zeros[i] = "0"
}
vars.push(["index=[", zeros.join(","), "]"].join(""))
}
for(var i=0; i<proc.offsetArgs.length; ++i) {
var off_arg = proc.offsetArgs[i]
var init_string = []
for(var j=0; j<off_arg.offset.length; ++j) {
if(off_arg.offset[j] === 0) {
continue
} else if(off_arg.offset[j] === 1) {
init_string.push(["t", off_arg.array, "p", j].join(""))
} else {
init_string.push([off_arg.offset[j], "*t", off_arg.array, "p", j].join(""))
}
}
if(init_string.length === 0) {
vars.push("q" + i + "=0")
} else {
vars.push(["q", i, "=", init_string.join("+")].join(""))
}
}
//Prepare this variables
var thisVars = uniq([].concat(proc.pre.thisVars)
.concat(proc.body.thisVars)
.concat(proc.post.thisVars))
vars = vars.concat(thisVars)
code.push("var " + vars.join(","))
for(var i=0; i<proc.arrayArgs.length; ++i) {
code.push("p"+i+"|=0")
}
//Inline prelude
if(proc.pre.body.length > 3) {
code.push(processBlock(proc.pre, proc, dtypes))
}
//Process body
var body = processBlock(proc.body, proc, dtypes)
var matched = countMatches(orders)
if(matched < dimension) {
code.push(outerFill(matched, orders[0], proc, body))
} else {
code.push(innerFill(orders[0], proc, body))
}
//Inline epilog
if(proc.post.body.length > 3) {
code.push(processBlock(proc.post, proc, dtypes))
}
if(proc.debug) {
console.log("Generated cwise routine for ", typesig, ":\n\n", code.join("\n"))
}
var loopName = [(proc.funcName||"unnamed"), "_cwise_loop_", orders[0].join("s"),"m",matched,typeSummary(dtypes)].join("")
var f = new Function(["function ",loopName,"(", arglist.join(","),"){", code.join("\n"),"} return ", loopName].join(""))
return f()
}
module.exports = generateCWiseOp
},{"uniq":101}],100:[function(require,module,exports){
"use strict"
var compile = require("./compile.js")
function createThunk(proc) {
var code = ["'use strict'", "var CACHED={}"]
var vars = []
var thunkName = proc.funcName + "_cwise_thunk"
//Build thunk
code.push(["return function ", thunkName, "(", proc.shimArgs.join(","), "){"].join(""))
var typesig = []
var string_typesig = []
var proc_args = [["array",proc.arrayArgs[0],".shape"].join("")]
for(var i=0; i<proc.arrayArgs.length; ++i) {
var j = proc.arrayArgs[i]
vars.push(["t", j, "=array", j, ".dtype,",
"r", j, "=array", j, ".order"].join(""))
typesig.push("t" + j)
typesig.push("r" + j)
string_typesig.push("t"+j)
string_typesig.push("r"+j+".join()")
proc_args.push("array" + j + ".data")
proc_args.push("array" + j + ".stride")
proc_args.push("array" + j + ".offset|0")
}
for(var i=0; i<proc.scalarArgs.length; ++i) {
proc_args.push("scalar" + proc.scalarArgs[i])
}
vars.push(["type=[", string_typesig.join(","), "].join()"].join(""))
vars.push("proc=CACHED[type]")
code.push("var " + vars.join(","))
code.push(["if(!proc){",
"CACHED[type]=proc=compile([", typesig.join(","), "])}",
"return proc(", proc_args.join(","), ")}"].join(""))
if(proc.debug) {
console.log("Generated thunk:", code.join("\n"))
}
//Compile thunk
var thunk = new Function("compile", code.join("\n"))
return thunk(compile.bind(undefined, proc))
}
module.exports = createThunk
},{"./compile.js":99}],101:[function(require,module,exports){
"use strict"
function unique_pred(list, compare) {
var ptr = 1
, len = list.length
, a=list[0], b=list[0]
for(var i=1; i<len; ++i) {
b = a
a = list[i]
if(compare(a, b)) {
if(i === ptr) {
ptr++
continue
}
list[ptr++] = a
}
}
list.length = ptr
return list
}
function unique_eq(list) {
var ptr = 1
, len = list.length
, a=list[0], b = list[0]
for(var i=1; i<len; ++i, b=a) {
b = a
a = list[i]
if(a !== b) {
if(i === ptr) {
ptr++
continue
}
list[ptr++] = a
}
}
list.length = ptr
return list
}
function unique(list, compare, sorted) {
if(list.length === 0) {
return list
}
if(compare) {
if(!sorted) {
list.sort(compare)
}
return unique_pred(list, compare)
}
if(!sorted) {
list.sort()
}
return unique_eq(list)
}
module.exports = unique
},{}],102:[function(require,module,exports){
(function (Buffer){
var iota = require("iota-array")
var hasTypedArrays = ((typeof Float64Array) !== "undefined")
var hasBuffer = ((typeof Buffer) !== "undefined")
function compare1st(a, b) {
return a[0] - b[0]
}
function order() {
var stride = this.stride
var terms = new Array(stride.length)
var i
for(i=0; i<terms.length; ++i) {
terms[i] = [Math.abs(stride[i]), i]
}
terms.sort(compare1st)
var result = new Array(terms.length)
for(i=0; i<result.length; ++i) {
result[i] = terms[i][1]
}
return result
}
function compileConstructor(dtype, dimension) {
var className = ["View", dimension, "d", dtype].join("")
if(dimension < 0) {
className = "View_Nil" + dtype
}
var useGetters = (dtype === "generic")
if(dimension === -1) {
//Special case for trivial arrays
var code =
"function "+className+"(a){this.data=a;};\
var proto="+className+".prototype;\
proto.dtype='"+dtype+"';\
proto.index=function(){return -1};\
proto.size=0;\
proto.dimension=-1;\
proto.shape=proto.stride=proto.order=[];\
proto.lo=proto.hi=proto.transpose=proto.step=\
function(){return new "+className+"(this.data);};\
proto.get=proto.set=function(){};\
proto.pick=function(){return null};\
return function construct_"+className+"(a){return new "+className+"(a);}"
var procedure = new Function(code)
return procedure()
} else if(dimension === 0) {
//Special case for 0d arrays
var code =
"function "+className+"(a,d) {\
this.data = a;\
this.offset = d\
};\
var proto="+className+".prototype;\
proto.dtype='"+dtype+"';\
proto.index=function(){return this.offset};\
proto.dimension=0;\
proto.size=1;\
proto.shape=\
proto.stride=\
proto.order=[];\
proto.lo=\
proto.hi=\
proto.transpose=\
proto.step=function "+className+"_copy() {\
return new "+className+"(this.data,this.offset)\
};\
proto.pick=function "+className+"_pick(){\
return TrivialArray(this.data);\
};\
proto.valueOf=proto.get=function "+className+"_get(){\
return "+(useGetters ? "this.data.get(this.offset)" : "this.data[this.offset]")+
"};\
proto.set=function "+className+"_set(v){\
return "+(useGetters ? "this.data.set(this.offset,v)" : "this.data[this.offset]=v")+"\
};\
return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}"
var procedure = new Function("TrivialArray", code)
return procedure(CACHED_CONSTRUCTORS[dtype][0])
}
var code = ["'use strict'"]
//Create constructor for view
var indices = iota(dimension)
var args = indices.map(function(i) { return "i"+i })
var index_str = "this.offset+" + indices.map(function(i) {
return "this.stride[" + i + "]*i" + i
}).join("+")
var shapeArg = indices.map(function(i) {
return "b"+i
}).join(",")
var strideArg = indices.map(function(i) {
return "c"+i
}).join(",")
code.push(
"function "+className+"(a," + shapeArg + "," + strideArg + ",d){this.data=a",
"this.shape=[" + shapeArg + "]",
"this.stride=[" + strideArg + "]",
"this.offset=d|0}",
"var proto="+className+".prototype",
"proto.dtype='"+dtype+"'",
"proto.dimension="+dimension)
//view.size:
code.push("Object.defineProperty(proto,'size',{get:function "+className+"_size(){\
return "+indices.map(function(i) { return "this.shape["+i+"]" }).join("*"),
"}})")
//view.order:
if(dimension === 1) {
code.push("proto.order=[0]")
} else {
code.push("Object.defineProperty(proto,'order',{get:")
if(dimension < 4) {
code.push("function "+className+"_order(){")
if(dimension === 2) {
code.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})")
} else if(dimension === 3) {
code.push(
"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\
if(s0>s1){\
if(s1>s2){\
return [2,1,0];\
}else if(s0>s2){\
return [1,2,0];\
}else{\
return [1,0,2];\
}\
}else if(s0>s2){\
return [2,0,1];\
}else if(s2>s1){\
return [0,1,2];\
}else{\
return [0,2,1];\
}}})")
}
} else {
code.push("ORDER})")
}
}
//view.set(i0, ..., v):
code.push(
"proto.set=function "+className+"_set("+args.join(",")+",v){")
if(useGetters) {
code.push("return this.data.set("+index_str+",v)}")
} else {
code.push("return this.data["+index_str+"]=v}")
}
//view.get(i0, ...):
code.push("proto.get=function "+className+"_get("+args.join(",")+"){")
if(useGetters) {
code.push("return this.data.get("+index_str+")}")
} else {
code.push("return this.data["+index_str+"]}")
}
//view.index:
code.push(
"proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}")
//view.hi():
code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+
indices.map(function(i) {
return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("")
}).join(",")+","+
indices.map(function(i) {
return "this.stride["+i + "]"
}).join(",")+",this.offset)}")
//view.lo():
var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" })
var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" })
code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(","))
for(var i=0; i<dimension; ++i) {
code.push(
"if(typeof i"+i+"==='number'&&i"+i+">=0){\
d=i"+i+"|0;\
b+=c"+i+"*d;\
a"+i+"-=d}")
}
code.push("return new "+className+"(this.data,"+
indices.map(function(i) {
return "a"+i
}).join(",")+","+
indices.map(function(i) {
return "c"+i
}).join(",")+",b)}")
//view.step():
code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+
indices.map(function(i) {
return "a"+i+"=this.shape["+i+"]"
}).join(",")+","+
indices.map(function(i) {
return "b"+i+"=this.stride["+i+"]"
}).join(",")+",c=this.offset,d=0,ceil=Math.ceil")
for(var i=0; i<dimension; ++i) {
code.push(
"if(typeof i"+i+"==='number'){\
d=i"+i+"|0;\
if(d<0){\
c+=b"+i+"*(a"+i+"-1);\
a"+i+"=ceil(-a"+i+"/d)\
}else{\
a"+i+"=ceil(a"+i+"/d)\
}\
b"+i+"*=d\
}")
}
code.push("return new "+className+"(this.data,"+
indices.map(function(i) {
return "a" + i
}).join(",")+","+
indices.map(function(i) {
return "b" + i
}).join(",")+",c)}")
//view.transpose():
var tShape = new Array(dimension)
var tStride = new Array(dimension)
for(var i=0; i<dimension; ++i) {
tShape[i] = "a[i"+i+"]"
tStride[i] = "b[i"+i+"]"
}
code.push("proto.transpose=function "+className+"_transpose("+args+"){"+
args.map(function(n,idx) { return n + "=(" + n + "===undefined?" + idx + ":" + n + "|0)"}).join(";"),
"var a=this.shape,b=this.stride;return new "+className+"(this.data,"+tShape.join(",")+","+tStride.join(",")+",this.offset)}")
//view.pick():
code.push("proto.pick=function "+className+"_pick("+args+"){var a=[],b=[],c=this.offset")
for(var i=0; i<dimension; ++i) {
code.push("if(typeof i"+i+"==='number'&&i"+i+">=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}")
}
code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}")
//Add return statement
code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+
indices.map(function(i) {
return "shape["+i+"]"
}).join(",")+","+
indices.map(function(i) {
return "stride["+i+"]"
}).join(",")+",offset)}")
//Compile procedure
var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n"))
return procedure(CACHED_CONSTRUCTORS[dtype], order)
}
function arrayDType(data) {
if(hasBuffer) {
if(Buffer.isBuffer(data)) {
return "buffer"
}
}
if(hasTypedArrays) {
switch(Object.prototype.toString.call(data)) {
case "[object Float64Array]":
return "float64"
case "[object Float32Array]":
return "float32"
case "[object Int8Array]":
return "int8"
case "[object Int16Array]":
return "int16"
case "[object Int32Array]":
return "int32"
case "[object Uint8Array]":
return "uint8"
case "[object Uint16Array]":
return "uint16"
case "[object Uint32Array]":
return "uint32"
case "[object Uint8ClampedArray]":
return "uint8_clamped"
}
}
if(Array.isArray(data)) {
return "array"
}
return "generic"
}
var CACHED_CONSTRUCTORS = {
"float32":[],
"float64":[],
"int8":[],
"int16":[],
"int32":[],
"uint8":[],
"uint16":[],
"uint32":[],
"array":[],
"uint8_clamped":[],
"buffer":[],
"generic":[]
}
;(function() {
for(var id in CACHED_CONSTRUCTORS) {
CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1))
}
});
function wrappedNDArrayCtor(data, shape, stride, offset) {
if(data === undefined) {
var ctor = CACHED_CONSTRUCTORS.array[0]
return ctor([])
} else if(typeof data === "number") {
data = [data]
}
if(shape === undefined) {
shape = [ data.length ]
}
var d = shape.length
if(stride === undefined) {
stride = new Array(d)
for(var i=d-1, sz=1; i>=0; --i) {
stride[i] = sz
sz *= shape[i]
}
}
if(offset === undefined) {
offset = 0
for(var i=0; i<d; ++i) {
if(stride[i] < 0) {
offset -= (shape[i]-1)*stride[i]
}
}
}
var dtype = arrayDType(data)
var ctor_list = CACHED_CONSTRUCTORS[dtype]
while(ctor_list.length <= d+1) {
ctor_list.push(compileConstructor(dtype, ctor_list.length-1))
}
var ctor = ctor_list[d+1]
return ctor(data, shape, stride, offset)
}
module.exports = wrappedNDArrayCtor
}).call(this,require("buffer").Buffer)
},{"buffer":17,"iota-array":103}],103:[function(require,module,exports){
"use strict"
function iota(n) {
var result = new Array(n)
for(var i=0; i<n; ++i) {
result[i] = i
}
return result
}
module.exports = iota
},{}],104:[function(require,module,exports){
/**
* Bit twiddling hacks for JavaScript.
*
* Author: Mikola Lysenko
*
* Ported from Stanford bit twiddling hack library:
* http://graphics.stanford.edu/~seander/bithacks.html
*/
"use strict"; "use restrict";
//Number of bits in an integer
var INT_BITS = 32;
//Constants
exports.INT_BITS = INT_BITS;
exports.INT_MAX = 0x7fffffff;
exports.INT_MIN = -1<<(INT_BITS-1);
//Returns -1, 0, +1 depending on sign of x
exports.sign = function(v) {
return (v > 0) - (v < 0);
}
//Computes absolute value of integer
exports.abs = function(v) {
var mask = v >> (INT_BITS-1);
return (v ^ mask) - mask;
}
//Computes minimum of integers x and y
exports.min = function(x, y) {
return y ^ ((x ^ y) & -(x < y));
}
//Computes maximum of integers x and y
exports.max = function(x, y) {
return x ^ ((x ^ y) & -(x < y));
}
//Checks if a number is a power of two
exports.isPow2 = function(v) {
return !(v & (v-1)) && (!!v);
}
//Computes log base 2 of v
exports.log2 = function(v) {
var r, shift;
r = (v > 0xFFFF) << 4; v >>>= r;
shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift;
shift = (v > 0xF ) << 2; v >>>= shift; r |= shift;
shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift;
return r | (v >> 1);
}
//Computes log base 10 of v
exports.log10 = function(v) {
return (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
(v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
(v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
}
//Counts number of bits
exports.popCount = function(v) {
v = v - ((v >>> 1) & 0x55555555);
v = (v & 0x33333333) + ((v >>> 2) & 0x33333333);
return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24;
}
//Counts number of trailing zeros
function countTrailingZeros(v) {
var c = 32;
v &= -v;
if (v) c--;
if (v & 0x0000FFFF) c -= 16;
if (v & 0x00FF00FF) c -= 8;
if (v & 0x0F0F0F0F) c -= 4;
if (v & 0x33333333) c -= 2;
if (v & 0x55555555) c -= 1;
return c;
}
exports.countTrailingZeros = countTrailingZeros;
//Rounds to next power of 2
exports.nextPow2 = function(v) {
v += v === 0;
--v;
v |= v >>> 1;
v |= v >>> 2;
v |= v >>> 4;
v |= v >>> 8;
v |= v >>> 16;
return v + 1;
}
//Rounds down to previous power of 2
exports.prevPow2 = function(v) {
v |= v >>> 1;
v |= v >>> 2;
v |= v >>> 4;
v |= v >>> 8;
v |= v >>> 16;
return v - (v>>>1);
}
//Computes parity of word
exports.parity = function(v) {
v ^= v >>> 16;
v ^= v >>> 8;
v ^= v >>> 4;
v &= 0xf;
return (0x6996 >>> v) & 1;
}
var REVERSE_TABLE = new Array(256);
(function(tab) {
for(var i=0; i<256; ++i) {
var v = i, r = i, s = 7;
for (v >>>= 1; v; v >>>= 1) {
r <<= 1;
r |= v & 1;
--s;
}
tab[i] = (r << s) & 0xff;
}
})(REVERSE_TABLE);
//Reverse bits in a 32 bit word
exports.reverse = function(v) {
return (REVERSE_TABLE[ v & 0xff] << 24) |
(REVERSE_TABLE[(v >>> 8) & 0xff] << 16) |
(REVERSE_TABLE[(v >>> 16) & 0xff] << 8) |
REVERSE_TABLE[(v >>> 24) & 0xff];
}
//Interleave bits of 2 coordinates with 16 bits. Useful for fast quadtree codes
exports.interleave2 = function(x, y) {
x &= 0xFFFF;
x = (x | (x << 8)) & 0x00FF00FF;
x = (x | (x << 4)) & 0x0F0F0F0F;
x = (x | (x << 2)) & 0x33333333;
x = (x | (x << 1)) & 0x55555555;
y &= 0xFFFF;
y = (y | (y << 8)) & 0x00FF00FF;
y = (y | (y << 4)) & 0x0F0F0F0F;
y = (y | (y << 2)) & 0x33333333;
y = (y | (y << 1)) & 0x55555555;
return x | (y << 1);
}
//Extracts the nth interleaved component
exports.deinterleave2 = function(v, n) {
v = (v >>> n) & 0x55555555;
v = (v | (v >>> 1)) & 0x33333333;
v = (v | (v >>> 2)) & 0x0F0F0F0F;
v = (v | (v >>> 4)) & 0x00FF00FF;
v = (v | (v >>> 16)) & 0x000FFFF;
return (v << 16) >> 16;
}
//Interleave bits of 3 coordinates, each with 10 bits. Useful for fast octree codes
exports.interleave3 = function(x, y, z) {
x &= 0x3FF;
x = (x | (x<<16)) & 4278190335;
x = (x | (x<<8)) & 251719695;
x = (x | (x<<4)) & 3272356035;
x = (x | (x<<2)) & 1227133513;
y &= 0x3FF;
y = (y | (y<<16)) & 4278190335;
y = (y | (y<<8)) & 251719695;
y = (y | (y<<4)) & 3272356035;
y = (y | (y<<2)) & 1227133513;
x |= (y << 1);
z &= 0x3FF;
z = (z | (z<<16)) & 4278190335;
z = (z | (z<<8)) & 251719695;
z = (z | (z<<4)) & 3272356035;
z = (z | (z<<2)) & 1227133513;
return x | (z << 2);
}
//Extracts nth interleaved component of a 3-tuple
exports.deinterleave3 = function(v, n) {
v = (v >>> n) & 1227133513;
v = (v | (v>>>2)) & 3272356035;
v = (v | (v>>>4)) & 251719695;
v = (v | (v>>>8)) & 4278190335;
v = (v | (v>>>16)) & 0x3FF;
return (v<<22)>>22;
}
//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page)
exports.nextCombination = function(v) {
var t = v | (v - 1);
return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1));
}
},{}],105:[function(require,module,exports){
"use strict"
function dupe_array(count, value, i) {
var c = count[i]|0
if(c <= 0) {
return []
}
var result = new Array(c), j
if(i === count.length-1) {
for(j=0; j<c; ++j) {
result[j] = value
}
} else {
for(j=0; j<c; ++j) {
result[j] = dupe_array(count, value, i+1)
}
}
return result
}
function dupe_number(count, value) {
var result, i
result = new Array(count)
for(i=0; i<count; ++i) {
result[i] = value
}
return result
}
function dupe(count, value) {
if(typeof value === "undefined") {
value = 0
}
switch(typeof count) {
case "number":
if(count > 0) {
return dupe_number(count|0, value)
}
break
case "object":
if(typeof (count.length) === "number") {
return dupe_array(count, value, 0)
}
break
}
return []
}
module.exports = dupe
},{}],106:[function(require,module,exports){
(function (global,Buffer){
'use strict'
var bits = require('bit-twiddle')
var dup = require('dup')
//Legacy pool support
if(!global.__TYPEDARRAY_POOL) {
global.__TYPEDARRAY_POOL = {
UINT8 : dup([32, 0])
, UINT16 : dup([32, 0])
, UINT32 : dup([32, 0])
, INT8 : dup([32, 0])
, INT16 : dup([32, 0])
, INT32 : dup([32, 0])
, FLOAT : dup([32, 0])
, DOUBLE : dup([32, 0])
, DATA : dup([32, 0])
, UINT8C : dup([32, 0])
, BUFFER : dup([32, 0])
}
}
var hasUint8C = (typeof Uint8ClampedArray) !== 'undefined'
var POOL = global.__TYPEDARRAY_POOL
//Upgrade pool
if(!POOL.UINT8C) {
POOL.UINT8C = dup([32, 0])
}
if(!POOL.BUFFER) {
POOL.BUFFER = dup([32, 0])
}
//New technique: Only allocate from ArrayBufferView and Buffer
var DATA = POOL.DATA
, BUFFER = POOL.BUFFER
exports.free = function free(array) {
if(Buffer.isBuffer(array)) {
BUFFER[bits.log2(array.length)].push(array)
} else {
if(Object.prototype.toString.call(array) !== '[object ArrayBuffer]') {
array = array.buffer
}
if(!array) {
return
}
var n = array.length || array.byteLength
var log_n = bits.log2(n)|0
DATA[log_n].push(array)
}
}
function freeArrayBuffer(buffer) {
if(!buffer) {
return
}
var n = buffer.length || buffer.byteLength
var log_n = bits.log2(n)
DATA[log_n].push(buffer)
}
function freeTypedArray(array) {
freeArrayBuffer(array.buffer)
}
exports.freeUint8 =
exports.freeUint16 =
exports.freeUint32 =
exports.freeInt8 =
exports.freeInt16 =
exports.freeInt32 =
exports.freeFloat32 =
exports.freeFloat =
exports.freeFloat64 =
exports.freeDouble =
exports.freeUint8Clamped =
exports.freeDataView = freeTypedArray
exports.freeArrayBuffer = freeArrayBuffer
exports.freeBuffer = function freeBuffer(array) {
BUFFER[bits.log2(array.length)].push(array)
}
exports.malloc = function malloc(n, dtype) {
if(dtype === undefined || dtype === 'arraybuffer') {
return mallocArrayBuffer(n)
} else {
switch(dtype) {
case 'uint8':
return mallocUint8(n)
case 'uint16':
return mallocUint16(n)
case 'uint32':
return mallocUint32(n)
case 'int8':
return mallocInt8(n)
case 'int16':
return mallocInt16(n)
case 'int32':
return mallocInt32(n)
case 'float':
case 'float32':
return mallocFloat(n)
case 'double':
case 'float64':
return mallocDouble(n)
case 'uint8_clamped':
return mallocUint8Clamped(n)
case 'buffer':
return mallocBuffer(n)
case 'data':
case 'dataview':
return mallocDataView(n)
default:
return null
}
}
return null
}
function mallocArrayBuffer(n) {
var n = bits.nextPow2(n)
var log_n = bits.log2(n)
var d = DATA[log_n]
if(d.length > 0) {
return d.pop()
}
return new ArrayBuffer(n)
}
exports.mallocArrayBuffer = mallocArrayBuffer
function mallocUint8(n) {
return new Uint8Array(mallocArrayBuffer(n), 0, n)
}
exports.mallocUint8 = mallocUint8
function mallocUint16(n) {
return new Uint16Array(mallocArrayBuffer(2*n), 0, n)
}
exports.mallocUint16 = mallocUint16
function mallocUint32(n) {
return new Uint32Array(mallocArrayBuffer(4*n), 0, n)
}
exports.mallocUint32 = mallocUint32
function mallocInt8(n) {
return new Int8Array(mallocArrayBuffer(n), 0, n)
}
exports.mallocInt8 = mallocInt8
function mallocInt16(n) {
return new Int16Array(mallocArrayBuffer(2*n), 0, n)
}
exports.mallocInt16 = mallocInt16
function mallocInt32(n) {
return new Int32Array(mallocArrayBuffer(4*n), 0, n)
}
exports.mallocInt32 = mallocInt32
function mallocFloat(n) {
return new Float32Array(mallocArrayBuffer(4*n), 0, n)
}
exports.mallocFloat32 = exports.mallocFloat = mallocFloat
function mallocDouble(n) {
return new Float64Array(mallocArrayBuffer(8*n), 0, n)
}
exports.mallocFloat64 = exports.mallocDouble = mallocDouble
function mallocUint8Clamped(n) {
if(hasUint8C) {
return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n)
} else {
return mallocUint8(n)
}
}
exports.mallocUint8Clamped = mallocUint8Clamped
function mallocDataView(n) {
return new DataView(mallocArrayBuffer(n), 0, n)
}
exports.mallocDataView = mallocDataView
function mallocBuffer(n) {
n = bits.nextPow2(n)
var log_n = bits.log2(n)
var cache = BUFFER[log_n]
if(cache.length > 0) {
return cache.pop()
}
return new Buffer(n)
}
exports.mallocBuffer = mallocBuffer
exports.clearCache = function clearCache() {
for(var i=0; i<32; ++i) {
POOL.UINT8[i].length = 0
POOL.UINT16[i].length = 0
POOL.UINT32[i].length = 0
POOL.INT8[i].length = 0
POOL.INT16[i].length = 0
POOL.INT32[i].length = 0
POOL.FLOAT[i].length = 0
POOL.DOUBLE[i].length = 0
POOL.UINT8C[i].length = 0
DATA[i].length = 0
BUFFER[i].length = 0
}
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
},{"bit-twiddle":104,"buffer":17,"dup":105}],107:[function(require,module,exports){
// Copyright (C) 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Install a leaky WeakMap emulation on platforms that
* don't provide a built-in one.
*
* <p>Assumes that an ES5 platform where, if {@code WeakMap} is
* already present, then it conforms to the anticipated ES6
* specification. To run this file on an ES5 or almost ES5
* implementation where the {@code WeakMap} specification does not
* quite conform, run <code>repairES5.js</code> first.
*
* <p>Even though WeakMapModule is not global, the linter thinks it
* is, which is why it is in the overrides list below.
*
* <p>NOTE: Before using this WeakMap emulation in a non-SES
* environment, see the note below about hiddenRecord.
*
* @author Mark S. Miller
* @requires crypto, ArrayBuffer, Uint8Array, navigator, console
* @overrides WeakMap, ses, Proxy
* @overrides WeakMapModule
*/
/**
* This {@code WeakMap} emulation is observably equivalent to the
* ES-Harmony WeakMap, but with leakier garbage collection properties.
*
* <p>As with true WeakMaps, in this emulation, a key does not
* retain maps indexed by that key and (crucially) a map does not
* retain the keys it indexes. A map by itself also does not retain
* the values associated with that map.
*
* <p>However, the values associated with a key in some map are
* retained so long as that key is retained and those associations are
* not overridden. For example, when used to support membranes, all
* values exported from a given membrane will live for the lifetime
* they would have had in the absence of an interposed membrane. Even
* when the membrane is revoked, all objects that would have been
* reachable in the absence of revocation will still be reachable, as
* far as the GC can tell, even though they will no longer be relevant
* to ongoing computation.
*
* <p>The API implemented here is approximately the API as implemented
* in FF6.0a1 and agreed to by MarkM, Andreas Gal, and Dave Herman,
* rather than the offially approved proposal page. TODO(erights):
* upgrade the ecmascript WeakMap proposal page to explain this API
* change and present to EcmaScript committee for their approval.
*
* <p>The first difference between the emulation here and that in
* FF6.0a1 is the presence of non enumerable {@code get___, has___,
* set___, and delete___} methods on WeakMap instances to represent
* what would be the hidden internal properties of a primitive
* implementation. Whereas the FF6.0a1 WeakMap.prototype methods
* require their {@code this} to be a genuine WeakMap instance (i.e.,
* an object of {@code [[Class]]} "WeakMap}), since there is nothing
* unforgeable about the pseudo-internal method names used here,
* nothing prevents these emulated prototype methods from being
* applied to non-WeakMaps with pseudo-internal methods of the same
* names.
*
* <p>Another difference is that our emulated {@code
* WeakMap.prototype} is not itself a WeakMap. A problem with the
* current FF6.0a1 API is that WeakMap.prototype is itself a WeakMap
* providing ambient mutability and an ambient communications
* channel. Thus, if a WeakMap is already present and has this
* problem, repairES5.js wraps it in a safe wrappper in order to
* prevent access to this channel. (See
* PATCH_MUTABLE_FROZEN_WEAKMAP_PROTO in repairES5.js).
*/
/**
* If this is a full <a href=
* "http://code.google.com/p/es-lab/wiki/SecureableES5"
* >secureable ES5</a> platform and the ES-Harmony {@code WeakMap} is
* absent, install an approximate emulation.
*
* <p>If WeakMap is present but cannot store some objects, use our approximate
* emulation as a wrapper.
*
* <p>If this is almost a secureable ES5 platform, then WeakMap.js
* should be run after repairES5.js.
*
* <p>See {@code WeakMap} for documentation of the garbage collection
* properties of this WeakMap emulation.
*/
(function WeakMapModule() {
"use strict";
if (typeof ses !== 'undefined' && ses.ok && !ses.ok()) {
// already too broken, so give up
return;
}
/**
* In some cases (current Firefox), we must make a choice betweeen a
* WeakMap which is capable of using all varieties of host objects as
* keys and one which is capable of safely using proxies as keys. See
* comments below about HostWeakMap and DoubleWeakMap for details.
*
* This function (which is a global, not exposed to guests) marks a
* WeakMap as permitted to do what is necessary to index all host
* objects, at the cost of making it unsafe for proxies.
*
* Do not apply this function to anything which is not a genuine
* fresh WeakMap.
*/
function weakMapPermitHostObjects(map) {
// identity of function used as a secret -- good enough and cheap
if (map.permitHostObjects___) {
map.permitHostObjects___(weakMapPermitHostObjects);
}
}
if (typeof ses !== 'undefined') {
ses.weakMapPermitHostObjects = weakMapPermitHostObjects;
}
// IE 11 has no Proxy but has a broken WeakMap such that we need to patch
// it using DoubleWeakMap; this flag tells DoubleWeakMap so.
var doubleWeakMapCheckSilentFailure = false;
// Check if there is already a good-enough WeakMap implementation, and if so
// exit without replacing it.
if (typeof WeakMap === 'function') {
var HostWeakMap = WeakMap;
// There is a WeakMap -- is it good enough?
if (typeof navigator !== 'undefined' &&
/Firefox/.test(navigator.userAgent)) {
// We're now *assuming not*, because as of this writing (2013-05-06)
// Firefox's WeakMaps have a miscellany of objects they won't accept, and
// we don't want to make an exhaustive list, and testing for just one
// will be a problem if that one is fixed alone (as they did for Event).
// If there is a platform that we *can* reliably test on, here's how to
// do it:
// var problematic = ... ;
// var testHostMap = new HostWeakMap();
// try {
// testHostMap.set(problematic, 1); // Firefox 20 will throw here
// if (testHostMap.get(problematic) === 1) {
// return;
// }
// } catch (e) {}
} else {
// IE 11 bug: WeakMaps silently fail to store frozen objects.
var testMap = new HostWeakMap();
var testObject = Object.freeze({});
testMap.set(testObject, 1);
if (testMap.get(testObject) !== 1) {
doubleWeakMapCheckSilentFailure = true;
// Fall through to installing our WeakMap.
} else {
module.exports = WeakMap;
return;
}
}
}
var hop = Object.prototype.hasOwnProperty;
var gopn = Object.getOwnPropertyNames;
var defProp = Object.defineProperty;
var isExtensible = Object.isExtensible;
/**
* Security depends on HIDDEN_NAME being both <i>unguessable</i> and
* <i>undiscoverable</i> by untrusted code.
*
* <p>Given the known weaknesses of Math.random() on existing
* browsers, it does not generate unguessability we can be confident
* of.
*
* <p>It is the monkey patching logic in this file that is intended
* to ensure undiscoverability. The basic idea is that there are
* three fundamental means of discovering properties of an object:
* The for/in loop, Object.keys(), and Object.getOwnPropertyNames(),
* as well as some proposed ES6 extensions that appear on our
* whitelist. The first two only discover enumerable properties, and
* we only use HIDDEN_NAME to name a non-enumerable property, so the
* only remaining threat should be getOwnPropertyNames and some
* proposed ES6 extensions that appear on our whitelist. We monkey
* patch them to remove HIDDEN_NAME from the list of properties they
* returns.
*
* <p>TODO(erights): On a platform with built-in Proxies, proxies
* could be used to trap and thereby discover the HIDDEN_NAME, so we
* need to monkey patch Proxy.create, Proxy.createFunction, etc, in
* order to wrap the provided handler with the real handler which
* filters out all traps using HIDDEN_NAME.
*
* <p>TODO(erights): Revisit Mike Stay's suggestion that we use an
* encapsulated function at a not-necessarily-secret name, which
* uses the Stiegler shared-state rights amplification pattern to
* reveal the associated value only to the WeakMap in which this key
* is associated with that value. Since only the key retains the
* function, the function can also remember the key without causing
* leakage of the key, so this doesn't violate our general gc
* goals. In addition, because the name need not be a guarded
* secret, we could efficiently handle cross-frame frozen keys.
*/
var HIDDEN_NAME_PREFIX = 'weakmap:';
var HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'ident:' + Math.random() + '___';
if (typeof crypto !== 'undefined' &&
typeof crypto.getRandomValues === 'function' &&
typeof ArrayBuffer === 'function' &&
typeof Uint8Array === 'function') {
var ab = new ArrayBuffer(25);
var u8s = new Uint8Array(ab);
crypto.getRandomValues(u8s);
HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'rand:' +
Array.prototype.map.call(u8s, function(u8) {
return (u8 % 36).toString(36);
}).join('') + '___';
}
function isNotHiddenName(name) {
return !(
name.substr(0, HIDDEN_NAME_PREFIX.length) == HIDDEN_NAME_PREFIX &&
name.substr(name.length - 3) === '___');
}
/**
* Monkey patch getOwnPropertyNames to avoid revealing the
* HIDDEN_NAME.
*
* <p>The ES5.1 spec requires each name to appear only once, but as
* of this writing, this requirement is controversial for ES6, so we
* made this code robust against this case. If the resulting extra
* search turns out to be expensive, we can probably relax this once
* ES6 is adequately supported on all major browsers, iff no browser
* versions we support at that time have relaxed this constraint
* without providing built-in ES6 WeakMaps.
*/
defProp(Object, 'getOwnPropertyNames', {
value: function fakeGetOwnPropertyNames(obj) {
return gopn(obj).filter(isNotHiddenName);
}
});
/**
* getPropertyNames is not in ES5 but it is proposed for ES6 and
* does appear in our whitelist, so we need to clean it too.
*/
if ('getPropertyNames' in Object) {
var originalGetPropertyNames = Object.getPropertyNames;
defProp(Object, 'getPropertyNames', {
value: function fakeGetPropertyNames(obj) {
return originalGetPropertyNames(obj).filter(isNotHiddenName);
}
});
}
/**
* <p>To treat objects as identity-keys with reasonable efficiency
* on ES5 by itself (i.e., without any object-keyed collections), we
* need to add a hidden property to such key objects when we
* can. This raises several issues:
* <ul>
* <li>Arranging to add this property to objects before we lose the
* chance, and
* <li>Hiding the existence of this new property from most
* JavaScript code.
* <li>Preventing <i>certification theft</i>, where one object is
* created falsely claiming to be the key of an association
* actually keyed by another object.
* <li>Preventing <i>value theft</i>, where untrusted code with
* access to a key object but not a weak map nevertheless
* obtains access to the value associated with that key in that
* weak map.
* </ul>
* We do so by
* <ul>
* <li>Making the name of the hidden property unguessable, so "[]"
* indexing, which we cannot intercept, cannot be used to access
* a property without knowing the name.
* <li>Making the hidden property non-enumerable, so we need not
* worry about for-in loops or {@code Object.keys},
* <li>monkey patching those reflective methods that would
* prevent extensions, to add this hidden property first,
* <li>monkey patching those methods that would reveal this
* hidden property.
* </ul>
* Unfortunately, because of same-origin iframes, we cannot reliably
* add this hidden property before an object becomes
* non-extensible. Instead, if we encounter a non-extensible object
* without a hidden record that we can detect (whether or not it has
* a hidden record stored under a name secret to us), then we just
* use the key object itself to represent its identity in a brute
* force leaky map stored in the weak map, losing all the advantages
* of weakness for these.
*/
function getHiddenRecord(key) {
if (key !== Object(key)) {
throw new TypeError('Not an object: ' + key);
}
var hiddenRecord = key[HIDDEN_NAME];
if (hiddenRecord && hiddenRecord.key === key) { return hiddenRecord; }
if (!isExtensible(key)) {
// Weak map must brute force, as explained in doc-comment above.
return void 0;
}
// The hiddenRecord and the key point directly at each other, via
// the "key" and HIDDEN_NAME properties respectively. The key
// field is for quickly verifying that this hidden record is an
// own property, not a hidden record from up the prototype chain.
//
// NOTE: Because this WeakMap emulation is meant only for systems like
// SES where Object.prototype is frozen without any numeric
// properties, it is ok to use an object literal for the hiddenRecord.
// This has two advantages:
// * It is much faster in a performance critical place
// * It avoids relying on Object.create(null), which had been
// problematic on Chrome 28.0.1480.0. See
// https://code.google.com/p/google-caja/issues/detail?id=1687
hiddenRecord = { key: key };
// When using this WeakMap emulation on platforms where
// Object.prototype might not be frozen and Object.create(null) is
// reliable, use the following two commented out lines instead.
// hiddenRecord = Object.create(null);
// hiddenRecord.key = key;
// Please contact us if you need this to work on platforms where
// Object.prototype might not be frozen and
// Object.create(null) might not be reliable.
try {
defProp(key, HIDDEN_NAME, {
value: hiddenRecord,
writable: false,
enumerable: false,
configurable: false
});
return hiddenRecord;
} catch (error) {
// Under some circumstances, isExtensible seems to misreport whether
// the HIDDEN_NAME can be defined.
// The circumstances have not been isolated, but at least affect
// Node.js v0.10.26 on TravisCI / Linux, but not the same version of
// Node.js on OS X.
return void 0;
}
}
/**
* Monkey patch operations that would make their argument
* non-extensible.
*
* <p>The monkey patched versions throw a TypeError if their
* argument is not an object, so it should only be done to functions
* that should throw a TypeError anyway if their argument is not an
* object.
*/
(function(){
var oldFreeze = Object.freeze;
defProp(Object, 'freeze', {
value: function identifyingFreeze(obj) {
getHiddenRecord(obj);
return oldFreeze(obj);
}
});
var oldSeal = Object.seal;
defProp(Object, 'seal', {
value: function identifyingSeal(obj) {
getHiddenRecord(obj);
return oldSeal(obj);
}
});
var oldPreventExtensions = Object.preventExtensions;
defProp(Object, 'preventExtensions', {
value: function identifyingPreventExtensions(obj) {
getHiddenRecord(obj);
return oldPreventExtensions(obj);
}
});
})();
function constFunc(func) {
func.prototype = null;
return Object.freeze(func);
}
var calledAsFunctionWarningDone = false;
function calledAsFunctionWarning() {
// Future ES6 WeakMap is currently (2013-09-10) expected to reject WeakMap()
// but we used to permit it and do it ourselves, so warn only.
if (!calledAsFunctionWarningDone && typeof console !== 'undefined') {
calledAsFunctionWarningDone = true;
console.warn('WeakMap should be invoked as new WeakMap(), not ' +
'WeakMap(). This will be an error in the future.');
}
}
var nextId = 0;
var OurWeakMap = function() {
if (!(this instanceof OurWeakMap)) { // approximate test for new ...()
calledAsFunctionWarning();
}
// We are currently (12/25/2012) never encountering any prematurely
// non-extensible keys.
var keys = []; // brute force for prematurely non-extensible keys.
var values = []; // brute force for corresponding values.
var id = nextId++;
function get___(key, opt_default) {
var index;
var hiddenRecord = getHiddenRecord(key);
if (hiddenRecord) {
return id in hiddenRecord ? hiddenRecord[id] : opt_default;
} else {
index = keys.indexOf(key);
return index >= 0 ? values[index] : opt_default;
}
}
function has___(key) {
var hiddenRecord = getHiddenRecord(key);
if (hiddenRecord) {
return id in hiddenRecord;
} else {
return keys.indexOf(key) >= 0;
}
}
function set___(key, value) {
var index;
var hiddenRecord = getHiddenRecord(key);
if (hiddenRecord) {
hiddenRecord[id] = value;
} else {
index = keys.indexOf(key);
if (index >= 0) {
values[index] = value;
} else {
// Since some browsers preemptively terminate slow turns but
// then continue computing with presumably corrupted heap
// state, we here defensively get keys.length first and then
// use it to update both the values and keys arrays, keeping
// them in sync.
index = keys.length;
values[index] = value;
// If we crash here, values will be one longer than keys.
keys[index] = key;
}
}
return this;
}
function delete___(key) {
var hiddenRecord = getHiddenRecord(key);
var index, lastIndex;
if (hiddenRecord) {
return id in hiddenRecord && delete hiddenRecord[id];
} else {
index = keys.indexOf(key);
if (index < 0) {
return false;
}
// Since some browsers preemptively terminate slow turns but
// then continue computing with potentially corrupted heap
// state, we here defensively get keys.length first and then use
// it to update both the keys and the values array, keeping
// them in sync. We update the two with an order of assignments,
// such that any prefix of these assignments will preserve the
// key/value correspondence, either before or after the delete.
// Note that this needs to work correctly when index === lastIndex.
lastIndex = keys.length - 1;
keys[index] = void 0;
// If we crash here, there's a void 0 in the keys array, but
// no operation will cause a "keys.indexOf(void 0)", since
// getHiddenRecord(void 0) will always throw an error first.
values[index] = values[lastIndex];
// If we crash here, values[index] cannot be found here,
// because keys[index] is void 0.
keys[index] = keys[lastIndex];
// If index === lastIndex and we crash here, then keys[index]
// is still void 0, since the aliasing killed the previous key.
keys.length = lastIndex;
// If we crash here, keys will be one shorter than values.
values.length = lastIndex;
return true;
}
}
return Object.create(OurWeakMap.prototype, {
get___: { value: constFunc(get___) },
has___: { value: constFunc(has___) },
set___: { value: constFunc(set___) },
delete___: { value: constFunc(delete___) }
});
};
OurWeakMap.prototype = Object.create(Object.prototype, {
get: {
/**
* Return the value most recently associated with key, or
* opt_default if none.
*/
value: function get(key, opt_default) {
return this.get___(key, opt_default);
},
writable: true,
configurable: true
},
has: {
/**
* Is there a value associated with key in this WeakMap?
*/
value: function has(key) {
return this.has___(key);
},
writable: true,
configurable: true
},
set: {
/**
* Associate value with key in this WeakMap, overwriting any
* previous association if present.
*/
value: function set(key, value) {
return this.set___(key, value);
},
writable: true,
configurable: true
},
'delete': {
/**
* Remove any association for key in this WeakMap, returning
* whether there was one.
*
* <p>Note that the boolean return here does not work like the
* {@code delete} operator. The {@code delete} operator returns
* whether the deletion succeeds at bringing about a state in
* which the deleted property is absent. The {@code delete}
* operator therefore returns true if the property was already
* absent, whereas this {@code delete} method returns false if
* the association was already absent.
*/
value: function remove(key) {
return this.delete___(key);
},
writable: true,
configurable: true
}
});
if (typeof HostWeakMap === 'function') {
(function() {
// If we got here, then the platform has a WeakMap but we are concerned
// that it may refuse to store some key types. Therefore, make a map
// implementation which makes use of both as possible.
// In this mode we are always using double maps, so we are not proxy-safe.
// This combination does not occur in any known browser, but we had best
// be safe.
if (doubleWeakMapCheckSilentFailure && typeof Proxy !== 'undefined') {
Proxy = undefined;
}
function DoubleWeakMap() {
if (!(this instanceof OurWeakMap)) { // approximate test for new ...()
calledAsFunctionWarning();
}
// Preferable, truly weak map.
var hmap = new HostWeakMap();
// Our hidden-property-based pseudo-weak-map. Lazily initialized in the
// 'set' implementation; thus we can avoid performing extra lookups if
// we know all entries actually stored are entered in 'hmap'.
var omap = undefined;
// Hidden-property maps are not compatible with proxies because proxies
// can observe the hidden name and either accidentally expose it or fail
// to allow the hidden property to be set. Therefore, we do not allow
// arbitrary WeakMaps to switch to using hidden properties, but only
// those which need the ability, and unprivileged code is not allowed
// to set the flag.
//
// (Except in doubleWeakMapCheckSilentFailure mode in which case we
// disable proxies.)
var enableSwitching = false;
function dget(key, opt_default) {
if (omap) {
return hmap.has(key) ? hmap.get(key)
: omap.get___(key, opt_default);
} else {
return hmap.get(key, opt_default);
}
}
function dhas(key) {
return hmap.has(key) || (omap ? omap.has___(key) : false);
}
var dset;
if (doubleWeakMapCheckSilentFailure) {
dset = function(key, value) {
hmap.set(key, value);
if (!hmap.has(key)) {
if (!omap) { omap = new OurWeakMap(); }
omap.set(key, value);
}
return this;
};
} else {
dset = function(key, value) {
if (enableSwitching) {
try {
hmap.set(key, value);
} catch (e) {
if (!omap) { omap = new OurWeakMap(); }
omap.set___(key, value);
}
} else {
hmap.set(key, value);
}
return this;
};
}
function ddelete(key) {
var result = !!hmap['delete'](key);
if (omap) { return omap.delete___(key) || result; }
return result;
}
return Object.create(OurWeakMap.prototype, {
get___: { value: constFunc(dget) },
has___: { value: constFunc(dhas) },
set___: { value: constFunc(dset) },
delete___: { value: constFunc(ddelete) },
permitHostObjects___: { value: constFunc(function(token) {
if (token === weakMapPermitHostObjects) {
enableSwitching = true;
} else {
throw new Error('bogus call to permitHostObjects___');
}
})}
});
}
DoubleWeakMap.prototype = OurWeakMap.prototype;
module.exports = DoubleWeakMap;
// define .constructor to hide OurWeakMap ctor
Object.defineProperty(WeakMap.prototype, 'constructor', {
value: WeakMap,
enumerable: false, // as default .constructor is
configurable: true,
writable: true
});
})();
} else {
// There is no host WeakMap, so we must use the emulation.
// Emulated WeakMaps are incompatible with native proxies (because proxies
// can observe the hidden name), so we must disable Proxy usage (in
// ArrayLike and Domado, currently).
if (typeof Proxy !== 'undefined') {
Proxy = undefined;
}
module.exports = OurWeakMap;
}
})();
},{}],108:[function(require,module,exports){
'use strict'
var weakMap = typeof WeakMap === 'undefined' ? require('weak-map') : WeakMap
var WebGLEWStruct = new weakMap()
function baseName(ext_name) {
return ext_name.replace(/^[A-Z]+_/, '')
}
function initWebGLEW(gl) {
var struct = WebGLEWStruct.get(gl)
if(struct) {
return struct
}
var extensions = {}
var supported = gl.getSupportedExtensions()
for(var i=0; i<supported.length; ++i) {
var extName = supported[i]
//Skip MOZ_ extensions
if(extName.indexOf('MOZ_') === 0) {
continue
}
var ext = gl.getExtension(supported[i])
if(!ext) {
continue
}
while(true) {
extensions[extName] = ext
var base = baseName(extName)
if(base === extName) {
break
}
extName = base
}
}
WebGLEWStruct.set(gl, extensions)
return extensions
}
module.exports = initWebGLEW
},{"weak-map":107}],109:[function(require,module,exports){
"use strict"
function doBind(gl, elements, attributes) {
if(elements) {
elements.bind()
} else {
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null)
}
var nattribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS)|0
if(attributes) {
if(attributes.length > nattribs) {
throw new Error("gl-vao: Too many vertex attributes")
}
for(var i=0; i<attributes.length; ++i) {
var attrib = attributes[i]
if(attrib.buffer) {
var buffer = attrib.buffer
var size = attrib.size || 4
var type = attrib.type || gl.FLOAT
var normalized = !!attrib.normalized
var stride = attrib.stride || 0
var offset = attrib.offset || 0
buffer.bind()
gl.enableVertexAttribArray(i)
gl.vertexAttribPointer(i, size, type, normalized, stride, offset)
} else {
if(typeof attrib === "number") {
gl.vertexAttrib1f(i, attrib)
} else if(attrib.length === 1) {
gl.vertexAttrib1f(i, attrib[0])
} else if(attrib.length === 2) {
gl.vertexAttrib2f(i, attrib[0], attrib[1])
} else if(attrib.length === 3) {
gl.vertexAttrib3f(i, attrib[0], attrib[1], attrib[2])
} else if(attrib.length === 4) {
gl.vertexAttrib4f(i, attrib[0], attrib[1], attrib[2], attrib[3])
} else {
throw new Error("gl-vao: Invalid vertex attribute")
}
gl.disableVertexAttribArray(i)
}
}
for(; i<nattribs; ++i) {
gl.disableVertexAttribArray(i)
}
} else {
gl.bindBuffer(gl.ARRAY_BUFFER, null)
for(var i=0; i<nattribs; ++i) {
gl.disableVertexAttribArray(i)
}
}
}
module.exports = doBind
},{}],110:[function(require,module,exports){
"use strict"
var bindAttribs = require("./do-bind.js")
function VAOEmulated(gl) {
this.gl = gl
this._elements = null
this._attributes = null
this._elementsType = gl.UNSIGNED_SHORT
}
VAOEmulated.prototype.bind = function() {
bindAttribs(this.gl, this._elements, this._attributes)
}
VAOEmulated.prototype.update = function(attributes, elements, elementsType) {
this._elements = elements
this._attributes = attributes
this._elementsType = elementsType || this.gl.UNSIGNED_SHORT
}
VAOEmulated.prototype.dispose = function() { }
VAOEmulated.prototype.unbind = function() { }
VAOEmulated.prototype.draw = function(mode, count, offset) {
offset = offset || 0
var gl = this.gl
if(this._elements) {
gl.drawElements(mode, count, this._elementsType, offset)
} else {
gl.drawArrays(mode, offset, count)
}
}
function createVAOEmulated(gl) {
return new VAOEmulated(gl)
}
module.exports = createVAOEmulated
},{"./do-bind.js":109}],111:[function(require,module,exports){
"use strict"
var bindAttribs = require("./do-bind.js")
function VertexAttribute(location, dimension, a, b, c, d) {
this.location = location
this.dimension = dimension
this.a = a
this.b = b
this.c = c
this.d = d
}
VertexAttribute.prototype.bind = function(gl) {
switch(this.dimension) {
case 1:
gl.vertexAttrib1f(this.location, this.a)
break
case 2:
gl.vertexAttrib2f(this.location, this.a, this.b)
break
case 3:
gl.vertexAttrib3f(this.location, this.a, this.b, this.c)
break
case 4:
gl.vertexAttrib4f(this.location, this.a, this.b, this.c, this.d)
break
}
}
function VAONative(gl, ext, handle) {
this.gl = gl
this._ext = ext
this.handle = handle
this._attribs = []
this._useElements = false
this._elementsType = gl.UNSIGNED_SHORT
}
VAONative.prototype.bind = function() {
this._ext.bindVertexArrayOES(this.handle)
for(var i=0; i<this._attribs.length; ++i) {
this._attribs[i].bind(this.gl)
}
}
VAONative.prototype.unbind = function() {
this._ext.bindVertexArrayOES(null)
}
VAONative.prototype.dispose = function() {
this._ext.deleteVertexArrayOES(this.handle)
}
VAONative.prototype.update = function(attributes, elements, elementsType) {
this.bind()
bindAttribs(this.gl, elements, attributes)
this.unbind()
this._attribs.length = 0
if(attributes)
for(var i=0; i<attributes.length; ++i) {
var a = attributes[i]
if(typeof a === "number") {
this._attribs.push(new VertexAttribute(i, 1, a))
} else if(Array.isArray(a)) {
this._attribs.push(new VertexAttribute(i, a.length, a[0], a[1], a[2], a[3]))
}
}
this._useElements = !!elements
this._elementsType = elementsType || this.gl.UNSIGNED_SHORT
}
VAONative.prototype.draw = function(mode, count, offset) {
offset = offset || 0
var gl = this.gl
if(this._useElements) {
gl.drawElements(mode, count, this._elementsType, offset)
} else {
gl.drawArrays(mode, offset, count)
}
}
function createVAONative(gl, ext) {
return new VAONative(gl, ext, ext.createVertexArrayOES())
}
module.exports = createVAONative
},{"./do-bind.js":109}],112:[function(require,module,exports){
arguments[4][107][0].apply(exports,arguments)
},{"dup":107}],113:[function(require,module,exports){
arguments[4][108][0].apply(exports,arguments)
},{"dup":108,"weak-map":112}],114:[function(require,module,exports){
"use strict"
var webglew = require("webglew")
var createVAONative = require("./lib/vao-native.js")
var createVAOEmulated = require("./lib/vao-emulated.js")
function createVAO(gl, attributes, elements, elementsType) {
var ext = webglew(gl).OES_vertex_array_object
var vao
if(ext) {
vao = createVAONative(gl, ext)
} else {
vao = createVAOEmulated(gl)
}
vao.update(attributes, elements, elementsType)
return vao
}
module.exports = createVAO
},{"./lib/vao-emulated.js":110,"./lib/vao-native.js":111,"webglew":113}],115:[function(require,module,exports){
"use strict"
var createShader = require("gl-shader")
module.exports = function createSimple3DShader(gl) {
return createShader(gl,
"attribute vec3 position;\
attribute vec3 color;\
uniform mat4 model;\
uniform mat4 view;\
uniform mat4 projection;\
varying vec3 fragColor;\
void main() {\
gl_Position = projection * view * model * vec4(position,1);\
fragColor = color;\
}",
"precision highp float;\
varying vec3 fragColor;\
void main() {\
gl_FragColor = vec4(fragColor, 1.0);\
}")
}
},{"gl-shader":116}],116:[function(require,module,exports){
"use strict"
var glslExports = require("glsl-exports")
var uniq = require("uniq")
function Shader(gl, prog, uniforms, attributes) {
this.gl = gl
this.program = prog
this.uniforms = uniforms
this.attributes = attributes
}
Shader.prototype.bind = function() {
this.gl.useProgram(this.program)
}
function kvPairs(obj) {
return Object.keys(obj).map(function(x) { return [x, obj[x]] })
}
function makeVectorUniform(gl, prog, location, obj, type, d, name) {
if(d > 1) {
type += "v"
}
var setter = new Function("gl", "prog", "v", "gl.uniform" + d + type + "(gl.getUniformLocation(prog,'"+name+"'), v)")
var getter = new Function("gl", "prog", "return gl.getUniform(prog, gl.getUniformLocation(prog,'"+name+"'))")
Object.defineProperty(obj, name, {
set: setter.bind(undefined, gl, prog),
get: getter.bind(undefined, gl, prog),
enumerable: true
})
}
function makeMatrixUniform(gl, prog, location, obj, d, name) {
var setter = new Function("gl", "prog", "v", "gl.uniformMatrix" + d + "fv(gl.getUniformLocation(prog,'"+name+"'), false, v)")
var getter = new Function("gl", "prog", "return gl.getUniform(prog, gl.getUniformLocation(prog,'"+name+"'))")
Object.defineProperty(obj, name, {
set: setter.bind(undefined, gl, prog),
get: getter.bind(undefined, gl, prog),
enumerable: true
})
}
function makeVectorAttrib(gl, prog, location, obj, d, name) {
var out = {}
out.pointer = function attribPointer(type, normalized, stride, offset) {
gl.vertexAttribPointer(location, d, type||gl.FLOAT, normalized?gl.TRUE:gl.FALSE, stride||0, offset||0)
}
out.enable = function enableAttrib() {
gl.enableVertexAttribArray(location)
}
out.disable = function disableAttrib() {
gl.disableVertexAttribArray(location)
}
Object.defineProperty(out, "location", {
get: function() {
return location
},
set: function(v) {
if(v !== location) {
location = v
gl.bindAttribLocation(prog, v, name)
gl.linkProgram(prog)
}
return v
}
})
var constFuncArgs = [ "gl", "v" ]
var var_names = []
for(var i=0; i<d; ++i) {
constFuncArgs.push("x"+i)
var_names.push("x"+i)
}
constFuncArgs.push([
"if(x0.length === undefined) {",
"return gl.vertexAttrib"+d+"f(v," + var_names.join(",") + ")",
"} else {",
"return gl.vertexAttrib" + d + "fv(v,x0)",
"}"
].join("\n"))
var constFunc = Function.apply(undefined, constFuncArgs)
out.set = function setAttrib(x, y, z, w) {
return constFunc(gl, location, x, y, z, w)
}
Object.defineProperty(obj, name, {
set: function(x) {
out.isArray = false
constFunc(gl, location, x)
return x
},
get: function() {
return out
},
enumerable: true
})
}
function makeShader(gl, vert_source, frag_source) {
var vert_shader = gl.createShader(gl.VERTEX_SHADER)
gl.shaderSource(vert_shader, vert_source)
gl.compileShader(vert_shader)
if(!gl.getShaderParameter(vert_shader, gl.COMPILE_STATUS)) {
throw new Error("Error compiling vertex shader: " + gl.getShaderInfoLog(vert_shader))
}
var frag_shader = gl.createShader(gl.FRAGMENT_SHADER)
gl.shaderSource(frag_shader, frag_source)
gl.compileShader(frag_shader)
if(!gl.getShaderParameter(frag_shader, gl.COMPILE_STATUS)) {
throw new Error("Error compiling fragment shader: " + gl.getShaderInfoLog(frag_shader))
}
var program = gl.createProgram()
gl.attachShader(program, frag_shader)
gl.attachShader(program, vert_shader)
gl.linkProgram(program)
if(!gl.getProgramParameter(program, gl.LINK_STATUS)) {
throw new Error("Error linking shader program: " + gl.getProgramInfoLog (program))
}
var frag_exports = glslExports(frag_source)
var vert_exports = glslExports(vert_source)
//Bind uniforms
var uniforms = uniq(
kvPairs(frag_exports.uniforms)
.concat(kvPairs(vert_exports.uniforms)),
function compare(a,b) {
return a[0] < b[0] ? -1 : (a[0] === b[0] ? 0 : 1)
})
var uniform_fields = {}
for(var i=0; i<uniforms.length; ++i) {
var u = uniforms[i]
var name = u[0]
var type = u[1]
var x = gl.getUniformLocation(program, name)
if(!x) {
Object.defineProperty(uniform_fields, name, {
get: function() { },
set: function() { }
})
continue
}
switch(type) {
case "bool":
case "int":
case "sampler2D":
case "samplerCube":
makeVectorUniform(gl, program, x, uniform_fields, "i", 1, name)
break
case "float":
makeVectorUniform(gl, program, x, uniform_fields, "f", 1, name)
break
default:
if(type.indexOf("vec") >= 0) {
var d = type.charCodeAt(type.length-1) - 48
if(d < 2 || d > 4) {
throw new Error("Invalid data type")
}
switch(type.charAt(0)) {
case "b":
case "i":
makeVectorUniform(gl, program, x, uniform_fields, "i", d, name)
break
case "v":
makeVectorUniform(gl, program, x, uniform_fields, "f", d, name)
break
default:
throw new Error("Unrecognized data type")
}
} else if(type.charAt(0) === "m") {
var d = type.charCodeAt(type.length-1) - 48
if(d < 2 || d > 4) {
throw new Error("Invalid data type")
}
makeMatrixUniform(gl, program, x, uniform_fields, d, name)
} else {
throw new Error("Invalid data type")
}
break
}
}
//Bind attributes
var attributes = kvPairs(vert_exports.attributes)
var attribute_fields = {}
for(var i=0; i<attributes.length; ++i) {
var u = attributes[i]
var name = u[0]
var type = u[1]
var x = gl.getAttribLocation(program, name)
switch(type) {
case "bool":
case "int":
case "float":
makeVectorAttrib(gl, program, x, attribute_fields, 1, name)
break
default:
if(type.indexOf("vec") >= 0) {
var d = type.charCodeAt(type.length-1) - 48
if(d < 2 || d > 4) {
throw new Error("Invalid data type")
}
makeVectorAttrib(gl, program, x, attribute_fields, d, name)
} else {
throw new Error("Invalid data type")
}
break
}
}
return new Shader(gl, program, uniform_fields, attribute_fields)
}
module.exports = makeShader
},{"glsl-exports":117,"uniq":128}],117:[function(require,module,exports){
"use strict"
var glslTokenizer = require("glsl-tokenizer")
var glslParser = require("glsl-parser")
var through = require("through")
function parseDeclaration(x) {
var type, identifiers = [], i
for(var i=0; i<x.children.length; ++i) {
var c = x.children[i]
if(c.type === "placeholder") {
continue
} else if(c.type === "keyword") {
if(c.token.data === "uniform" ||
c.token.data === "attribute") {
continue
}
type = c.token.data
} else if(c.type === "decllist") {
for(var j=0; j<c.children.length; ++j) {
var d = c.children[j]
if(d.type === "ident") {
identifiers.push(d.token.data)
}
}
}
}
return {
type: type,
vars: identifiers
}
}
function glslGlobals(src) {
var uniforms = {}
var attributes = {}
var strm = through()
strm.pipe(glslTokenizer()).pipe(glslParser()).on('data', function(x) {
if(x.type === "decl" && x.token.type === "keyword") {
if(x.token.data === "uniform") {
var result = parseDeclaration(x)
for(var i=0; i<result.vars.length; ++i) {
uniforms[result.vars[i]] = result.type
}
} else if(x.token.data === "attribute") {
var result = parseDeclaration(x)
for(var i=0; i<result.vars.length; ++i) {
attributes[result.vars[i]] = result.type
}
}
}
})
strm.write(src)
return {
uniforms: uniforms,
attributes: attributes
};
}
module.exports = glslGlobals
},{"glsl-parser":118,"glsl-tokenizer":123,"through":127}],118:[function(require,module,exports){
module.exports = require('./lib/index')
},{"./lib/index":120}],119:[function(require,module,exports){
var state
, token
, tokens
, idx
var original_symbol = {
nud: function() { return this.children && this.children.length ? this : fail('unexpected')() }
, led: fail('missing operator')
}
var symbol_table = {}
function itself() {
return this
}
symbol('(ident)').nud = itself
symbol('(keyword)').nud = itself
symbol('(builtin)').nud = itself
symbol('(literal)').nud = itself
symbol('(end)')
symbol(':')
symbol(';')
symbol(',')
symbol(')')
symbol(']')
symbol('}')
infixr('&&', 30)
infixr('||', 30)
infix('|', 43)
infix('^', 44)
infix('&', 45)
infix('==', 46)
infix('!=', 46)
infix('<', 47)
infix('<=', 47)
infix('>', 47)
infix('>=', 47)
infix('>>', 48)
infix('<<', 48)
infix('+', 50)
infix('-', 50)
infix('*', 60)
infix('/', 60)
infix('%', 60)
infix('?', 20, function(left) {
this.children = [left, expression(0), (advance(':'), expression(0))]
this.type = 'ternary'
return this
})
infix('.', 80, function(left) {
token.type = 'literal'
state.fake(token)
this.children = [left, token]
advance()
return this
})
infix('[', 80, function(left) {
this.children = [left, expression(0)]
this.type = 'binary'
advance(']')
return this
})
infix('(', 80, function(left) {
this.children = [left]
this.type = 'call'
if(token.data !== ')') while(1) {
this.children.push(expression(0))
if(token.data !== ',') break
advance(',')
}
advance(')')
return this
})
prefix('-')
prefix('+')
prefix('!')
prefix('~')
prefix('defined')
prefix('(', function() {
this.type = 'group'
this.children = [expression(0)]
advance(')')
return this
})
prefix('++')
prefix('--')
suffix('++')
suffix('--')
assignment('=')
assignment('+=')
assignment('-=')
assignment('*=')
assignment('/=')
assignment('%=')
assignment('&=')
assignment('|=')
assignment('^=')
assignment('>>=')
assignment('<<=')
module.exports = function(incoming_state, incoming_tokens) {
state = incoming_state
tokens = incoming_tokens
idx = 0
var result
if(!tokens.length) return
advance()
result = expression(0)
result.parent = state[0]
emit(result)
if(idx < tokens.length) {
throw new Error('did not use all tokens')
}
result.parent.children = [result]
function emit(node) {
state.unshift(node, false)
for(var i = 0, len = node.children.length; i < len; ++i) {
emit(node.children[i])
}
state.shift()
}
}
function symbol(id, binding_power) {
var sym = symbol_table[id]
binding_power = binding_power || 0
if(sym) {
if(binding_power > sym.lbp) {
sym.lbp = binding_power
}
} else {
sym = Object.create(original_symbol)
sym.id = id
sym.lbp = binding_power
symbol_table[id] = sym
}
return sym
}
function expression(rbp) {
var left, t = token
advance()
left = t.nud()
while(rbp < token.lbp) {
t = token
advance()
left = t.led(left)
}
return left
}
function infix(id, bp, led) {
var sym = symbol(id, bp)
sym.led = led || function(left) {
this.children = [left, expression(bp)]
this.type = 'binary'
return this
}
}
function infixr(id, bp, led) {
var sym = symbol(id, bp)
sym.led = led || function(left) {
this.children = [left, expression(bp - 1)]
this.type = 'binary'
return this
}
return sym
}
function prefix(id, nud) {
var sym = symbol(id)
sym.nud = nud || function() {
this.children = [expression(70)]
this.type = 'unary'
return this
}
return sym
}
function suffix(id) {
var sym = symbol(id, 150)
sym.led = function(left) {
this.children = [left]
this.type = 'suffix'
return this
}
}
function assignment(id) {
return infixr(id, 10, function(left) {
this.children = [left, expression(9)]
this.assignment = true
this.type = 'assign'
return this
})
}
function advance(id) {
var next
, value
, type
, output
if(id && token.data !== id) {
return state.unexpected('expected `'+ id + '`, got `'+token.data+'`')
}
if(idx >= tokens.length) {
token = symbol_table['(end)']
return
}
next = tokens[idx++]
value = next.data
type = next.type
if(type === 'ident') {
output = state.scope.find(value) || state.create_node()
type = output.type
} else if(type === 'builtin') {
output = symbol_table['(builtin)']
} else if(type === 'keyword') {
output = symbol_table['(keyword)']
} else if(type === 'operator') {
output = symbol_table[value]
if(!output) {
return state.unexpected('unknown operator `'+value+'`')
}
} else if(type === 'float' || type === 'integer') {
type = 'literal'
output = symbol_table['(literal)']
} else {
return state.unexpected('unexpected token.')
}
if(output) {
if(!output.nud) { output.nud = itself }
if(!output.children) { output.children = [] }
}
output = Object.create(output)
output.token = next
output.type = type
if(!output.data) output.data = value
return token = output
}
function fail(message) {
return function() { return state.unexpected(message) }
}
},{}],120:[function(require,module,exports){
module.exports = parser
var through = require('through')
, full_parse_expr = require('./expr')
, Scope = require('./scope')
// singleton!
var Advance = new Object
var DEBUG = false
var _ = 0
, IDENT = _++
, STMT = _++
, STMTLIST = _++
, STRUCT = _++
, FUNCTION = _++
, FUNCTIONARGS = _++
, DECL = _++
, DECLLIST = _++
, FORLOOP = _++
, WHILELOOP = _++
, IF = _++
, EXPR = _++
, PRECISION = _++
, COMMENT = _++
, PREPROCESSOR = _++
, KEYWORD = _++
, KEYWORD_OR_IDENT = _++
, RETURN = _++
, BREAK = _++
, CONTINUE = _++
, DISCARD = _++
, DOWHILELOOP = _++
, PLACEHOLDER = _++
, QUANTIFIER = _++
var DECL_ALLOW_ASSIGN = 0x1
, DECL_ALLOW_COMMA = 0x2
, DECL_REQUIRE_NAME = 0x4
, DECL_ALLOW_INVARIANT = 0x8
, DECL_ALLOW_STORAGE = 0x10
, DECL_NO_INOUT = 0x20
, DECL_ALLOW_STRUCT = 0x40
, DECL_STATEMENT = 0xFF
, DECL_FUNCTION = DECL_STATEMENT & ~(DECL_ALLOW_ASSIGN | DECL_ALLOW_COMMA | DECL_NO_INOUT | DECL_ALLOW_INVARIANT | DECL_REQUIRE_NAME)
, DECL_STRUCT = DECL_STATEMENT & ~(DECL_ALLOW_ASSIGN | DECL_ALLOW_INVARIANT | DECL_ALLOW_STORAGE | DECL_ALLOW_STRUCT)
var QUALIFIERS = ['const', 'attribute', 'uniform', 'varying']
var NO_ASSIGN_ALLOWED = false
, NO_COMMA_ALLOWED = false
// map of tokens to stmt types
var token_map = {
'block-comment': COMMENT
, 'line-comment': COMMENT
, 'preprocessor': PREPROCESSOR
}
// map of stmt types to human
var stmt_type = _ = [
'ident'
, 'stmt'
, 'stmtlist'
, 'struct'
, 'function'
, 'functionargs'
, 'decl'
, 'decllist'
, 'forloop'
, 'whileloop'
, 'if'
, 'expr'
, 'precision'
, 'comment'
, 'preprocessor'
, 'keyword'
, 'keyword_or_ident'
, 'return'
, 'break'
, 'continue'
, 'discard'
, 'do-while'
, 'placeholder'
, 'quantifier'
]
function parser() {
var stmtlist = n(STMTLIST)
, stmt = n(STMT)
, decllist = n(DECLLIST)
, precision = n(PRECISION)
, ident = n(IDENT)
, keyword_or_ident = n(KEYWORD_OR_IDENT)
, fn = n(FUNCTION)
, fnargs = n(FUNCTIONARGS)
, forstmt = n(FORLOOP)
, ifstmt = n(IF)
, whilestmt = n(WHILELOOP)
, returnstmt = n(RETURN)
, dowhilestmt = n(DOWHILELOOP)
, quantifier = n(QUANTIFIER)
var parse_struct
, parse_precision
, parse_quantifier
, parse_forloop
, parse_if
, parse_return
, parse_whileloop
, parse_dowhileloop
, parse_function
, parse_function_args
var stream = through(write, end)
, check = arguments.length ? [].slice.call(arguments) : []
, depth = 0
, state = []
, tokens = []
, whitespace = []
, errored = false
, program
, token
, node
// setup state
state.shift = special_shift
state.unshift = special_unshift
state.fake = special_fake
state.unexpected = unexpected
state.scope = new Scope(state)
state.create_node = function() {
var n = mknode(IDENT, token)
n.parent = stream.program
return n
}
setup_stative_parsers()
// setup root node
node = stmtlist()
node.expecting = '(eof)'
node.mode = STMTLIST
node.token = {type: '(program)', data: '(program)'}
program = node
stream.program = program
stream.scope = function(scope) {
if(arguments.length === 1) {
state.scope = scope
}
return state.scope
}
state.unshift(node)
return stream
// stream functions ---------------------------------------------
function write(input) {
if(input.type === 'whitespace' || input.type === 'line-comment' || input.type === 'block-comment') {
whitespace.push(input)
return
}
tokens.push(input)
token = token || tokens[0]
if(token && whitespace.length) {
token.preceding = token.preceding || []
token.preceding = token.preceding.concat(whitespace)
whitespace = []
}
while(take()) switch(state[0].mode) {
case STMT: parse_stmt(); break
case STMTLIST: parse_stmtlist(); break
case DECL: parse_decl(); break
case DECLLIST: parse_decllist(); break
case EXPR: parse_expr(); break
case STRUCT: parse_struct(true, true); break
case PRECISION: parse_precision(); break
case IDENT: parse_ident(); break
case KEYWORD: parse_keyword(); break
case KEYWORD_OR_IDENT: parse_keyword_or_ident(); break
case FUNCTION: parse_function(); break
case FUNCTIONARGS: parse_function_args(); break
case FORLOOP: parse_forloop(); break
case WHILELOOP: parse_whileloop(); break
case DOWHILELOOP: parse_dowhileloop(); break
case RETURN: parse_return(); break
case IF: parse_if(); break
case QUANTIFIER: parse_quantifier(); break
}
}
function end(tokens) {
if(arguments.length) {
write(tokens)
}
if(state.length > 1) {
unexpected('unexpected EOF')
return
}
stream.emit('end')
}
function take() {
if(errored || !state.length)
return false
return (token = tokens[0]) && !stream.paused
}
// ----- state manipulation --------
function special_fake(x) {
state.unshift(x)
state.shift()
}
function special_unshift(_node, add_child) {
_node.parent = state[0]
var ret = [].unshift.call(this, _node)
add_child = add_child === undefined ? true : add_child
if(DEBUG) {
var pad = ''
for(var i = 0, len = this.length - 1; i < len; ++i) {
pad += ' |'
}
console.log(pad, '\\'+_node.type, _node.token.data)
}
if(add_child && node !== _node) node.children.push(_node)
node = _node
return ret
}
function special_shift() {
var _node = [].shift.call(this)
, okay = check[this.length]
, emit = false
if(DEBUG) {
var pad = ''
for(var i = 0, len = this.length; i < len; ++i) {
pad += ' |'
}
console.log(pad, '/'+_node.type)
}
if(check.length) {
if(typeof check[0] === 'function') {
emit = check[0](_node)
} else if(okay !== undefined) {
emit = okay.test ? okay.test(_node.type) : okay === _node.type
}
} else {
emit = true
}
if(emit) stream.emit('data', _node)
node = _node.parent
return _node
}
// parse states ---------------
function parse_stmtlist() {
// determine the type of the statement
// and then start parsing
return stative(
function() { state.scope.enter(); return Advance }
, normal_mode
)()
function normal_mode() {
if(token.data === state[0].expecting) {
return state.scope.exit(), state.shift()
}
switch(token.type) {
case 'preprocessor':
state.fake(adhoc())
tokens.shift()
return
default:
state.unshift(stmt())
return
}
}
}
function parse_stmt() {
if(state[0].brace) {
if(token.data !== '}') {
return unexpected('expected `}`, got '+token.data)
}
state[0].brace = false
return tokens.shift(), state.shift()
}
switch(token.type) {
case 'eof': return state.shift()
case 'keyword':
switch(token.data) {
case 'for': return state.unshift(forstmt());
case 'if': return state.unshift(ifstmt());
case 'while': return state.unshift(whilestmt());
case 'do': return state.unshift(dowhilestmt());
case 'break': return state.fake(mknode(BREAK, token)), tokens.shift()
case 'continue': return state.fake(mknode(CONTINUE, token)), tokens.shift()
case 'discard': return state.fake(mknode(DISCARD, token)), tokens.shift()
case 'return': return state.unshift(returnstmt());
case 'precision': return state.unshift(precision());
}
return state.unshift(decl(DECL_STATEMENT))
case 'ident':
var lookup
if(lookup = state.scope.find(token.data)) {
if(lookup.parent.type === 'struct') {
// this is strictly untrue, you could have an
// expr that starts with a struct constructor.
// ... sigh
return state.unshift(decl(DECL_STATEMENT))
}
return state.unshift(expr(';'))
}
case 'operator':
if(token.data === '{') {
state[0].brace = true
var n = stmtlist()
n.expecting = '}'
return tokens.shift(), state.unshift(n)
}
if(token.data === ';') {
return tokens.shift(), state.shift()
}
default: return state.unshift(expr(';'))
}
}
function parse_decl() {
var stmt = state[0]
return stative(
invariant_or_not,
storage_or_not,
parameter_or_not,
precision_or_not,
struct_or_type,
maybe_name,
maybe_lparen, // lparen means we're a function
is_decllist,
done
)()
function invariant_or_not() {
if(token.data === 'invariant') {
if(stmt.flags & DECL_ALLOW_INVARIANT) {
state.unshift(keyword())
return Advance
} else {
return unexpected('`invariant` is not allowed here')
}
} else {
state.fake(mknode(PLACEHOLDER, {data: '', position: token.position}))
return Advance
}
}
function storage_or_not() {
if(is_storage(token)) {
if(stmt.flags & DECL_ALLOW_STORAGE) {
state.unshift(keyword())
return Advance
} else {
return unexpected('storage is not allowed here')
}
} else {
state.fake(mknode(PLACEHOLDER, {data: '', position: token.position}))
return Advance
}
}
function parameter_or_not() {
if(is_parameter(token)) {
if(!(stmt.flags & DECL_NO_INOUT)) {
state.unshift(keyword())
return Advance
} else {
return unexpected('parameter is not allowed here')
}
} else {
state.fake(mknode(PLACEHOLDER, {data: '', position: token.position}))
return Advance
}
}
function precision_or_not() {
if(is_precision(token)) {
state.unshift(keyword())
return Advance
} else {
state.fake(mknode(PLACEHOLDER, {data: '', position: token.position}))
return Advance
}
}
function struct_or_type() {
if(token.data === 'struct') {
if(!(stmt.flags & DECL_ALLOW_STRUCT)) {
return unexpected('cannot nest structs')
}
state.unshift(struct())
return Advance
}
if(token.type === 'keyword') {
state.unshift(keyword())
return Advance
}
var lookup = state.scope.find(token.data)
if(lookup) {
state.fake(Object.create(lookup))
tokens.shift()
return Advance
}
return unexpected('expected user defined type, struct or keyword, got '+token.data)
}
function maybe_name() {
if(token.data === ',' && !(stmt.flags & DECL_ALLOW_COMMA)) {
return state.shift()
}
if(token.data === '[') {
// oh lord.
state.unshift(quantifier())
return
}
if(token.data === ')') return state.shift()
if(token.data === ';') {
return stmt.stage + 3
}
if(token.type !== 'ident' && token.type !== 'builtin') {
return unexpected('expected identifier, got '+token.data)
}
stmt.collected_name = tokens.shift()
return Advance
}
function maybe_lparen() {
if(token.data === '(') {
tokens.unshift(stmt.collected_name)
delete stmt.collected_name
state.unshift(fn())
return stmt.stage + 2
}
return Advance
}
function is_decllist() {
tokens.unshift(stmt.collected_name)
delete stmt.collected_name
state.unshift(decllist())
return Advance
}
function done() {
return state.shift()
}
}
function parse_decllist() {
// grab ident
if(token.type === 'ident') {
var name = token.data
state.unshift(ident())
state.scope.define(name)
return
}
if(token.type === 'operator') {
if(token.data === ',') {
// multi-decl!
if(!(state[1].flags & DECL_ALLOW_COMMA)) {
return state.shift()
}
return tokens.shift()
} else if(token.data === '=') {
if(!(state[1].flags & DECL_ALLOW_ASSIGN)) return unexpected('`=` is not allowed here.')
tokens.shift()
state.unshift(expr(',', ';'))
return
} else if(token.data === '[') {
state.unshift(quantifier())
return
}
}
return state.shift()
}
function parse_keyword_or_ident() {
if(token.type === 'keyword') {
state[0].type = 'keyword'
state[0].mode = KEYWORD
return
}
if(token.type === 'ident') {
state[0].type = 'ident'
state[0].mode = IDENT
return
}
return unexpected('expected keyword or user-defined name, got '+token.data)
}
function parse_keyword() {
if(token.type !== 'keyword') {
return unexpected('expected keyword, got '+token.data)
}
return state.shift(), tokens.shift()
}
function parse_ident() {
if(token.type !== 'ident') {
return unexpected('expected user-defined name, got '+token.data)
}
state[0].data = token.data
return state.shift(), tokens.shift()
}
function parse_expr() {
var expecting = state[0].expecting
state[0].tokens = state[0].tokens || []
if(state[0].parenlevel === undefined) {
state[0].parenlevel = 0
state[0].bracelevel = 0
}
if(state[0].parenlevel < 1 && expecting.indexOf(token.data) > -1) {
return parseexpr(state[0].tokens)
}
if(token.data === '(') {
++state[0].parenlevel
} else if(token.data === ')') {
--state[0].parenlevel
}
switch(token.data) {
case '{': ++state[0].bracelevel; break
case '}': --state[0].bracelevel; break
case '(': ++state[0].parenlevel; break
case ')': --state[0].parenlevel; break
}
if(state[0].parenlevel < 0) return unexpected('unexpected `)`')
if(state[0].bracelevel < 0) return unexpected('unexpected `}`')
state[0].tokens.push(tokens.shift())
return
function parseexpr(tokens) {
return full_parse_expr(state, tokens), state.shift()
}
}
// node types ---------------
function n(type) {
// this is a function factory that suffices for most kinds of expressions and statements
return function() {
return mknode(type, token)
}
}
function adhoc() {
return mknode(token_map[token.type], token, node)
}
function decl(flags) {
var _ = mknode(DECL, token, node)
_.flags = flags
return _
}
function struct(allow_assign, allow_comma) {
var _ = mknode(STRUCT, token, node)
_.allow_assign = allow_assign === undefined ? true : allow_assign
_.allow_comma = allow_comma === undefined ? true : allow_comma
return _
}
function expr() {
var n = mknode(EXPR, token, node)
n.expecting = [].slice.call(arguments)
return n
}
function keyword(default_value) {
var t = token
if(default_value) {
t = {'type': '(implied)', data: '(default)', position: t.position}
}
return mknode(KEYWORD, t, node)
}
// utils ----------------------------
function unexpected(str) {
errored = true
stream.emit('error', new Error(
(str || 'unexpected '+state) +
' at line '+state[0].token.line
))
}
function assert(type, data) {
return 1,
assert_null_string_or_array(type, token.type) &&
assert_null_string_or_array(data, token.data)
}
function assert_null_string_or_array(x, y) {
switch(typeof x) {
case 'string': if(y !== x) {
unexpected('expected `'+x+'`, got '+y+'\n'+token.data);
} return !errored
case 'object': if(x && x.indexOf(y) === -1) {
unexpected('expected one of `'+x.join('`, `')+'`, got '+y);
} return !errored
}
return true
}
// stative ----------------------------
function stative() {
var steps = [].slice.call(arguments)
, step
, result
return function() {
var current = state[0]
current.stage || (current.stage = 0)
step = steps[current.stage]
if(!step) return unexpected('parser in undefined state!')
result = step()
if(result === Advance) return ++current.stage
if(result === undefined) return
current.stage = result
}
}
function advance(op, t) {
t = t || 'operator'
return function() {
if(!assert(t, op)) return
var last = tokens.shift()
, children = state[0].children
, last_node = children[children.length - 1]
if(last_node && last_node.token && last.preceding) {
last_node.token.succeeding = last_node.token.succeeding || []
last_node.token.succeeding = last_node.token.succeeding.concat(last.preceding)
}
return Advance
}
}
function advance_expr(until) {
return function() { return state.unshift(expr(until)), Advance }
}
function advance_ident(declare) {
return declare ? function() {
var name = token.data
return assert('ident') && (state.unshift(ident()), state.scope.define(name), Advance)
} : function() {
if(!assert('ident')) return
var s = Object.create(state.scope.find(token.data))
s.token = token
return (tokens.shift(), Advance)
}
}
function advance_stmtlist() {
return function() {
var n = stmtlist()
n.expecting = '}'
return state.unshift(n), Advance
}
}
function maybe_stmtlist(skip) {
return function() {
var current = state[0].stage
if(token.data !== '{') { return state.unshift(stmt()), current + skip }
return tokens.shift(), Advance
}
}
function popstmt() {
return function() { return state.shift(), state.shift() }
}
function setup_stative_parsers() {
// could also be
// struct { } decllist
parse_struct =
stative(
advance('struct', 'keyword')
, function() {
if(token.data === '{') {
state.fake(mknode(IDENT, {data:'', position: token.position, type:'ident'}))
return Advance
}
return advance_ident(true)()
}
, function() { state.scope.enter(); return Advance }
, advance('{')
, function() {
if(token.type === 'preprocessor') {
state.fake(adhoc())
tokens.shift()
return
}
if(token.data === '}') {
state.scope.exit()
tokens.shift()
return state.shift()
}
if(token.data === ';') { tokens.shift(); return }
state.unshift(decl(DECL_STRUCT))
}
)
parse_precision =
stative(
function() { return tokens.shift(), Advance }
, function() {
return assert(
'keyword', ['lowp', 'mediump', 'highp']
) && (state.unshift(keyword()), Advance)
}
, function() { return (state.unshift(keyword()), Advance) }
, function() { return state.shift() }
)
parse_quantifier =
stative(
advance('[')
, advance_expr(']')
, advance(']')
, function() { return state.shift() }
)
parse_forloop =
stative(
advance('for', 'keyword')
, advance('(')
, function() {
var lookup
if(token.type === 'ident') {
if(!(lookup = state.scope.find(token.data))) {
lookup = state.create_node()
}
if(lookup.parent.type === 'struct') {
return state.unshift(decl(DECL_STATEMENT)), Advance
}
} else if(token.type === 'builtin' || token.type === 'keyword') {
return state.unshift(decl(DECL_STATEMENT)), Advance
}
return advance_expr(';')()
}
, advance(';')
, advance_expr(';')
, advance(';')
, advance_expr(')')
, advance(')')
, maybe_stmtlist(3)
, advance_stmtlist()
, advance('}')
, popstmt()
)
parse_if =
stative(
advance('if', 'keyword')
, advance('(')
, advance_expr(')')
, advance(')')
, maybe_stmtlist(3)
, advance_stmtlist()
, advance('}')
, function() {
if(token.data === 'else') {
return tokens.shift(), state.unshift(stmt()), Advance
}
return popstmt()()
}
, popstmt()
)
parse_return =
stative(
advance('return', 'keyword')
, function() {
if(token.data === ';') return Advance
return state.unshift(expr(';')), Advance
}
, function() { tokens.shift(), popstmt()() }
)
parse_whileloop =
stative(
advance('while', 'keyword')
, advance('(')
, advance_expr(')')
, advance(')')
, maybe_stmtlist(3)
, advance_stmtlist()
, advance('}')
, popstmt()
)
parse_dowhileloop =
stative(
advance('do', 'keyword')
, maybe_stmtlist(3)
, advance_stmtlist()
, advance('}')
, advance('while', 'keyword')
, advance('(')
, advance_expr(')')
, advance(')')
, popstmt()
)
parse_function =
stative(
function() {
for(var i = 1, len = state.length; i < len; ++i) if(state[i].mode === FUNCTION) {
return unexpected('function definition is not allowed within another function')
}
return Advance
}
, function() {
if(!assert("ident")) return
var name = token.data
, lookup = state.scope.find(name)
state.unshift(ident())
state.scope.define(name)
state.scope.enter(lookup ? lookup.scope : null)
return Advance
}
, advance('(')
, function() { return state.unshift(fnargs()), Advance }
, advance(')')
, function() {
// forward decl
if(token.data === ';') {
return state.scope.exit(), state.shift(), state.shift()
}
return Advance
}
, advance('{')
, advance_stmtlist()
, advance('}')
, function() { state.scope.exit(); return Advance }
, function() { return state.shift(), state.shift(), state.shift() }
)
parse_function_args =
stative(
function() {
if(token.data === 'void') { state.fake(keyword()); tokens.shift(); return Advance }
if(token.data === ')') { state.shift(); return }
if(token.data === 'struct') {
state.unshift(struct(NO_ASSIGN_ALLOWED, NO_COMMA_ALLOWED))
return Advance
}
state.unshift(decl(DECL_FUNCTION))
return Advance
}
, function() {
if(token.data === ',') { tokens.shift(); return 0 }
if(token.data === ')') { state.shift(); return }
unexpected('expected one of `,` or `)`, got '+token.data)
}
)
}
}
function mknode(mode, sourcetoken) {
return {
mode: mode
, token: sourcetoken
, children: []
, type: stmt_type[mode]
, id: (Math.random() * 0xFFFFFFFF).toString(16)
}
}
function is_storage(token) {
return token.data === 'const' ||
token.data === 'attribute' ||
token.data === 'uniform' ||
token.data === 'varying'
}
function is_parameter(token) {
return token.data === 'in' ||
token.data === 'inout' ||
token.data === 'out'
}
function is_precision(token) {
return token.data === 'highp' ||
token.data === 'mediump' ||
token.data === 'lowp'
}
},{"./expr":119,"./scope":121,"through":122}],121:[function(require,module,exports){
module.exports = scope
function scope(state) {
if(this.constructor !== scope)
return new scope(state)
this.state = state
this.scopes = []
this.current = null
}
var cons = scope
, proto = cons.prototype
proto.enter = function(s) {
this.scopes.push(
this.current = this.state[0].scope = s || {}
)
}
proto.exit = function() {
this.scopes.pop()
this.current = this.scopes[this.scopes.length - 1]
}
proto.define = function(str) {
this.current[str] = this.state[0]
}
proto.find = function(name, fail) {
for(var i = this.scopes.length - 1; i > -1; --i) {
if(this.scopes[i].hasOwnProperty(name)) {
return this.scopes[i][name]
}
}
return null
}
},{}],122:[function(require,module,exports){
(function (process){
var Stream = require('stream')
// through
//
// a stream that does nothing but re-emit the input.
// useful for aggregating a series of changing but not ending streams into one stream)
exports = module.exports = through
through.through = through
//create a readable writable stream.
function through (write, end) {
write = write || function (data) { this.emit('data', data) }
end = end || function () { this.emit('end') }
var ended = false, destroyed = false
var stream = new Stream(), buffer = []
stream.buffer = buffer
stream.readable = stream.writable = true
stream.paused = false
stream.write = function (data) {
write.call(this, data)
return !stream.paused
}
function drain() {
while(buffer.length && !stream.paused) {
var data = buffer.shift()
if(null === data)
return stream.emit('end')
else
stream.emit('data', data)
}
}
stream.queue = function (data) {
buffer.push(data)
drain()
}
//this will be registered as the first 'end' listener
//must call destroy next tick, to make sure we're after any
//stream piped from here.
//this is only a problem if end is not emitted synchronously.
//a nicer way to do this is to make sure this is the last listener for 'end'
stream.on('end', function () {
stream.readable = false
if(!stream.writable)
process.nextTick(function () {
stream.destroy()
})
})
function _end () {
stream.writable = false
end.call(stream)
if(!stream.readable)
stream.destroy()
}
stream.end = function (data) {
if(ended) return
ended = true
if(arguments.length) stream.write(data)
_end() // will emit or queue
}
stream.destroy = function () {
if(destroyed) return
destroyed = true
ended = true
buffer.length = 0
stream.writable = stream.readable = false
stream.emit('close')
}
stream.pause = function () {
if(stream.paused) return
stream.paused = true
stream.emit('pause')
}
stream.resume = function () {
if(stream.paused) {
stream.paused = false
}
drain()
//may have become paused again,
//as drain emits 'data'.
if(!stream.paused)
stream.emit('drain')
}
return stream
}
}).call(this,require('_process'))
},{"_process":25,"stream":37}],123:[function(require,module,exports){
module.exports = tokenize
var through = require('through')
var literals = require('./lib/literals')
, operators = require('./lib/operators')
, builtins = require('./lib/builtins')
var NORMAL = 999 // <-- never emitted
, TOKEN = 9999 // <-- never emitted
, BLOCK_COMMENT = 0
, LINE_COMMENT = 1
, PREPROCESSOR = 2
, OPERATOR = 3
, INTEGER = 4
, FLOAT = 5
, IDENT = 6
, BUILTIN = 7
, KEYWORD = 8
, WHITESPACE = 9
, EOF = 10
, HEX = 11
var map = [
'block-comment'
, 'line-comment'
, 'preprocessor'
, 'operator'
, 'integer'
, 'float'
, 'ident'
, 'builtin'
, 'keyword'
, 'whitespace'
, 'eof'
, 'integer'
]
function tokenize() {
var stream = through(write, end)
var i = 0
, total = 0
, mode = NORMAL
, c
, last
, content = []
, token_idx = 0
, token_offs = 0
, line = 1
, start = 0
, isnum = false
, isoperator = false
, input = ''
, len
return stream
function token(data) {
if(data.length) {
stream.queue({
type: map[mode]
, data: data
, position: start
, line: line
})
}
}
function write(chunk) {
i = 0
input += chunk.toString()
len = input.length
while(c = input[i], i < len) switch(mode) {
case BLOCK_COMMENT: i = block_comment(); break
case LINE_COMMENT: i = line_comment(); break
case PREPROCESSOR: i = preprocessor(); break
case OPERATOR: i = operator(); break
case INTEGER: i = integer(); break
case HEX: i = hex(); break
case FLOAT: i = decimal(); break
case TOKEN: i = readtoken(); break
case WHITESPACE: i = whitespace(); break
case NORMAL: i = normal(); break
}
total += i
input = input.slice(i)
}
function end(chunk) {
if(content.length) {
token(content.join(''))
}
mode = EOF
token('(eof)')
stream.queue(null)
}
function normal() {
content = content.length ? [] : content
if(last === '/' && c === '*') {
start = total + i - 1
mode = BLOCK_COMMENT
last = c
return i + 1
}
if(last === '/' && c === '/') {
start = total + i - 1
mode = LINE_COMMENT
last = c
return i + 1
}
if(c === '#') {
mode = PREPROCESSOR
start = total + i
return i
}
if(/\s/.test(c)) {
mode = WHITESPACE
start = total + i
return i
}
isnum = /\d/.test(c)
isoperator = /[^\w_]/.test(c)
start = total + i
mode = isnum ? INTEGER : isoperator ? OPERATOR : TOKEN
return i
}
function whitespace() {
if(c === '\n') ++line
if(/[^\s]/g.test(c)) {
token(content.join(''))
mode = NORMAL
return i
}
content.push(c)
last = c
return i + 1
}
function preprocessor() {
if(c === '\n') ++line
if(c === '\n' && last !== '\\') {
token(content.join(''))
mode = NORMAL
return i
}
content.push(c)
last = c
return i + 1
}
function line_comment() {
return preprocessor()
}
function block_comment() {
if(c === '/' && last === '*') {
content.push(c)
token(content.join(''))
mode = NORMAL
return i + 1
}
if(c === '\n') ++line
content.push(c)
last = c
return i + 1
}
function operator() {
if(last === '.' && /\d/.test(c)) {
mode = FLOAT
return i
}
if(last === '/' && c === '*') {
mode = BLOCK_COMMENT
return i
}
if(last === '/' && c === '/') {
mode = LINE_COMMENT
return i
}
if(c === '.' && content.length) {
while(determine_operator(content));
mode = FLOAT
return i
}
if(c === ';' || c === ')' || c === '(') {
if(content.length) while(determine_operator(content));
token(c)
mode = NORMAL
return i + 1
}
var is_composite_operator = content.length === 2 && c !== '='
if(/[\w_\d\s]/.test(c) || is_composite_operator) {
while(determine_operator(content));
mode = NORMAL
return i
}
content.push(c)
last = c
return i + 1
}
function determine_operator(buf) {
var j = 0
, idx
do {
idx = operators.indexOf(buf.slice(0, buf.length + j).join(''))
if(idx === -1) {
j -= 1
continue
}
token(operators[idx])
start += operators[idx].length
content = content.slice(operators[idx].length)
return content.length
} while(1)
}
function hex() {
if(/[^a-fA-F0-9]/.test(c)) {
token(content.join(''))
mode = NORMAL
return i
}
content.push(c)
last = c
return i + 1
}
function integer() {
if(c === '.') {
content.push(c)
mode = FLOAT
last = c
return i + 1
}
if(/[eE]/.test(c)) {
content.push(c)
mode = FLOAT
last = c
return i + 1
}
if(c === 'x' && content.length === 1 && content[0] === '0') {
mode = HEX
content.push(c)
last = c
return i + 1
}
if(/[^\d]/.test(c)) {
token(content.join(''))
mode = NORMAL
return i
}
content.push(c)
last = c
return i + 1
}
function decimal() {
if(c === 'f') {
content.push(c)
last = c
i += 1
}
if(/[eE]/.test(c)) {
content.push(c)
last = c
return i + 1
}
if(/[^\d]/.test(c)) {
token(content.join(''))
mode = NORMAL
return i
}
content.push(c)
last = c
return i + 1
}
function readtoken() {
if(/[^\d\w_]/.test(c)) {
var contentstr = content.join('')
if(literals.indexOf(contentstr) > -1) {
mode = KEYWORD
} else if(builtins.indexOf(contentstr) > -1) {
mode = BUILTIN
} else {
mode = IDENT
}
token(content.join(''))
mode = NORMAL
return i
}
content.push(c)
last = c
return i + 1
}
}
},{"./lib/builtins":124,"./lib/literals":125,"./lib/operators":126,"through":127}],124:[function(require,module,exports){
module.exports = [
'gl_Position'
, 'gl_PointSize'
, 'gl_ClipVertex'
, 'gl_FragCoord'
, 'gl_FrontFacing'
, 'gl_FragColor'
, 'gl_FragData'
, 'gl_FragDepth'
, 'gl_Color'
, 'gl_SecondaryColor'
, 'gl_Normal'
, 'gl_Vertex'
, 'gl_MultiTexCoord0'
, 'gl_MultiTexCoord1'
, 'gl_MultiTexCoord2'
, 'gl_MultiTexCoord3'
, 'gl_MultiTexCoord4'
, 'gl_MultiTexCoord5'
, 'gl_MultiTexCoord6'
, 'gl_MultiTexCoord7'
, 'gl_FogCoord'
, 'gl_MaxLights'
, 'gl_MaxClipPlanes'
, 'gl_MaxTextureUnits'
, 'gl_MaxTextureCoords'
, 'gl_MaxVertexAttribs'
, 'gl_MaxVertexUniformComponents'
, 'gl_MaxVaryingFloats'
, 'gl_MaxVertexTextureImageUnits'
, 'gl_MaxCombinedTextureImageUnits'
, 'gl_MaxTextureImageUnits'
, 'gl_MaxFragmentUniformComponents'
, 'gl_MaxDrawBuffers'
, 'gl_ModelViewMatrix'
, 'gl_ProjectionMatrix'
, 'gl_ModelViewProjectionMatrix'
, 'gl_TextureMatrix'
, 'gl_NormalMatrix'
, 'gl_ModelViewMatrixInverse'
, 'gl_ProjectionMatrixInverse'
, 'gl_ModelViewProjectionMatrixInverse'
, 'gl_TextureMatrixInverse'
, 'gl_ModelViewMatrixTranspose'
, 'gl_ProjectionMatrixTranspose'
, 'gl_ModelViewProjectionMatrixTranspose'
, 'gl_TextureMatrixTranspose'
, 'gl_ModelViewMatrixInverseTranspose'
, 'gl_ProjectionMatrixInverseTranspose'
, 'gl_ModelViewProjectionMatrixInverseTranspose'
, 'gl_TextureMatrixInverseTranspose'
, 'gl_NormalScale'
, 'gl_DepthRangeParameters'
, 'gl_DepthRange'
, 'gl_ClipPlane'
, 'gl_PointParameters'
, 'gl_Point'
, 'gl_MaterialParameters'
, 'gl_FrontMaterial'
, 'gl_BackMaterial'
, 'gl_LightSourceParameters'
, 'gl_LightSource'
, 'gl_LightModelParameters'
, 'gl_LightModel'
, 'gl_LightModelProducts'
, 'gl_FrontLightModelProduct'
, 'gl_BackLightModelProduct'
, 'gl_LightProducts'
, 'gl_FrontLightProduct'
, 'gl_BackLightProduct'
, 'gl_FogParameters'
, 'gl_Fog'
, 'gl_TextureEnvColor'
, 'gl_EyePlaneS'
, 'gl_EyePlaneT'
, 'gl_EyePlaneR'
, 'gl_EyePlaneQ'
, 'gl_ObjectPlaneS'
, 'gl_ObjectPlaneT'
, 'gl_ObjectPlaneR'
, 'gl_ObjectPlaneQ'
, 'gl_FrontColor'
, 'gl_BackColor'
, 'gl_FrontSecondaryColor'
, 'gl_BackSecondaryColor'
, 'gl_TexCoord'
, 'gl_FogFragCoord'
, 'gl_Color'
, 'gl_SecondaryColor'
, 'gl_TexCoord'
, 'gl_FogFragCoord'
, 'gl_PointCoord'
, 'radians'
, 'degrees'
, 'sin'
, 'cos'
, 'tan'
, 'asin'
, 'acos'
, 'atan'
, 'pow'
, 'exp'
, 'log'
, 'exp2'
, 'log2'
, 'sqrt'
, 'inversesqrt'
, 'abs'
, 'sign'
, 'floor'
, 'ceil'
, 'fract'
, 'mod'
, 'min'
, 'max'
, 'clamp'
, 'mix'
, 'step'
, 'smoothstep'
, 'length'
, 'distance'
, 'dot'
, 'cross'
, 'normalize'
, 'faceforward'
, 'reflect'
, 'refract'
, 'matrixCompMult'
, 'lessThan'
, 'lessThanEqual'
, 'greaterThan'
, 'greaterThanEqual'
, 'equal'
, 'notEqual'
, 'any'
, 'all'
, 'not'
, 'texture2D'
, 'texture2DProj'
, 'texture2DLod'
, 'texture2DProjLod'
, 'textureCube'
, 'textureCubeLod'
]
},{}],125:[function(require,module,exports){
module.exports = [
// current
'precision'
, 'highp'
, 'mediump'
, 'lowp'
, 'attribute'
, 'const'
, 'uniform'
, 'varying'
, 'break'
, 'continue'
, 'do'
, 'for'
, 'while'
, 'if'
, 'else'
, 'in'
, 'out'
, 'inout'
, 'float'
, 'int'
, 'void'
, 'bool'
, 'true'
, 'false'
, 'discard'
, 'return'
, 'mat2'
, 'mat3'
, 'mat4'
, 'vec2'
, 'vec3'
, 'vec4'
, 'ivec2'
, 'ivec3'
, 'ivec4'
, 'bvec2'
, 'bvec3'
, 'bvec4'
, 'sampler1D'
, 'sampler2D'
, 'sampler3D'
, 'samplerCube'
, 'sampler1DShadow'
, 'sampler2DShadow'
, 'struct'
// future
, 'asm'
, 'class'
, 'union'
, 'enum'
, 'typedef'
, 'template'
, 'this'
, 'packed'
, 'goto'
, 'switch'
, 'default'
, 'inline'
, 'noinline'
, 'volatile'
, 'public'
, 'static'
, 'extern'
, 'external'
, 'interface'
, 'long'
, 'short'
, 'double'
, 'half'
, 'fixed'
, 'unsigned'
, 'input'
, 'output'
, 'hvec2'
, 'hvec3'
, 'hvec4'
, 'dvec2'
, 'dvec3'
, 'dvec4'
, 'fvec2'
, 'fvec3'
, 'fvec4'
, 'sampler2DRect'
, 'sampler3DRect'
, 'sampler2DRectShadow'
, 'sizeof'
, 'cast'
, 'namespace'
, 'using'
]
},{}],126:[function(require,module,exports){
module.exports = [
'<<='
, '>>='
, '++'
, '--'
, '<<'
, '>>'
, '<='
, '>='
, '=='
, '!='
, '&&'
, '||'
, '+='
, '-='
, '*='
, '/='
, '%='
, '&='
, '^='
, '|='
, '('
, ')'
, '['
, ']'
, '.'
, '!'
, '~'
, '*'
, '/'
, '%'
, '+'
, '-'
, '<'
, '>'
, '&'
, '^'
, '|'
, '?'
, ':'
, '='
, ','
, ';'
, '{'
, '}'
]
},{}],127:[function(require,module,exports){
(function (process){
var Stream = require('stream')
// through
//
// a stream that does nothing but re-emit the input.
// useful for aggregating a series of changing but not ending streams into one stream)
exports = module.exports = through
through.through = through
//create a readable writable stream.
function through (write, end, opts) {
write = write || function (data) { this.queue(data) }
end = end || function () { this.queue(null) }
var ended = false, destroyed = false, buffer = [], _ended = false
var stream = new Stream()
stream.readable = stream.writable = true
stream.paused = false
// stream.autoPause = !(opts && opts.autoPause === false)
stream.autoDestroy = !(opts && opts.autoDestroy === false)
stream.write = function (data) {
write.call(this, data)
return !stream.paused
}
function drain() {
while(buffer.length && !stream.paused) {
var data = buffer.shift()
if(null === data)
return stream.emit('end')
else
stream.emit('data', data)
}
}
stream.queue = stream.push = function (data) {
// console.error(ended)
if(_ended) return stream
if(data == null) _ended = true
buffer.push(data)
drain()
return stream
}
//this will be registered as the first 'end' listener
//must call destroy next tick, to make sure we're after any
//stream piped from here.
//this is only a problem if end is not emitted synchronously.
//a nicer way to do this is to make sure this is the last listener for 'end'
stream.on('end', function () {
stream.readable = false
if(!stream.writable && stream.autoDestroy)
process.nextTick(function () {
stream.destroy()
})
})
function _end () {
stream.writable = false
end.call(stream)
if(!stream.readable && stream.autoDestroy)
stream.destroy()
}
stream.end = function (data) {
if(ended) return
ended = true
if(arguments.length) stream.write(data)
_end() // will emit or queue
return stream
}
stream.destroy = function () {
if(destroyed) return
destroyed = true
ended = true
buffer.length = 0
stream.writable = stream.readable = false
stream.emit('close')
return stream
}
stream.pause = function () {
if(stream.paused) return
stream.paused = true
return stream
}
stream.resume = function () {
if(stream.paused) {
stream.paused = false
stream.emit('resume')
}
drain()
//may have become paused again,
//as drain emits 'data'.
if(!stream.paused)
stream.emit('drain')
return stream
}
return stream
}
}).call(this,require('_process'))
},{"_process":25,"stream":37}],128:[function(require,module,exports){
"use strict"
function unique_pred(list, compare) {
var ptr = 1
, len = list.length
, a=list[0], b=list[0]
for(var i=1; i<len; ++i) {
b = a
a = list[i]
if(compare(a, b)) {
if(i === ptr) {
ptr++
continue
}
list[ptr++] = a
}
}
list.length = ptr
return list
}
function unique_eq(list) {
var ptr = 1
, len = list.length
, a=list[0], b = list[0]
for(var i=1; i<len; ++i, b=a) {
b = a
a = list[i]
if(a !== b) {
if(i === ptr) {
ptr++
continue
}
list[ptr++] = a
}
}
list.length = ptr
return list
}
function unique(list, compare, sorted) {
if(list.length === 0) {
return []
}
if(compare) {
if(!sorted) {
list.sort(compare)
}
return unique_pred(list, compare)
}
if(!sorted) {
list.sort()
}
return unique_eq(list)
}
module.exports = unique
},{}],129:[function(require,module,exports){
var CommandsPlugin, ItemPile, shellwords,
slice = [].slice,
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
shellwords = require('shellwords');
ItemPile = require('itempile');
module.exports = function(game, opts) {
return new CommandsPlugin(game, opts);
};
module.exports.pluginInfo = {
loadAfter: ['voxel-console']
};
CommandsPlugin = (function() {
function CommandsPlugin(game1, opts) {
var ref, ref1;
this.game = game1;
this.console = (ref = this.game.plugins) != null ? ref.get('voxel-console') : void 0;
if (this.console == null) {
throw new Error('voxel-commands requires voxel-console');
}
this.registry = (ref1 = this.game.plugins) != null ? ref1.get('voxel-registry') : void 0;
if (this.registry == null) {
throw new Error('voxel-commands requires voxel-registry');
}
this.usages = {
pos: "x y z",
home: "",
item: "name [count [tags]]",
clear: "",
block: "name [data]",
plugins: "",
enable: "plugin",
disable: "plugin"
};
this.handlers = {
undefined: function() {
var args, command;
command = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
return this.console.log("Invalid command " + command + " " + (args.join(' ')));
},
help: function() {
var name, ref2, results, usage;
this.console.log("Available commands:");
results = [];
for (name in this.usages) {
usage = (ref2 = this.usages[name]) != null ? ref2 : '';
results.push(this.console.log("." + name + " " + usage));
}
return results;
},
plugins: function() {
var list, ref2;
list = (ref2 = this.game.plugins) != null ? ref2.list() : void 0;
return this.console.log(("Enabled plugins (" + list.length + "): ") + list.join(' '));
},
enable: function(name) {
var ref2;
if ((ref2 = this.game.plugins) != null ? ref2.enable(name) : void 0) {
return this.console.log("Enabled plugin: " + name);
} else {
return this.console.log("Failed to enable plugin: " + name);
}
},
disable: function(name) {
if (this.game.plugins.disable(name)) {
return this.console.log("Disabled plugin: " + name);
} else {
return this.console.log("Failed to disable plugin: " + name);
}
},
pos: function(x, y, z) {
var player, ref2;
player = (ref2 = this.game.plugins) != null ? ref2.get('voxel-player') : void 0;
if (player) {
player.moveTo(x, y, z);
return this.console.log([player.position.x, player.position.y, player.position.z]);
}
},
home: function() {
var ref2, ref3;
return (ref2 = this.game.plugins) != null ? (ref3 = ref2.get('voxel-player')) != null ? ref3.home() : void 0 : void 0;
},
item: function(name, count, tagsStr) {
var carry, e, pile, props, ref2, tags;
props = this.registry.getItemProps(name);
if (props == null) {
this.console.log("No such item: " + name);
return;
}
if (tagsStr != null) {
try {
tags = JSON.parse(tagsStr);
} catch (_error) {
e = _error;
this.console.log("Invalid JSON " + tagsStr + ": " + e);
return;
}
} else {
tags = void 0;
}
if (count == null) {
count = 1;
}
count = parseInt(count, 10);
if (isNaN(count)) {
count = 1;
}
pile = new ItemPile(name, count, tags);
carry = (ref2 = this.game.plugins) != null ? ref2.get('voxel-carry') : void 0;
if (carry) {
carry.inventory.give(pile);
return this.console.log("Gave " + name + " x " + count + " " + (tags != null ? JSON.stringify(tags) : ''));
}
},
clear: function() {
var carry, ref2;
carry = (ref2 = this.game.plugins) != null ? ref2.get('voxel-carry') : void 0;
if (carry) {
carry.inventory.clear();
return this.console.log("Cleared inventory");
}
},
block: function(name, data) {
var blockdata, dataInfo, hit, index, oldData, oldIndex, oldName, reachDistance, ref2, ref3, x, y, z;
if (name != null) {
index = this.registry.getBlockIndex(name);
if (index == null) {
this.console.log("No such block: " + name);
return;
}
}
reachDistance = 8;
hit = this.game.raycastVoxels(this.game.cameraPosition(), this.game.cameraVector(), reachDistance);
if (!hit) {
this.console.log("No block targetted");
return;
}
ref2 = hit.voxel, x = ref2[0], y = ref2[1], z = ref2[2];
oldIndex = hit.value;
oldName = this.registry.getBlockName(oldIndex);
if (name != null) {
this.game.setBlock(hit.voxel, index);
}
blockdata = (ref3 = this.game.plugins) != null ? ref3.get('voxel-blockdata') : void 0;
if (blockdata != null) {
oldData = blockdata.get(x, y, z);
if (data != null) {
blockdata.set(x, y, z, data);
}
}
dataInfo = "";
if (oldData != null) {
dataInfo = (JSON.stringify(oldData)) + " -> ";
}
if (data == null) {
data = oldData;
}
if (oldData != null) {
dataInfo += JSON.stringify(data);
}
if (name == null) {
name = oldName;
}
if (index == null) {
index = oldIndex;
}
return this.console.log("Set (" + x + ", " + y + ", " + z + ") " + oldName + "/" + oldIndex + " -> " + name + "/" + index + " " + dataInfo);
}
};
this.handlers.p = this.handlers.position = this.handlers.tp = this.handlers.pos;
this.handlers.i = this.handlers.give = this.handlers.item;
this.handlers.b = this.handlers.setblock = this.handlers.set = this.handlers.block;
this.enable();
}
CommandsPlugin.prototype.process = function(input) {
var args, command, connection, handler, ref, ref1, words;
if (input.indexOf('.') !== 0) {
this.console.log(input);
connection = (ref = this.game.plugins) != null ? (ref1 = ref.get('voxel-client')) != null ? ref1.connection : void 0 : void 0;
if (connection != null) {
connection.emit('chat', {
message: input
});
} else {
this.console.log('Not connected to server. Type .help for commands');
}
return;
}
input = input.substring(1);
words = shellwords.split(input);
command = words[0], args = 2 <= words.length ? slice.call(words, 1) : [];
handler = this.handlers[command];
if (handler == null) {
handler = this.handlers.undefined;
args.unshift(command);
}
return handler.apply(this, args);
};
CommandsPlugin.prototype.enable = function() {
var ref, ref1, ref2;
if ((ref = this.console.widget) != null) {
ref.on('input', this.onInput = (function(_this) {
return function(input) {
return _this.process(input);
};
})(this));
}
return (ref1 = this.game.plugins) != null ? (ref2 = ref1.get('voxel-client')) != null ? ref2.connection.on('chat', this.onChat = (function(_this) {
return function(input) {
var ref3;
return _this.console.log((ref3 = input.message) != null ? ref3 : input);
};
})(this)) : void 0 : void 0;
};
CommandsPlugin.prototype.disable = function() {
var ref, ref1;
this.console.widget.removeListener('input', this.onInput);
return (ref = this.game.plugins) != null ? (ref1 = ref.get('voxel-client')) != null ? ref1.connection.removeListener('chat', this.onChat) : void 0 : void 0;
};
CommandsPlugin.prototype.registerCommand = function(name, handler, usage, help) {
if (indexOf.call(this.handlers, name) >= 0) {
throw new Error("voxel-commands duplicate command registration: " + name + " for " + handler);
}
this.handlers[name] = handler;
return this.usages[name] = usage + " -- " + help;
};
CommandsPlugin.prototype.unregisterCommand = function(name, handler) {
if (this.handlers[name] !== handler) {
throw new Error("voxel-commands attempted to unregister mismatched command: " + name + " was " + this.handlers[name] + " not " + handler);
}
delete this.handlers[name];
return delete this.usages[name];
};
return CommandsPlugin;
})();
},{"itempile":130,"shellwords":135}],130:[function(require,module,exports){
"use strict";
var _slicedToArray = function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } };
var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
var deepEqual = require("deep-equal");
var cloneObject = require("clone");
var ItemPile = (function () {
function ItemPile(item) {
var count = arguments[1] === undefined ? 1 : arguments[1];
var tags = arguments[2] === undefined ? {} : arguments[2];
_classCallCheck(this, ItemPile);
this.item = typeof item === "string" ? ItemPile.itemFromString(item) : item;
this.count = count;
this.tags = tags;
}
_prototypeProperties(ItemPile, {
maxPileSize: {
// maximum size items should pile
get: function () {
return 64;
},
configurable: true
},
itemFromString: {
// convert item<->string; change these to use non-string items
value: function itemFromString(s) {
if (s instanceof ItemPile) {
return s;
}return !s ? "" : s;
},
writable: true,
configurable: true
},
itemToString: {
value: function itemToString(item) {
return "" + item;
},
writable: true,
configurable: true
},
fromString: {
value: function fromString(s) {
var a = s.match(/^([^:]+):([^ ]+) ?(.*)/); // assumptions: positive integral count, item name no spaces
if (!a) {
return undefined;
}
var _a = _slicedToArray(a, 4);
var _ = _a[0];
var countStr = _a[1];
var itemStr = _a[2];
var tagsStr = _a[3];
var count = undefined;
if (countStr === "Infinity") {
count = Infinity;
} else {
count = parseInt(countStr, 10);
}
var item = ItemPile.itemFromString(itemStr);
var tags = undefined;
if (tagsStr && tagsStr.length) {
tags = JSON.parse(tagsStr);
} else {
tags = {};
}
return new ItemPile(item, count, tags);
},
writable: true,
configurable: true
},
fromArray: {
value: function fromArray(_ref) {
var _ref2 = _slicedToArray(_ref, 3);
var item = _ref2[0];
var count = _ref2[1];
var tags = _ref2[2];
return new ItemPile(item, count, tags);
},
writable: true,
configurable: true
},
fromArrayIfArray: {
value: function fromArrayIfArray(a) {
if (Array.isArray(a)) {
return ItemPile.fromArray(a);
} else {
return a;
}
},
writable: true,
configurable: true
}
}, {
clone: {
value: function clone() {
return new ItemPile(this.item, this.count, cloneObject(this.tags, false));
},
writable: true,
configurable: true
},
hasTags: {
value: function hasTags() {
return Object.keys(this.tags).length !== 0; // not "{}"
},
writable: true,
configurable: true
},
matchesType: {
value: function matchesType(itemPile) {
return this.item === itemPile.item;
},
writable: true,
configurable: true
},
matchesTypeAndCount: {
value: function matchesTypeAndCount(itemPile) {
return this.item === itemPile.item && this.count === itemPile.count;
},
writable: true,
configurable: true
},
matchesTypeAndTags: {
value: function matchesTypeAndTags(itemPile) {
return this.item === itemPile.item && deepEqual(this.tags, itemPile.tags, { strict: true });
},
writable: true,
configurable: true
},
matchesAll: {
value: function matchesAll(itemPile) {
return this.matchesTypeAndCount(itemPile) && deepEqual(this.tags, itemPile.tags, { strict: true });
},
writable: true,
configurable: true
},
canPileWith: {
// can this pile be merged with another?
value: function canPileWith(itemPile) {
if (itemPile.item !== this.item) {
return false;
}if (itemPile.count === 0 || this.count === 0) {
return true;
} // (special case: can always merge with 0-size pile of same item, regardless of tags - for placeholder slots)
if (itemPile.hasTags() || this.hasTags()) {
return false;
} // any tag data makes unpileable
return true;
},
writable: true,
configurable: true
},
mergePile: {
// combine two piles if possible, altering both this and argument pile
// returns count of items that didn't fit
value: function mergePile(itemPile) {
if (!this.canPileWith(itemPile)) {
return false;
}itemPile.count = this.increase(itemPile.count);
return itemPile.count;
},
writable: true,
configurable: true
},
increase: {
// increase count by argument, returning number of items that didn't fit
value: function increase(n) {
var _tryAdding = this.tryAdding(n);
var _tryAdding2 = _slicedToArray(_tryAdding, 2);
var newCount = _tryAdding2[0];
var excessCount = _tryAdding2[1];
this.count = newCount;
return excessCount;
},
writable: true,
configurable: true
},
decrease: {
// decrease count by argument, returning number of items removed
value: function decrease(n) {
var _trySubtracting = this.trySubtracting(n);
var _trySubtracting2 = _slicedToArray(_trySubtracting, 2);
var removedCount = _trySubtracting2[0];
var remainingCount = _trySubtracting2[1];
this.count = remainingCount;
return removedCount;
},
writable: true,
configurable: true
},
tryAdding: {
// try combining count of items up to max pile size, returns [newCount, excessCount]
value: function tryAdding(n) {
// special case: infinite incoming count sets pile to infinite, even though >maxPileSize
// TODO: option to disable infinite piles? might want to add only up to 64 etc. (ref GH-2)
if (n === Infinity) {
return [Infinity, 0];
}var sum = this.count + n;
if (sum > ItemPile.maxPileSize && this.count !== Infinity) {
// (special case: infinite destination piles never overflow)
return [ItemPile.maxPileSize, sum - ItemPile.maxPileSize]; // overflowing pile
} else {
return [sum, 0]; // added everything they wanted
}
},
writable: true,
configurable: true
},
trySubtracting: {
// try removing a finite count of items, returns [removedCount, remainingCount]
value: function trySubtracting(n) {
var difference = this.count - n;
if (difference < 0) {
return [this.count, n - this.count]; // didn't have enough
} else {
return [n, this.count - n]; // had enough, some remain
}
},
writable: true,
configurable: true
},
splitPile: {
// remove count of argument items, returning new pile of those items which were split off
value: function splitPile(n) {
if (n === 0) {
return false;
}if (n < 0) {
// negative count = all but n
n = this.count + n;
} else if (n < 1) {
// fraction = fraction
n = Math.ceil(this.count * n);
}
if (n > this.count) {
return false;
}if (n !== Infinity) this.count -= n; // (subtract, but avoid Infinity - Infinity = NaN)
return new ItemPile(this.item, n, cloneObject(this.tags, false));
},
writable: true,
configurable: true
},
toString: {
value: function toString() {
if (this.hasTags()) {
return "" + this.count + ":" + this.item + " " + JSON.stringify(this.tags);
} else {
return "" + this.count + ":" + this.item;
}
},
writable: true,
configurable: true
}
});
return ItemPile;
})();
module.exports = ItemPile;
},{"clone":131,"deep-equal":132}],131:[function(require,module,exports){
arguments[4][64][0].apply(exports,arguments)
},{"buffer":17,"dup":64}],132:[function(require,module,exports){
arguments[4][65][0].apply(exports,arguments)
},{"./lib/is_arguments.js":133,"./lib/keys.js":134,"dup":65}],133:[function(require,module,exports){
arguments[4][66][0].apply(exports,arguments)
},{"dup":66}],134:[function(require,module,exports){
arguments[4][67][0].apply(exports,arguments)
},{"dup":67}],135:[function(require,module,exports){
// Generated by CoffeeScript 1.3.3
(function() {
var scan;
scan = function(string, pattern, callback) {
var match, result;
result = "";
while (string.length > 0) {
match = string.match(pattern);
if (match) {
result += string.slice(0, match.index);
result += callback(match);
string = string.slice(match.index + match[0].length);
} else {
result += string;
string = "";
}
}
return result;
};
exports.split = function(line) {
var field, words;
if (line == null) {
line = "";
}
words = [];
field = "";
scan(line, /\s*(?:([^\s\\\'\"]+)|'((?:[^\'\\]|\\.)*)'|"((?:[^\"\\]|\\.)*)"|(\\.?)|(\S))(\s|$)?/, function(match) {
var dq, escape, garbage, raw, seperator, sq, word;
raw = match[0], word = match[1], sq = match[2], dq = match[3], escape = match[4], garbage = match[5], seperator = match[6];
if (garbage != null) {
throw new Error("Unmatched quote");
}
field += word || (sq || dq || escape).replace(/\\(?=.)/, "");
if (seperator != null) {
words.push(field);
return field = "";
}
});
if (field) {
words.push(field);
}
return words;
};
exports.escape = function(str) {
if (str == null) {
str = "";
}
if (str == null) {
return "''";
}
return str.replace(/([^A-Za-z0-9_\-.,:\/@\n])/g, "\\$1").replace(/\n/g, "'\n'");
};
}).call(this);
},{}],136:[function(require,module,exports){
var Console, ConsoleWidget, EventEmitter, Modal, inherits,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
inherits = require('inherits');
EventEmitter = require('events').EventEmitter;
Modal = require('voxel-modal');
ConsoleWidget = require('console-widget');
module.exports = function(game, opts) {
return new Console(game, opts);
};
module.exports.pluginInfo = {
loadAfter: ['voxel-keys']
};
Console = (function(superClass) {
extend(Console, superClass);
function Console(game1, opts1) {
var base, ref, widgetOpts;
this.game = game1;
this.opts = opts1;
if (!this.game.isClient) {
return;
}
if ((base = this.opts).includeTextBindings == null) {
base.includeTextBindings = {
'console': void 0,
console2: '/',
console3: '.'
};
}
widgetOpts = this.opts;
widgetOpts.closeKeys = [];
this.widget = ConsoleWidget(widgetOpts);
this.keys = (function() {
if ((ref = game.plugins.get('voxel-keys')) != null) {
return ref;
} else {
throw new Error('voxel-console requires voxel-keys plugin');
}
})();
this.bindKeys();
Console.__super__.constructor.call(this, game, {
element: this.widget.containerNode
});
}
inherits(Console, EventEmitter);
Console.prototype.bindKeys = function() {
return ['console', 'console2', 'console3'].forEach((function(_this) {
return function(binding) {
return _this.keys.down.on(binding, function() {
var initialText;
initialText = _this.opts.includeTextBindings[binding];
return _this.open(initialText);
});
};
})(this));
};
Console.prototype.open = function(initialText) {
if (initialText == null) {
initialText = void 0;
}
Console.__super__.open.call(this);
this.emit('open');
this.on('open', (function(_this) {
return function() {
return console.log('opened');
};
})(this));
return this.widget.open(initialText);
};
Console.prototype.close = function() {
Console.__super__.close.call(this);
console.log("closed");
this.emit('close');
return this.on('close', (function(_this) {
return function() {
return console.log('closed');
};
})(this));
};
Console.prototype.log = function(text) {
return this.widget.log(text);
};
Console.prototype.logNode = function(node) {
return this.widget.logNode(node);
};
return Console;
})(Modal);
},{"console-widget":137,"events":21,"inherits":139,"voxel-modal":140}],137:[function(require,module,exports){
var ConsoleWidget, EventEmitter, MAX_LINES, vkey,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
EventEmitter = (require('events')).EventEmitter;
vkey = require('vkey');
MAX_LINES = 999;
ConsoleWidget = (function(_super) {
__extends(ConsoleWidget, _super);
function ConsoleWidget(opts) {
var _base, _base1, _base2, _base3, _base4, _base5, _base6;
this.opts = opts;
if (this.opts == null) {
this.opts = {};
}
if ((_base = this.opts).widthPx == null) {
_base.widthPx = 500;
}
if ((_base1 = this.opts).rows == null) {
_base1.rows = 10;
}
if ((_base2 = this.opts).lineHeightPx == null) {
_base2.lineHeightPx = 20;
}
if ((_base3 = this.opts).font == null) {
_base3.font = '12pt Menlo, Courier, \'Courier New\', monospace';
}
if ((_base4 = this.opts).backgroundImage == null) {
_base4.backgroundImage = 'linear-gradient(rgba(0,0,0,0.6) 0%, rgba(0,0,0,0.6) 100%)';
}
if ((_base5 = this.opts).closeKeys == null) {
_base5.closeKeys = ['<escape>'];
}
if ((_base6 = this.opts).hideTimeout == null) {
_base6.hideTimeout = 5000;
}
this.history = [];
this.historyCursor = this.history.length;
this.hideTimer = void 0;
this.createNodes();
}
ConsoleWidget.prototype.show = function() {
this.containerNode.style.visibility = '';
this.containerNode.style.transition = '';
this.containerNode.style.opacity = 1.0;
if (this.hideTimer != null) {
return clearTimeout(this.hideTimer);
}
};
ConsoleWidget.prototype.hide = function() {
return this.containerNode.style.visibility = 'hidden';
};
ConsoleWidget.prototype.open = function(text) {
if (text == null) {
text = void 0;
}
this.show();
if (text != null) {
this.setInput(text);
}
this.registerEvents();
return this.focusInput();
};
ConsoleWidget.prototype.close = function() {
this.unregisterEvents();
return this.hide();
};
ConsoleWidget.prototype.isOpen = function() {
return this.isShown();
};
ConsoleWidget.prototype.isShown = function() {
return this.containerNode.style.visibility !== 'hidden' && this.containerNode.style.opacity | 0 !== 0;
};
ConsoleWidget.prototype.log = function(text) {
return this.logNode(document.createTextNode(text));
};
ConsoleWidget.prototype.logNode = function(node) {
if (!this.isShown()) {
this.show();
this.hideTimer = setTimeout(this.fadeOut.bind(this), this.opts.hideTimeout);
}
this.outputNode.appendChild(node);
this.outputNode.appendChild(document.createElement('br'));
return this.scrollOutput();
};
ConsoleWidget.prototype.fadeOut = function() {
this.containerNode.style.transition = 'opacity linear 1s';
return this.containerNode.style.opacity = 0.0;
};
ConsoleWidget.prototype.focusInput = function() {
return this.inputNode.focus();
};
ConsoleWidget.prototype.setInput = function(text) {
this.inputNode.value = text;
return this.inputNode.setSelectionRange(text.length, text.length);
};
ConsoleWidget.prototype.scrollOutput = function() {
var _base;
return typeof (_base = this.outputNode).scrollByLines === "function" ? _base.scrollByLines(MAX_LINES + 1) : void 0;
};
ConsoleWidget.prototype.createNodes = function() {
this.containerNode = document.createElement('div');
this.containerNode.setAttribute('style', "width: " + this.opts.widthPx + "px; height: " + (this.opts.lineHeightPx * this.opts.rows) + "px; border: 1px solid white; color: white; visibility: hidden; bottom: 0px; position: absolute; font: " + this.opts.font + "; background-image: " + this.opts.backgroundImage + ";");
this.outputNode = document.createElement('div');
this.outputNode.setAttribute('style', "overflow-y: scroll; width: 100%; height: " + (this.opts.lineHeightPx * (this.opts.rows - 1)) + "px;");
this.inputNode = document.createElement('input');
this.inputNode.setAttribute('style', "width: 100%; height: " + this.opts.lineHeightPx + "px; padding: 0px; border: 1px dashed white; background-color: transparent; color: white; font: " + this.opts.font + ";");
this.containerNode.appendChild(this.outputNode);
this.containerNode.appendChild(this.inputNode);
return document.body.appendChild(this.containerNode);
};
ConsoleWidget.prototype.registerEvents = function() {
return document.body.addEventListener('keydown', this.onKeydown = (function(_this) {
return function(ev) {
var key, preventDefault, _base, _base1, _base2, _base3, _base4, _base5, _base6, _base7;
key = vkey[ev.keyCode];
preventDefault = true;
if (key === '<enter>') {
if (_this.inputNode.value.length === 0) {
return;
}
_this.history.push(_this.inputNode.value);
_this.historyCursor = _this.history.length - 1;
_this.emit('input', _this.inputNode.value);
_this.inputNode.value = '';
} else if (key === '<up>') {
if (ev.shiftKey) {
if (typeof (_base = _this.outputNode).scrollByLines === "function") {
_base.scrollByLines(-1);
}
} else {
if (_this.history[_this.historyCursor] != null) {
_this.inputNode.value = _this.history[_this.historyCursor];
}
_this.historyCursor -= 1;
if (_this.historyCursor < 0) {
_this.historyCursor = 0;
}
}
} else if (key === '<down>') {
if (ev.shiftKey) {
if (typeof (_base1 = _this.outputNode).scrollByLines === "function") {
_base1.scrollByLines(1);
}
} else {
if (_this.history[_this.historyCursor] != null) {
_this.inputNode.value = _this.history[_this.historyCursor];
}
_this.historyCursor += 1;
if (_this.historyCursor > _this.history.length - 1) {
_this.historyCursor = _this.history.length - 1;
}
}
} else if (key === '<page-up>') {
if (ev.shiftKey) {
if (typeof (_base2 = _this.outputNode).scrollByLines === "function") {
_base2.scrollByLines(-1);
}
} else if (ev.ctrlKey || ev.metaKey) {
if (typeof (_base3 = _this.outputNode).scrollByLines === "function") {
_base3.scrollByLines(-MAX_LINES);
}
} else {
if (typeof (_base4 = _this.outputNode).scrollByPages === "function") {
_base4.scrollByPages(-1);
}
}
} else if (key === '<page-down>') {
if (ev.shiftKey) {
if (typeof (_base5 = _this.outputNode).scrollByLines === "function") {
_base5.scrollByLines(1);
}
} else if (ev.ctrlKey || ev.metaKey) {
if (typeof (_base6 = _this.outputNode).scrollByLines === "function") {
_base6.scrollByLines(MAX_LINES);
}
} else {
if (typeof (_base7 = _this.outputNode).scrollByPages === "function") {
_base7.scrollByPages(1);
}
}
} else if (_this.opts.closeKeys.indexOf(key) !== -1) {
_this.close();
} else {
preventDefault = false;
}
if (preventDefault) {
return ev.preventDefault();
}
};
})(this));
};
ConsoleWidget.prototype.unregisterEvents = function() {
return document.body.removeEventListener('keydown', this.onKeydown);
};
return ConsoleWidget;
})(EventEmitter);
module.exports = function(opts) {
return new ConsoleWidget(opts);
};
},{"events":21,"vkey":138}],138:[function(require,module,exports){
arguments[4][55][0].apply(exports,arguments)
},{"dup":55}],139:[function(require,module,exports){
arguments[4][22][0].apply(exports,arguments)
},{"dup":22}],140:[function(require,module,exports){
arguments[4][59][0].apply(exports,arguments)
},{"dup":59,"ever":141}],141:[function(require,module,exports){
arguments[4][48][0].apply(exports,arguments)
},{"./init.json":142,"./types.json":143,"dup":48,"events":21}],142:[function(require,module,exports){
arguments[4][49][0].apply(exports,arguments)
},{"dup":49}],143:[function(require,module,exports){
arguments[4][50][0].apply(exports,arguments)
},{"dup":50}],144:[function(require,module,exports){
"use strict";
var createBuffer = require("gl-buffer");
var createVAO = require("gl-vao");
var glslify = require("glslify");
var mat4 = require("gl-mat4");
module.exports = function(game, opts) {
return new DecalsPlugin(game, opts);
};
module.exports.pluginInfo = {
loadAfter: ["voxel-mesher", "voxel-shader", "voxel-stitch"]
};
function DecalsPlugin(game, opts) {
this.game = game;
this.shell = game.shell;
this.mesherPlugin = game.plugins.get("voxel-mesher");
if (!this.mesherPlugin)
throw new Error("voxel-decals requires voxel-mesher");
this.shaderPlugin = game.plugins.get("voxel-shader");
if (!this.shaderPlugin)
throw new Error("voxel-decals requires voxel-shader");
this.stitchPlugin = game.plugins.get("voxel-stitch");
if (!this.stitchPlugin)
throw new Error("voxel-stitch requires voxel-shader");
this.info = [];
this.enable();
}
DecalsPlugin.prototype.add = function(info) {
this.info.push(info);
};
DecalsPlugin.prototype.remove = function(position) {
var found = undefined;
for (var i = 0; i < this.info.length; i += 1) {
if (this.info[i].position[0] === position[0] && this.info[i].position[1] === position[1] && this.info[i].position[2] === position[2]) {
found = i;
break;
}
}
if (found === undefined)
return;
this.info.splice(found, 1);
};
DecalsPlugin.prototype.change = function(info) {
this.remove(info.position);
this.add(info);
};
DecalsPlugin.prototype.enable = function() {
this.shell.on("gl-init", this.onInit = this.shaderInit.bind(this));
this.shell.on("gl-render", this.onRender = this.render.bind(this));
this.stitchPlugin.on("updateTexture", this.onUpdateTexture = this.update.bind(this));
};
DecalsPlugin.prototype.disable = function() {
this.stitchPlugin.removeListener("updateTexture", this.onUpdateTexture);
this.shell.removeListener("gl-render", this.onRender = this.render.bind(this));
this.shell.removeListener("gl-init", this.onInit);
};
DecalsPlugin.prototype.shaderInit = function() {
this.shader = require("glslify/adapter.js")("\n#define GLSLIFY 1\n\nattribute vec3 position;\nattribute vec2 uv;\nuniform mat4 projection;\nuniform mat4 view;\nuniform mat4 model;\nvarying vec2 vUv;\nvoid main() {\n gl_Position = projection * view * model * vec4(position, 1.0);\n vUv = uv;\n}", "\n#define GLSLIFY 1\n\nprecision highp float;\nuniform sampler2D texture;\nvarying vec2 vUv;\nvoid main() {\n gl_FragColor = texture2D(texture, vUv);\n}", [{"name":"projection","type":"mat4"},{"name":"view","type":"mat4"},{"name":"model","type":"mat4"},{"name":"texture","type":"sampler2D"}], [{"name":"position","type":"vec3"},{"name":"uv","type":"vec2"}])(this.shell.gl);
};
DecalsPlugin.prototype.update = function() {
var cube = {
"0|0|1": [0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1],
"0|0|-1": [0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0],
"0|1|0": [0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0],
"0|-1|0": [0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1],
"1|0|0": [1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1],
"-1|0|0": [0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0]
};
var vertices = [];
var uvArray = [];
for (var i = 0; i < this.info.length; i += 1) {
var normal = this.info[i].normal;
var plane = cube[normal.join("|")].slice(0);
for (var j = 0; j < plane.length; j += 1) {
plane[j] += this.info[i].position[j % 3];
plane[j] += normal[j % 3] * 0.001;
}
vertices = vertices.concat(plane);
var tileUV = this.stitchPlugin.getTextureUV(this.info[i].texture);
if (!tileUV)
throw new Error("failed to load decal texture: " + this.info[i].texture + " for " + this.info[i]);
var planeUV = [tileUV[3], tileUV[0], tileUV[1], tileUV[2]];
var r = 0;
if (normal[0] === -1 || normal[1] === -1 || normal[2] === 1) {
r = 3;
}
uvArray.push(planeUV[(0 + r) % 4][0]);
uvArray.push(planeUV[(0 + r) % 4][1]);
uvArray.push(planeUV[(1 + r) % 4][0]);
uvArray.push(planeUV[(1 + r) % 4][1]);
uvArray.push(planeUV[(2 + r) % 4][0]);
uvArray.push(planeUV[(2 + r) % 4][1]);
uvArray.push(planeUV[(0 + r) % 4][0]);
uvArray.push(planeUV[(0 + r) % 4][1]);
uvArray.push(planeUV[(2 + r) % 4][0]);
uvArray.push(planeUV[(2 + r) % 4][1]);
uvArray.push(planeUV[(3 + r) % 4][0]);
uvArray.push(planeUV[(3 + r) % 4][1]);
}
var uv = new Float32Array(uvArray);
var gl = this.shell.gl;
var verticesBuf = createBuffer(gl, new Float32Array(vertices));
var uvBuf = createBuffer(gl, uv);
this.mesh = createVAO(gl, [{
buffer: verticesBuf,
size: 3
}, {
buffer: uvBuf,
size: 2
}]);
this.mesh.length = vertices.length / 3;
};
var scratch0 = mat4.create();
DecalsPlugin.prototype.render = function() {
if (this.mesh) {
var gl = this.shell.gl;
this.shader.bind();
this.shader.attributes.position.location = 0;
this.shader.attributes.uv.location = 1;
this.shader.uniforms.projection = this.shaderPlugin.projectionMatrix;
this.shader.uniforms.view = this.shaderPlugin.viewMatrix;
this.shader.uniforms.model = scratch0;
if (this.stitchPlugin.texture)
this.shader.uniforms.texture = this.stitchPlugin.texture.bind();
this.mesh.bind();
this.mesh.draw(gl.TRIANGLES, this.mesh.length);
this.mesh.unbind();
}
};
},{"gl-buffer":145,"gl-mat4":167,"gl-vao":187,"glslify":189,"glslify/adapter.js":188}],145:[function(require,module,exports){
arguments[4][96][0].apply(exports,arguments)
},{"dup":96,"ndarray":151,"ndarray-ops":146,"typedarray-pool":155,"webglew":157}],146:[function(require,module,exports){
arguments[4][97][0].apply(exports,arguments)
},{"cwise-compiler":147,"dup":97}],147:[function(require,module,exports){
arguments[4][98][0].apply(exports,arguments)
},{"./lib/thunk.js":149,"dup":98}],148:[function(require,module,exports){
arguments[4][99][0].apply(exports,arguments)
},{"dup":99,"uniq":150}],149:[function(require,module,exports){
arguments[4][100][0].apply(exports,arguments)
},{"./compile.js":148,"dup":100}],150:[function(require,module,exports){
arguments[4][101][0].apply(exports,arguments)
},{"dup":101}],151:[function(require,module,exports){
arguments[4][102][0].apply(exports,arguments)
},{"buffer":17,"dup":102,"iota-array":152}],152:[function(require,module,exports){
arguments[4][103][0].apply(exports,arguments)
},{"dup":103}],153:[function(require,module,exports){
arguments[4][104][0].apply(exports,arguments)
},{"dup":104}],154:[function(require,module,exports){
arguments[4][105][0].apply(exports,arguments)
},{"dup":105}],155:[function(require,module,exports){
arguments[4][106][0].apply(exports,arguments)
},{"bit-twiddle":153,"buffer":17,"dup":106}],156:[function(require,module,exports){
arguments[4][107][0].apply(exports,arguments)
},{"dup":107}],157:[function(require,module,exports){
arguments[4][108][0].apply(exports,arguments)
},{"dup":108,"weak-map":156}],158:[function(require,module,exports){
module.exports = adjoint;
/**
* Calculates the adjugate of a mat4
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @returns {mat4} out
*/
function adjoint(out, a) {
var 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];
out[0] = (a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22));
out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));
out[2] = (a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12));
out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));
out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));
out[5] = (a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22));
out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));
out[7] = (a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12));
out[8] = (a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21));
out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));
out[10] = (a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11));
out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));
out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));
out[13] = (a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21));
out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));
out[15] = (a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11));
return out;
};
},{}],159:[function(require,module,exports){
module.exports = clone;
/**
* Creates a new mat4 initialized with values from an existing matrix
*
* @param {mat4} a matrix to clone
* @returns {mat4} a new 4x4 matrix
*/
function clone(a) {
var out = new Float32Array(16);
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[8] = a[8];
out[9] = a[9];
out[10] = a[10];
out[11] = a[11];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
return out;
};
},{}],160:[function(require,module,exports){
module.exports = copy;
/**
* Copy the values from one mat4 to another
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @returns {mat4} out
*/
function copy(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[8] = a[8];
out[9] = a[9];
out[10] = a[10];
out[11] = a[11];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
return out;
};
},{}],161:[function(require,module,exports){
module.exports = create;
/**
* Creates a new identity mat4
*
* @returns {mat4} a new 4x4 matrix
*/
function create() {
var out = new Float32Array(16);
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = 1;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 1;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
};
},{}],162:[function(require,module,exports){
module.exports = determinant;
/**
* Calculates the determinant of a mat4
*
* @param {mat4} a the source matrix
* @returns {Number} determinant of a
*/
function determinant(a) {
var 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],
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
return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
};
},{}],163:[function(require,module,exports){
module.exports = fromQuat;
/**
* Creates a matrix from a quaternion rotation.
*
* @param {mat4} out mat4 receiving operation result
* @param {quat4} q Rotation quaternion
* @returns {mat4} out
*/
function fromQuat(out, q) {
var x = q[0], y = q[1], z = q[2], w = q[3],
x2 = x + x,
y2 = y + y,
z2 = z + z,
xx = x * x2,
yx = y * x2,
yy = y * y2,
zx = z * x2,
zy = z * y2,
zz = z * z2,
wx = w * x2,
wy = w * y2,
wz = w * z2;
out[0] = 1 - yy - zz;
out[1] = yx + wz;
out[2] = zx - wy;
out[3] = 0;
out[4] = yx - wz;
out[5] = 1 - xx - zz;
out[6] = zy + wx;
out[7] = 0;
out[8] = zx + wy;
out[9] = zy - wx;
out[10] = 1 - xx - yy;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
};
},{}],164:[function(require,module,exports){
module.exports = fromRotationTranslation;
/**
* Creates a matrix from a quaternion rotation and vector translation
* This is equivalent to (but much faster than):
*
* mat4.identity(dest);
* mat4.translate(dest, vec);
* var quatMat = mat4.create();
* quat4.toMat4(quat, quatMat);
* mat4.multiply(dest, quatMat);
*
* @param {mat4} out mat4 receiving operation result
* @param {quat4} q Rotation quaternion
* @param {vec3} v Translation vector
* @returns {mat4} out
*/
function fromRotationTranslation(out, q, v) {
// Quaternion math
var x = q[0], y = q[1], z = q[2], w = q[3],
x2 = x + x,
y2 = y + y,
z2 = z + z,
xx = x * x2,
xy = x * y2,
xz = x * z2,
yy = y * y2,
yz = y * z2,
zz = z * z2,
wx = w * x2,
wy = w * y2,
wz = w * z2;
out[0] = 1 - (yy + zz);
out[1] = xy + wz;
out[2] = xz - wy;
out[3] = 0;
out[4] = xy - wz;
out[5] = 1 - (xx + zz);
out[6] = yz + wx;
out[7] = 0;
out[8] = xz + wy;
out[9] = yz - wx;
out[10] = 1 - (xx + yy);
out[11] = 0;
out[12] = v[0];
out[13] = v[1];
out[14] = v[2];
out[15] = 1;
return out;
};
},{}],165:[function(require,module,exports){
module.exports = frustum;
/**
* Generates a frustum matrix with the given bounds
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {Number} left Left bound of the frustum
* @param {Number} right Right bound of the frustum
* @param {Number} bottom Bottom bound of the frustum
* @param {Number} top Top bound of the frustum
* @param {Number} near Near bound of the frustum
* @param {Number} far Far bound of the frustum
* @returns {mat4} out
*/
function frustum(out, left, right, bottom, top, near, far) {
var rl = 1 / (right - left),
tb = 1 / (top - bottom),
nf = 1 / (near - far);
out[0] = (near * 2) * rl;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = (near * 2) * tb;
out[6] = 0;
out[7] = 0;
out[8] = (right + left) * rl;
out[9] = (top + bottom) * tb;
out[10] = (far + near) * nf;
out[11] = -1;
out[12] = 0;
out[13] = 0;
out[14] = (far * near * 2) * nf;
out[15] = 0;
return out;
};
},{}],166:[function(require,module,exports){
module.exports = identity;
/**
* Set a mat4 to the identity matrix
*
* @param {mat4} out the receiving matrix
* @returns {mat4} out
*/
function identity(out) {
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = 1;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 1;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
};
},{}],167:[function(require,module,exports){
module.exports = {
create: require('./create')
, clone: require('./clone')
, copy: require('./copy')
, identity: require('./identity')
, transpose: require('./transpose')
, invert: require('./invert')
, adjoint: require('./adjoint')
, determinant: require('./determinant')
, multiply: require('./multiply')
, translate: require('./translate')
, scale: require('./scale')
, rotate: require('./rotate')
, rotateX: require('./rotateX')
, rotateY: require('./rotateY')
, rotateZ: require('./rotateZ')
, fromRotationTranslation: require('./fromRotationTranslation')
, fromQuat: require('./fromQuat')
, frustum: require('./frustum')
, perspective: require('./perspective')
, perspectiveFromFieldOfView: require('./perspectiveFromFieldOfView')
, ortho: require('./ortho')
, lookAt: require('./lookAt')
, str: require('./str')
}
},{"./adjoint":158,"./clone":159,"./copy":160,"./create":161,"./determinant":162,"./fromQuat":163,"./fromRotationTranslation":164,"./frustum":165,"./identity":166,"./invert":168,"./lookAt":169,"./multiply":170,"./ortho":171,"./perspective":172,"./perspectiveFromFieldOfView":173,"./rotate":174,"./rotateX":175,"./rotateY":176,"./rotateZ":177,"./scale":178,"./str":179,"./translate":180,"./transpose":181}],168:[function(require,module,exports){
module.exports = invert;
/**
* Inverts a mat4
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @returns {mat4} out
*/
function invert(out, a) {
var 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],
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;
out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
return out;
};
},{}],169:[function(require,module,exports){
var identity = require('./identity');
module.exports = lookAt;
/**
* Generates a look-at matrix with the given eye position, focal point, and up axis
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {vec3} eye Position of the viewer
* @param {vec3} center Point the viewer is looking at
* @param {vec3} up vec3 pointing up
* @returns {mat4} out
*/
function lookAt(out, eye, center, up) {
var x0, x1, x2, y0, y1, y2, z0, z1, z2, len,
eyex = eye[0],
eyey = eye[1],
eyez = eye[2],
upx = up[0],
upy = up[1],
upz = up[2],
centerx = center[0],
centery = center[1],
centerz = center[2];
if (Math.abs(eyex - centerx) < 0.000001 &&
Math.abs(eyey - centery) < 0.000001 &&
Math.abs(eyez - centerz) < 0.000001) {
return identity(out);
}
z0 = eyex - centerx;
z1 = eyey - centery;
z2 = eyez - centerz;
len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
z0 *= len;
z1 *= len;
z2 *= len;
x0 = upy * z2 - upz * z1;
x1 = upz * z0 - upx * z2;
x2 = upx * z1 - upy * z0;
len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
if (!len) {
x0 = 0;
x1 = 0;
x2 = 0;
} else {
len = 1 / len;
x0 *= len;
x1 *= len;
x2 *= len;
}
y0 = z1 * x2 - z2 * x1;
y1 = z2 * x0 - z0 * x2;
y2 = z0 * x1 - z1 * x0;
len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);
if (!len) {
y0 = 0;
y1 = 0;
y2 = 0;
} else {
len = 1 / len;
y0 *= len;
y1 *= len;
y2 *= len;
}
out[0] = x0;
out[1] = y0;
out[2] = z0;
out[3] = 0;
out[4] = x1;
out[5] = y1;
out[6] = z1;
out[7] = 0;
out[8] = x2;
out[9] = y2;
out[10] = z2;
out[11] = 0;
out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
out[15] = 1;
return out;
};
},{"./identity":166}],170:[function(require,module,exports){
module.exports = multiply;
/**
* Multiplies two mat4's
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the first operand
* @param {mat4} b the second operand
* @returns {mat4} out
*/
function multiply(out, a, b) {
var 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];
// Cache only the current line of the second matrix
var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7];
out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11];
out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15];
out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
return out;
};
},{}],171:[function(require,module,exports){
module.exports = ortho;
/**
* Generates a orthogonal projection matrix with the given bounds
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {number} left Left bound of the frustum
* @param {number} right Right bound of the frustum
* @param {number} bottom Bottom bound of the frustum
* @param {number} top Top bound of the frustum
* @param {number} near Near bound of the frustum
* @param {number} far Far bound of the frustum
* @returns {mat4} out
*/
function ortho(out, left, right, bottom, top, near, far) {
var lr = 1 / (left - right),
bt = 1 / (bottom - top),
nf = 1 / (near - far);
out[0] = -2 * lr;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = -2 * bt;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 2 * nf;
out[11] = 0;
out[12] = (left + right) * lr;
out[13] = (top + bottom) * bt;
out[14] = (far + near) * nf;
out[15] = 1;
return out;
};
},{}],172:[function(require,module,exports){
module.exports = perspective;
/**
* Generates a perspective projection matrix with the given bounds
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {number} fovy Vertical field of view in radians
* @param {number} aspect Aspect ratio. typically viewport width/height
* @param {number} near Near bound of the frustum
* @param {number} far Far bound of the frustum
* @returns {mat4} out
*/
function perspective(out, fovy, aspect, near, far) {
var f = 1.0 / Math.tan(fovy / 2),
nf = 1 / (near - far);
out[0] = f / aspect;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = f;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = (far + near) * nf;
out[11] = -1;
out[12] = 0;
out[13] = 0;
out[14] = (2 * far * near) * nf;
out[15] = 0;
return out;
};
},{}],173:[function(require,module,exports){
module.exports = perspectiveFromFieldOfView;
/**
* Generates a perspective projection matrix with the given field of view.
* This is primarily useful for generating projection matrices to be used
* with the still experiemental WebVR API.
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {number} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees
* @param {number} near Near bound of the frustum
* @param {number} far Far bound of the frustum
* @returns {mat4} out
*/
function perspectiveFromFieldOfView(out, fov, near, far) {
var upTan = Math.tan(fov.upDegrees * Math.PI/180.0),
downTan = Math.tan(fov.downDegrees * Math.PI/180.0),
leftTan = Math.tan(fov.leftDegrees * Math.PI/180.0),
rightTan = Math.tan(fov.rightDegrees * Math.PI/180.0),
xScale = 2.0 / (leftTan + rightTan),
yScale = 2.0 / (upTan + downTan);
out[0] = xScale;
out[1] = 0.0;
out[2] = 0.0;
out[3] = 0.0;
out[4] = 0.0;
out[5] = yScale;
out[6] = 0.0;
out[7] = 0.0;
out[8] = -((leftTan - rightTan) * xScale * 0.5);
out[9] = ((upTan - downTan) * yScale * 0.5);
out[10] = far / (near - far);
out[11] = -1.0;
out[12] = 0.0;
out[13] = 0.0;
out[14] = (far * near) / (near - far);
out[15] = 0.0;
return out;
}
},{}],174:[function(require,module,exports){
module.exports = rotate;
/**
* Rotates a mat4 by the given angle
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @param {vec3} axis the axis to rotate around
* @returns {mat4} out
*/
function rotate(out, a, rad, axis) {
var x = axis[0], y = axis[1], z = axis[2],
len = Math.sqrt(x * x + y * y + z * z),
s, c, t,
a00, a01, a02, a03,
a10, a11, a12, a13,
a20, a21, a22, a23,
b00, b01, b02,
b10, b11, b12,
b20, b21, b22;
if (Math.abs(len) < 0.000001) { return null; }
len = 1 / len;
x *= len;
y *= len;
z *= len;
s = Math.sin(rad);
c = Math.cos(rad);
t = 1 - c;
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];
// Construct the elements of the rotation matrix
b00 = x * x * t + c; b01 = y * x * t + z * s; b02 = z * x * t - y * s;
b10 = x * y * t - z * s; b11 = y * y * t + c; b12 = z * y * t + x * s;
b20 = x * z * t + y * s; b21 = y * z * t - x * s; b22 = z * z * t + c;
// Perform rotation-specific matrix multiplication
out[0] = a00 * b00 + a10 * b01 + a20 * b02;
out[1] = a01 * b00 + a11 * b01 + a21 * b02;
out[2] = a02 * b00 + a12 * b01 + a22 * b02;
out[3] = a03 * b00 + a13 * b01 + a23 * b02;
out[4] = a00 * b10 + a10 * b11 + a20 * b12;
out[5] = a01 * b10 + a11 * b11 + a21 * b12;
out[6] = a02 * b10 + a12 * b11 + a22 * b12;
out[7] = a03 * b10 + a13 * b11 + a23 * b12;
out[8] = a00 * b20 + a10 * b21 + a20 * b22;
out[9] = a01 * b20 + a11 * b21 + a21 * b22;
out[10] = a02 * b20 + a12 * b21 + a22 * b22;
out[11] = a03 * b20 + a13 * b21 + a23 * b22;
if (a !== out) { // If the source and destination differ, copy the unchanged last row
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
return out;
};
},{}],175:[function(require,module,exports){
module.exports = rotateX;
/**
* Rotates a matrix by the given angle around the X axis
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function rotateX(out, a, rad) {
var s = Math.sin(rad),
c = Math.cos(rad),
a10 = a[4],
a11 = a[5],
a12 = a[6],
a13 = a[7],
a20 = a[8],
a21 = a[9],
a22 = a[10],
a23 = a[11];
if (a !== out) { // If the source and destination differ, copy the unchanged rows
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
// Perform axis-specific matrix multiplication
out[4] = a10 * c + a20 * s;
out[5] = a11 * c + a21 * s;
out[6] = a12 * c + a22 * s;
out[7] = a13 * c + a23 * s;
out[8] = a20 * c - a10 * s;
out[9] = a21 * c - a11 * s;
out[10] = a22 * c - a12 * s;
out[11] = a23 * c - a13 * s;
return out;
};
},{}],176:[function(require,module,exports){
module.exports = rotateY;
/**
* Rotates a matrix by the given angle around the Y axis
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function rotateY(out, a, rad) {
var s = Math.sin(rad),
c = Math.cos(rad),
a00 = a[0],
a01 = a[1],
a02 = a[2],
a03 = a[3],
a20 = a[8],
a21 = a[9],
a22 = a[10],
a23 = a[11];
if (a !== out) { // If the source and destination differ, copy the unchanged rows
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
// Perform axis-specific matrix multiplication
out[0] = a00 * c - a20 * s;
out[1] = a01 * c - a21 * s;
out[2] = a02 * c - a22 * s;
out[3] = a03 * c - a23 * s;
out[8] = a00 * s + a20 * c;
out[9] = a01 * s + a21 * c;
out[10] = a02 * s + a22 * c;
out[11] = a03 * s + a23 * c;
return out;
};
},{}],177:[function(require,module,exports){
module.exports = rotateZ;
/**
* Rotates a matrix by the given angle around the Z axis
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function rotateZ(out, a, rad) {
var s = Math.sin(rad),
c = Math.cos(rad),
a00 = a[0],
a01 = a[1],
a02 = a[2],
a03 = a[3],
a10 = a[4],
a11 = a[5],
a12 = a[6],
a13 = a[7];
if (a !== out) { // If the source and destination differ, copy the unchanged last row
out[8] = a[8];
out[9] = a[9];
out[10] = a[10];
out[11] = a[11];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
// Perform axis-specific matrix multiplication
out[0] = a00 * c + a10 * s;
out[1] = a01 * c + a11 * s;
out[2] = a02 * c + a12 * s;
out[3] = a03 * c + a13 * s;
out[4] = a10 * c - a00 * s;
out[5] = a11 * c - a01 * s;
out[6] = a12 * c - a02 * s;
out[7] = a13 * c - a03 * s;
return out;
};
},{}],178:[function(require,module,exports){
module.exports = scale;
/**
* Scales the mat4 by the dimensions in the given vec3
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to scale
* @param {vec3} v the vec3 to scale the matrix by
* @returns {mat4} out
**/
function scale(out, a, v) {
var x = v[0], y = v[1], z = v[2];
out[0] = a[0] * x;
out[1] = a[1] * x;
out[2] = a[2] * x;
out[3] = a[3] * x;
out[4] = a[4] * y;
out[5] = a[5] * y;
out[6] = a[6] * y;
out[7] = a[7] * y;
out[8] = a[8] * z;
out[9] = a[9] * z;
out[10] = a[10] * z;
out[11] = a[11] * z;
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
return out;
};
},{}],179:[function(require,module,exports){
module.exports = str;
/**
* Returns a string representation of a mat4
*
* @param {mat4} mat matrix to represent as a string
* @returns {String} string representation of the matrix
*/
function str(a) {
return 'mat4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' +
a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ', ' +
a[8] + ', ' + a[9] + ', ' + a[10] + ', ' + a[11] + ', ' +
a[12] + ', ' + a[13] + ', ' + a[14] + ', ' + a[15] + ')';
};
},{}],180:[function(require,module,exports){
module.exports = translate;
/**
* Translate a mat4 by the given vector
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to translate
* @param {vec3} v vector to translate by
* @returns {mat4} out
*/
function translate(out, a, v) {
var x = v[0], y = v[1], z = v[2],
a00, a01, a02, a03,
a10, a11, a12, a13,
a20, a21, a22, a23;
if (a === out) {
out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
} else {
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];
out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03;
out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13;
out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23;
out[12] = a00 * x + a10 * y + a20 * z + a[12];
out[13] = a01 * x + a11 * y + a21 * z + a[13];
out[14] = a02 * x + a12 * y + a22 * z + a[14];
out[15] = a03 * x + a13 * y + a23 * z + a[15];
}
return out;
};
},{}],181:[function(require,module,exports){
module.exports = transpose;
/**
* Transpose the values of a mat4
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @returns {mat4} out
*/
function transpose(out, a) {
// If we are transposing ourselves we can skip a few steps but have to cache some values
if (out === a) {
var a01 = a[1], a02 = a[2], a03 = a[3],
a12 = a[6], a13 = a[7],
a23 = a[11];
out[1] = a[4];
out[2] = a[8];
out[3] = a[12];
out[4] = a01;
out[6] = a[9];
out[7] = a[13];
out[8] = a02;
out[9] = a12;
out[11] = a[14];
out[12] = a03;
out[13] = a13;
out[14] = a23;
} else {
out[0] = a[0];
out[1] = a[4];
out[2] = a[8];
out[3] = a[12];
out[4] = a[1];
out[5] = a[5];
out[6] = a[9];
out[7] = a[13];
out[8] = a[2];
out[9] = a[6];
out[10] = a[10];
out[11] = a[14];
out[12] = a[3];
out[13] = a[7];
out[14] = a[11];
out[15] = a[15];
}
return out;
};
},{}],182:[function(require,module,exports){
arguments[4][109][0].apply(exports,arguments)
},{"dup":109}],183:[function(require,module,exports){
arguments[4][110][0].apply(exports,arguments)
},{"./do-bind.js":182,"dup":110}],184:[function(require,module,exports){
arguments[4][111][0].apply(exports,arguments)
},{"./do-bind.js":182,"dup":111}],185:[function(require,module,exports){
arguments[4][107][0].apply(exports,arguments)
},{"dup":107}],186:[function(require,module,exports){
arguments[4][108][0].apply(exports,arguments)
},{"dup":108,"weak-map":185}],187:[function(require,module,exports){
arguments[4][114][0].apply(exports,arguments)
},{"./lib/vao-emulated.js":183,"./lib/vao-native.js":184,"dup":114,"webglew":186}],188:[function(require,module,exports){
module.exports = programify
var shader = require('gl-shader-core')
function programify(vertex, fragment, uniforms, attributes) {
return function(gl) {
return shader(gl, vertex, fragment, uniforms, attributes)
}
}
},{"gl-shader-core":194}],189:[function(require,module,exports){
module.exports = noop
function noop() {
throw new Error(
'You should bundle your code ' +
'using `glslify` as a transform.'
)
}
},{}],190:[function(require,module,exports){
'use strict'
module.exports = createAttributeWrapper
//Shader attribute class
function ShaderAttribute(gl, program, location, dimension, name, constFunc, relink) {
this._gl = gl
this._program = program
this._location = location
this._dimension = dimension
this._name = name
this._constFunc = constFunc
this._relink = relink
}
var proto = ShaderAttribute.prototype
proto.pointer = function setAttribPointer(type, normalized, stride, offset) {
var gl = this._gl
gl.vertexAttribPointer(this._location, this._dimension, type||gl.FLOAT, !!normalized, stride||0, offset||0)
this._gl.enableVertexAttribArray(this._location)
}
Object.defineProperty(proto, 'location', {
get: function() {
return this._location
}
, set: function(v) {
if(v !== this._location) {
this._location = v
this._gl.bindAttribLocation(this._program, v, this._name)
this._gl.linkProgram(this._program)
this._relink()
}
}
})
//Adds a vector attribute to obj
function addVectorAttribute(gl, program, location, dimension, obj, name, doLink) {
var constFuncArgs = [ 'gl', 'v' ]
var varNames = []
for(var i=0; i<dimension; ++i) {
constFuncArgs.push('x'+i)
varNames.push('x'+i)
}
constFuncArgs.push([
'if(x0.length===void 0){return gl.vertexAttrib', dimension, 'f(v,', varNames.join(), ')}else{return gl.vertexAttrib', dimension, 'fv(v,x0)}'
].join(''))
var constFunc = Function.apply(undefined, constFuncArgs)
var attr = new ShaderAttribute(gl, program, location, dimension, name, constFunc, doLink)
Object.defineProperty(obj, name, {
set: function(x) {
gl.disableVertexAttribArray(attr._location)
constFunc(gl, attr._location, x)
return x
}
, get: function() {
return attr
}
, enumerable: true
})
}
//Create shims for attributes
function createAttributeWrapper(gl, program, attributes, doLink) {
var obj = {}
for(var i=0, n=attributes.length; i<n; ++i) {
var a = attributes[i]
var name = a.name
var type = a.type
var location = gl.getAttribLocation(program, name)
switch(type) {
case 'bool':
case 'int':
case 'float':
addVectorAttribute(gl, program, location, 1, obj, name, doLink)
break
default:
if(type.indexOf('vec') >= 0) {
var d = type.charCodeAt(type.length-1) - 48
if(d < 2 || d > 4) {
throw new Error('gl-shader: Invalid data type for attribute ' + name + ': ' + type)
}
addVectorAttribute(gl, program, location, d, obj, name, doLink)
} else {
throw new Error('gl-shader: Unknown data type for attribute ' + name + ': ' + type)
}
break
}
}
return obj
}
},{}],191:[function(require,module,exports){
'use strict'
var dup = require('dup')
var coallesceUniforms = require('./reflect')
module.exports = createUniformWrapper
//Binds a function and returns a value
function identity(x) {
var c = new Function('y', 'return function(){return y}')
return c(x)
}
//Create shims for uniforms
function createUniformWrapper(gl, program, uniforms, locations) {
function makeGetter(index) {
var proc = new Function('gl', 'prog', 'locations',
'return function(){return gl.getUniform(prog,locations[' + index + '])}')
return proc(gl, program, locations)
}
function makePropSetter(path, index, type) {
switch(type) {
case 'bool':
case 'int':
case 'sampler2D':
case 'samplerCube':
return 'gl.uniform1i(locations[' + index + '],obj' + path + ')'
case 'float':
return 'gl.uniform1f(locations[' + index + '],obj' + path + ')'
default:
var vidx = type.indexOf('vec')
if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
var d = type.charCodeAt(type.length-1) - 48
if(d < 2 || d > 4) {
throw new Error('gl-shader: Invalid data type')
}
switch(type.charAt(0)) {
case 'b':
case 'i':
return 'gl.uniform' + d + 'iv(locations[' + index + '],obj' + path + ')'
case 'v':
return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')'
default:
throw new Error('gl-shader: Unrecognized data type for vector ' + name + ': ' + type)
}
} else if(type.indexOf('mat') === 0 && type.length === 4) {
var d = type.charCodeAt(type.length-1) - 48
if(d < 2 || d > 4) {
throw new Error('gl-shader: Invalid uniform dimension type for matrix ' + name + ': ' + type)
}
return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')'
} else {
throw new Error('gl-shader: Unknown uniform data type for ' + name + ': ' + type)
}
break
}
}
function enumerateIndices(prefix, type) {
if(typeof type !== 'object') {
return [ [prefix, type] ]
}
var indices = []
for(var id in type) {
var prop = type[id]
var tprefix = prefix
if(parseInt(id) + '' === id) {
tprefix += '[' + id + ']'
} else {
tprefix += '.' + id
}
if(typeof prop === 'object') {
indices.push.apply(indices, enumerateIndices(tprefix, prop))
} else {
indices.push([tprefix, prop])
}
}
return indices
}
function makeSetter(type) {
var code = [ 'return function updateProperty(obj){' ]
var indices = enumerateIndices('', type)
for(var i=0; i<indices.length; ++i) {
var item = indices[i]
var path = item[0]
var idx = item[1]
if(locations[idx]) {
code.push(makePropSetter(path, idx, uniforms[idx].type))
}
}
code.push('return obj}')
var proc = new Function('gl', 'prog', 'locations', code.join('\n'))
return proc(gl, program, locations)
}
function defaultValue(type) {
switch(type) {
case 'bool':
return false
case 'int':
case 'sampler2D':
case 'samplerCube':
return 0
case 'float':
return 0.0
default:
var vidx = type.indexOf('vec')
if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
var d = type.charCodeAt(type.length-1) - 48
if(d < 2 || d > 4) {
throw new Error('gl-shader: Invalid data type')
}
if(type.charAt(0) === 'b') {
return dup(d, false)
}
return dup(d)
} else if(type.indexOf('mat') === 0 && type.length === 4) {
var d = type.charCodeAt(type.length-1) - 48
if(d < 2 || d > 4) {
throw new Error('gl-shader: Invalid uniform dimension type for matrix ' + name + ': ' + type)
}
return dup([d,d])
} else {
throw new Error('gl-shader: Unknown uniform data type for ' + name + ': ' + type)
}
break
}
}
function storeProperty(obj, prop, type) {
if(typeof type === 'object') {
var child = processObject(type)
Object.defineProperty(obj, prop, {
get: identity(child),
set: makeSetter(type),
enumerable: true,
configurable: false
})
} else {
if(locations[type]) {
Object.defineProperty(obj, prop, {
get: makeGetter(type),
set: makeSetter(type),
enumerable: true,
configurable: false
})
} else {
obj[prop] = defaultValue(uniforms[type].type)
}
}
}
function processObject(obj) {
var result
if(Array.isArray(obj)) {
result = new Array(obj.length)
for(var i=0; i<obj.length; ++i) {
storeProperty(result, i, obj[i])
}
} else {
result = {}
for(var id in obj) {
storeProperty(result, id, obj[id])
}
}
return result
}
//Return data
var coallesced = coallesceUniforms(uniforms, true)
return {
get: identity(processObject(coallesced)),
set: makeSetter(coallesced),
enumerable: true,
configurable: true
}
}
},{"./reflect":192,"dup":193}],192:[function(require,module,exports){
'use strict'
module.exports = makeReflectTypes
//Construct type info for reflection.
//
// This iterates over the flattened list of uniform type values and smashes them into a JSON object.
//
// The leaves of the resulting object are either indices or type strings representing primitive glslify types
function makeReflectTypes(uniforms, useIndex) {
var obj = {}
for(var i=0; i<uniforms.length; ++i) {
var n = uniforms[i].name
var parts = n.split(".")
var o = obj
for(var j=0; j<parts.length; ++j) {
var x = parts[j].split("[")
if(x.length > 1) {
if(!(x[0] in o)) {
o[x[0]] = []
}
o = o[x[0]]
for(var k=1; k<x.length; ++k) {
var y = parseInt(x[k])
if(k<x.length-1 || j<parts.length-1) {
if(!(y in o)) {
if(k < x.length-1) {
o[y] = []
} else {
o[y] = {}
}
}
o = o[y]
} else {
if(useIndex) {
o[y] = i
} else {
o[y] = uniforms[i].type
}
}
}
} else if(j < parts.length-1) {
if(!(x[0] in o)) {
o[x[0]] = {}
}
o = o[x[0]]
} else {
if(useIndex) {
o[x[0]] = i
} else {
o[x[0]] = uniforms[i].type
}
}
}
}
return obj
}
},{}],193:[function(require,module,exports){
arguments[4][105][0].apply(exports,arguments)
},{"dup":105}],194:[function(require,module,exports){
'use strict'
var createUniformWrapper = require('./lib/create-uniforms')
var createAttributeWrapper = require('./lib/create-attributes')
var makeReflect = require('./lib/reflect')
//Shader object
function Shader(gl, prog, vertShader, fragShader) {
this.gl = gl
this.handle = prog
this.attributes = null
this.uniforms = null
this.types = null
this.vertexShader = vertShader
this.fragmentShader = fragShader
}
//Binds the shader
Shader.prototype.bind = function() {
this.gl.useProgram(this.handle)
}
//Destroy shader, release resources
Shader.prototype.dispose = function() {
var gl = this.gl
gl.deleteShader(this.vertexShader)
gl.deleteShader(this.fragmentShader)
gl.deleteProgram(this.handle)
}
Shader.prototype.updateExports = function(uniforms, attributes) {
var locations = new Array(uniforms.length)
var program = this.handle
var gl = this.gl
var doLink = relinkUniforms.bind(void 0,
gl,
program,
locations,
uniforms
)
doLink()
this.types = {
uniforms: makeReflect(uniforms),
attributes: makeReflect(attributes)
}
this.attributes = createAttributeWrapper(
gl,
program,
attributes,
doLink
)
Object.defineProperty(this, 'uniforms', createUniformWrapper(
gl,
program,
uniforms,
locations
))
}
//Relinks all uniforms
function relinkUniforms(gl, program, locations, uniforms) {
for(var i=0; i<uniforms.length; ++i) {
locations[i] = gl.getUniformLocation(program, uniforms[i].name)
}
}
//Compiles and links a shader program with the given attribute and vertex list
function createShader(
gl
, vertSource
, fragSource
, uniforms
, attributes) {
//Compile vertex shader
var vertShader = gl.createShader(gl.VERTEX_SHADER)
gl.shaderSource(vertShader, vertSource)
gl.compileShader(vertShader)
if(!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) {
var errLog = gl.getShaderInfoLog(vertShader)
console.error('gl-shader: Error compling vertex shader:', errLog)
throw new Error('gl-shader: Error compiling vertex shader:' + errLog)
}
//Compile fragment shader
var fragShader = gl.createShader(gl.FRAGMENT_SHADER)
gl.shaderSource(fragShader, fragSource)
gl.compileShader(fragShader)
if(!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) {
var errLog = gl.getShaderInfoLog(fragShader)
console.error('gl-shader: Error compiling fragment shader:', errLog)
throw new Error('gl-shader: Error compiling fragment shader:' + errLog)
}
//Link program
var program = gl.createProgram()
gl.attachShader(program, fragShader)
gl.attachShader(program, vertShader)
//Optional default attriubte locations
attributes.forEach(function(a) {
if (typeof a.location === 'number')
gl.bindAttribLocation(program, a.location, a.name)
})
gl.linkProgram(program)
if(!gl.getProgramParameter(program, gl.LINK_STATUS)) {
var errLog = gl.getProgramInfoLog(program)
console.error('gl-shader: Error linking shader program:', errLog)
throw new Error('gl-shader: Error linking shader program:' + errLog)
}
//Return final linked shader object
var shader = new Shader(
gl,
program,
vertShader,
fragShader
)
shader.updateExports(uniforms, attributes)
return shader
}
module.exports = createShader
},{"./lib/create-attributes":190,"./lib/create-uniforms":191,"./lib/reflect":192}],195:[function(require,module,exports){
'use strict';
var ucfirst = require('ucfirst');
module.exports = function(game, opts) {
return new DecorativePlugin(game, opts);
};
module.exports.pluginInfo = {
loadAfter: [
'voxel-registry',
'voxel-land', // for materials
'voxel-recipes']
};
function DecorativePlugin(game, opts) {
this.registry = game.plugins.get('voxel-registry');
if (!this.registry) throw new Error('voxel-decorative requires voxel-registry');
this.recipes = game.plugins.get('voxel-recipes');
if (!this.recipes) throw new Error('voxel-decorative requires voxel-recipes');
this.storageMaterials = opts.storageMaterials || ['coal', 'iron', 'gold', 'diamond'];
this.storageBases = opts.storageBases || {iron: 'ingotIron', gold: 'ingotIron'}; // TODO: refactor, metals? (always require ingots)
this.storageHardnessFactor = opts.storageHardnessFactor || 2.0;
this.enable();
}
DecorativePlugin.prototype.enable = function() {
var registry = this.registry;
var recipes = this.recipes;
var self = this;
// "storage" blocks
this.storageMaterials.forEach(function(name) {
var baseMaterial = self.storageBases[name] || name;
var baseHardness = registry.getProp('ore' + ucfirst(baseMaterial), 'hardness') || 20.0;
registry.registerBlock('block' + ucfirst(name), {
texture: name + '_block',
displayName: 'Block of ' + ucfirst(name),
hardness: baseHardness * self.storageHardnessFactor,
creativeTab: 'decorative'
});
// blocking up TODO: require a compressor?
recipes.registerAmorphous([
baseMaterial, baseMaterial, baseMaterial,
baseMaterial, baseMaterial, baseMaterial,
baseMaterial, baseMaterial, baseMaterial], ['block' + ucfirst(name)]);
// blocking down TODO: require a macerator?
recipes.registerAmorphous(['block' + ucfirst(name)], [baseMaterial, 9]);
});
// stone bricks
var hardness = registry.getProp('cobblestone', 'hardness') || 10.0; // match stone hardness
registry.registerBlock('stoneBrick', {texture: 'stonebrick', displayName: 'Stone Bricks', hardness: hardness, creativeTab: 'decorative'});
registry.registerBlock('stoneBrickCarved', {texture: 'stonebrick_carved', displayName: 'Carved Stone Bricks', hardness: hardness, creativeTab: 'decorative'});
registry.registerBlock('stoneBrickCracked', {texture: 'stonebrick_cracked', displayName: 'Cracked Stone Bricks', hardness: hardness, creativeTab: 'decorative'});
registry.registerBlock('stoneBrickMossy', {texture: 'stonebrick_mossy', displayName: 'Mossy Stone Bricks', hardness: hardness, creativeTab: 'decorative'});
recipes.registerPositional([
['stone', 'stone'],
['stone', 'stone']], ['stoneBrick']);
recipes.registerAmorphous(['stoneBrick'], ['stoneBrickCarved']); // TODO: maybe require using on a chisel?
recipes.registerAmorphous(['stoneBrickCarved'], ['stoneBrickCracked']);
//recipes.registerAmorphous(['stoneBrickCracked', ['stoneBrick']);
// TODO: recipe for mossy (+vines?)
};
DecorativePlugin.prototype.disable = function() {
// TODO
};
},{"ucfirst":196}],196:[function(require,module,exports){
arguments[4][68][0].apply(exports,arguments)
},{"dup":68}],197:[function(require,module,exports){
var DropPlugin, coffee_script, ever, playerdat;
ever = require('ever');
coffee_script = require('coffee-script');
playerdat = require('playerdat');
require('string.prototype.endswith');
module.exports = function(game, opts) {
return new DropPlugin(game, opts);
};
module.exports.pluginInfo = {
loadAfter: ['voxel-stitch']
};
DropPlugin = (function() {
function DropPlugin(game1, opts) {
var ref, ref1, ref2, ref3;
this.game = game1;
if (!this.game.isClient) {
return;
}
this.packs = (ref = (ref1 = this.game.materials) != null ? ref1.artPacks : void 0) != null ? ref : (ref2 = this.game.plugins) != null ? (ref3 = ref2.get('voxel-stitch')) != null ? ref3.artpacks : void 0 : void 0;
if (this.packs == null) {
throw new Error('voxel-drop requires voxel-stitch or voxel-texture-shader with artPacks');
}
this.body = ever(document.body);
this.enable();
}
DropPlugin.prototype.enable = function() {
this.body.on('dragover', this.dragover = function(ev) {
ev.stopPropagation();
return ev.preventDefault();
});
return this.body.on('drop', this.drop = (function(_this) {
return function(mouseEvent) {
var file, files, j, len, results, shouldAdd, shouldClear;
mouseEvent.stopPropagation();
mouseEvent.preventDefault();
console.log('drop', mouseEvent);
files = mouseEvent.target.files || mouseEvent.dataTransfer.files;
console.log('Dropped', files);
results = [];
for (j = 0, len = files.length; j < len; j++) {
file = files[j];
console.log('Reading dropped', file);
if (file.name.endsWith('.zip') || file.name.endsWith('.jar')) {
shouldClear = mouseEvent.shiftKey;
results.push(_this.loadArtPack(file, shouldClear));
} else if (file.name.endsWith('.js')) {
results.push(_this.loadScript(file));
} else if (file.name.endsWith('.coffee')) {
results.push(_this.loadScript(file));
} else if (file.name.endsWith('.dat')) {
shouldAdd = mouseEvent.shiftKey;
results.push(_this.loadPlayerDat(file, shouldAdd));
} else {
results.push(window.alert("Unrecognized file dropped: " + file.name + ". Try dropping a resourcepack/artpack (.zip)"));
}
}
return results;
};
})(this));
};
DropPlugin.prototype.readAll = function(file, cb) {
var reader;
reader = new FileReader();
ever(reader).on('load', (function(_this) {
return function(readEvent) {
var result;
if (readEvent.total !== readEvent.loaded) {
return;
}
result = readEvent.currentTarget.result;
return cb(result);
};
})(this));
return reader;
};
DropPlugin.prototype.readAllText = function(file, cb) {
return (this.readAll(file, cb)).readAsText(file);
};
DropPlugin.prototype.readAllData = function(file, cb) {
return (this.readAll(file, cb)).readAsArrayBuffer(file);
};
DropPlugin.prototype.loadScript = function(file) {
return this.readAllText(file, (function(_this) {
return function(rawText) {
var createCreatePlugin, createPlugin, e, name, opts, plugin, text;
if (file.name.endsWith('.coffee')) {
text = coffee_script.compile(rawText);
} else {
text = rawText;
}
try {
createCreatePlugin = new Function("var module = {exports: {}}; var require = " + _this.game.plugins.require + "; " + text + " return module.exports;");
} catch (_error) {
e = _error;
window.alert("Exception loading plugin " + file.name + ": " + e);
throw e;
}
createPlugin = createCreatePlugin();
name = file.name;
opts = {};
console.log("loadScript #file.name = " + createPlugin);
if (!createPlugin || typeof createPlugin !== 'function') {
console.log("Ignored non-plugin " + name + ", returned " + createPlugin);
return;
}
plugin = _this.game.plugins.instantiate(createPlugin, name, opts);
if (!plugin) {
return window.alert('Failed to load plugin ' + name);
} else {
return console.log("Loaded plugin: " + name + " = " + plugin);
}
};
})(this));
};
DropPlugin.prototype.loadArtPack = function(file, shouldClear) {
return this.readAllData(file, (function(_this) {
return function(arrayBuffer) {
if (shouldClear) {
_this.packs.clear();
}
_this.packs.once('refresh', function() {
return window.setTimeout(function() {
var base;
return typeof (base = _this.game).showAllChunks === "function" ? base.showAllChunks() : void 0;
}, 5000);
});
return _this.packs.addPack(arrayBuffer, file.name);
};
})(this));
};
DropPlugin.prototype.loadPlayerDat = function(file, shouldAdd) {
return this.readAllData(file, (function(_this) {
return function(arrayBuffer) {
var carryInventory, ref;
carryInventory = (ref = _this.game.plugins.get('voxel-carry')) != null ? ref.inventory : void 0;
if (carryInventory == null) {
return;
}
return playerdat.loadInventory(arrayBuffer, function(inventory) {
var i, j, ref1, results;
if (inventory != null) {
if (!shouldAdd) {
carryInventory.clear();
}
results = [];
for (i = j = 0, ref1 = inventory.size(); 0 <= ref1 ? j < ref1 : j > ref1; i = 0 <= ref1 ? ++j : --j) {
if (shouldAdd) {
results.push(carryInventory.give(inventory.get(i)));
} else {
results.push(carryInventory.set(i, inventory.get(i)));
}
}
return results;
}
});
};
})(this));
};
DropPlugin.prototype.disable = function() {
this.body.removeListener('dragover', this.dragover);
return this.body.removeListener('drop', this.drop);
};
return DropPlugin;
})();
},{"coffee-script":198,"ever":48,"playerdat":218,"string.prototype.endswith":219}],198:[function(require,module,exports){
(function (process,global){
// Generated by CoffeeScript 1.9.1
(function() {
var Lexer, SourceMap, base, compile, ext, formatSourcePosition, fs, getSourceMap, helpers, i, len, lexer, parser, path, ref, sourceMaps, vm, withPrettyErrors,
hasProp = {}.hasOwnProperty,
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
fs = require('fs');
vm = require('vm');
path = require('path');
Lexer = require('./lexer').Lexer;
parser = require('./parser').parser;
helpers = require('./helpers');
SourceMap = require('./sourcemap');
exports.VERSION = '1.9.1';
exports.FILE_EXTENSIONS = ['.coffee', '.litcoffee', '.coffee.md'];
exports.helpers = helpers;
withPrettyErrors = function(fn) {
return function(code, options) {
var err;
if (options == null) {
options = {};
}
try {
return fn.call(this, code, options);
} catch (_error) {
err = _error;
throw helpers.updateSyntaxError(err, code, options.filename);
}
};
};
exports.compile = compile = withPrettyErrors(function(code, options) {
var answer, currentColumn, currentLine, extend, fragment, fragments, header, i, js, len, map, merge, newLines, token, tokens;
merge = helpers.merge, extend = helpers.extend;
options = extend({}, options);
if (options.sourceMap) {
map = new SourceMap;
}
tokens = lexer.tokenize(code, options);
options.referencedVars = (function() {
var i, len, results;
results = [];
for (i = 0, len = tokens.length; i < len; i++) {
token = tokens[i];
if (token.variable) {
results.push(token[1]);
}
}
return results;
})();
fragments = parser.parse(tokens).compileToFragments(options);
currentLine = 0;
if (options.header) {
currentLine += 1;
}
if (options.shiftLine) {
currentLine += 1;
}
currentColumn = 0;
js = "";
for (i = 0, len = fragments.length; i < len; i++) {
fragment = fragments[i];
if (options.sourceMap) {
if (fragment.locationData) {
map.add([fragment.locationData.first_line, fragment.locationData.first_column], [currentLine, currentColumn], {
noReplace: true
});
}
newLines = helpers.count(fragment.code, "\n");
currentLine += newLines;
if (newLines) {
currentColumn = fragment.code.length - (fragment.code.lastIndexOf("\n") + 1);
} else {
currentColumn += fragment.code.length;
}
}
js += fragment.code;
}
if (options.header) {
header = "Generated by CoffeeScript " + this.VERSION;
js = "// " + header + "\n" + js;
}
if (options.sourceMap) {
answer = {
js: js
};
answer.sourceMap = map;
answer.v3SourceMap = map.generate(options, code);
return answer;
} else {
return js;
}
});
exports.tokens = withPrettyErrors(function(code, options) {
return lexer.tokenize(code, options);
});
exports.nodes = withPrettyErrors(function(source, options) {
if (typeof source === 'string') {
return parser.parse(lexer.tokenize(source, options));
} else {
return parser.parse(source);
}
});
exports.run = function(code, options) {
var answer, dir, mainModule, ref;
if (options == null) {
options = {};
}
mainModule = require.main;
mainModule.filename = process.argv[1] = options.filename ? fs.realpathSync(options.filename) : '.';
mainModule.moduleCache && (mainModule.moduleCache = {});
dir = options.filename ? path.dirname(fs.realpathSync(options.filename)) : fs.realpathSync('.');
mainModule.paths = require('module')._nodeModulePaths(dir);
if (!helpers.isCoffee(mainModule.filename) || require.extensions) {
answer = compile(code, options);
code = (ref = answer.js) != null ? ref : answer;
}
return mainModule._compile(code, mainModule.filename);
};
exports["eval"] = function(code, options) {
var Module, _module, _require, createContext, i, isContext, js, k, len, o, r, ref, ref1, ref2, ref3, sandbox, v;
if (options == null) {
options = {};
}
if (!(code = code.trim())) {
return;
}
createContext = (ref = vm.Script.createContext) != null ? ref : vm.createContext;
isContext = (ref1 = vm.isContext) != null ? ref1 : function(ctx) {
return options.sandbox instanceof createContext().constructor;
};
if (createContext) {
if (options.sandbox != null) {
if (isContext(options.sandbox)) {
sandbox = options.sandbox;
} else {
sandbox = createContext();
ref2 = options.sandbox;
for (k in ref2) {
if (!hasProp.call(ref2, k)) continue;
v = ref2[k];
sandbox[k] = v;
}
}
sandbox.global = sandbox.root = sandbox.GLOBAL = sandbox;
} else {
sandbox = global;
}
sandbox.__filename = options.filename || 'eval';
sandbox.__dirname = path.dirname(sandbox.__filename);
if (!(sandbox !== global || sandbox.module || sandbox.require)) {
Module = require('module');
sandbox.module = _module = new Module(options.modulename || 'eval');
sandbox.require = _require = function(path) {
return Module._load(path, _module, true);
};
_module.filename = sandbox.__filename;
ref3 = Object.getOwnPropertyNames(require);
for (i = 0, len = ref3.length; i < len; i++) {
r = ref3[i];
if (r !== 'paths') {
_require[r] = require[r];
}
}
_require.paths = _module.paths = Module._nodeModulePaths(process.cwd());
_require.resolve = function(request) {
return Module._resolveFilename(request, _module);
};
}
}
o = {};
for (k in options) {
if (!hasProp.call(options, k)) continue;
v = options[k];
o[k] = v;
}
o.bare = true;
js = compile(code, o);
if (sandbox === global) {
return vm.runInThisContext(js);
} else {
return vm.runInContext(js, sandbox);
}
};
exports.register = function() {
return require('./register');
};
if (require.extensions) {
ref = this.FILE_EXTENSIONS;
for (i = 0, len = ref.length; i < len; i++) {
ext = ref[i];
if ((base = require.extensions)[ext] == null) {
base[ext] = function() {
throw new Error("Use CoffeeScript.register() or require the coffee-script/register module to require " + ext + " files.");
};
}
}
}
exports._compileFile = function(filename, sourceMap) {
var answer, err, raw, stripped;
if (sourceMap == null) {
sourceMap = false;
}
raw = fs.readFileSync(filename, 'utf8');
stripped = raw.charCodeAt(0) === 0xFEFF ? raw.substring(1) : raw;
try {
answer = compile(stripped, {
filename: filename,
sourceMap: sourceMap,
literate: helpers.isLiterate(filename)
});
} catch (_error) {
err = _error;
throw helpers.updateSyntaxError(err, stripped, filename);
}
return answer;
};
lexer = new Lexer;
parser.lexer = {
lex: function() {
var tag, token;
token = parser.tokens[this.pos++];
if (token) {
tag = token[0], this.yytext = token[1], this.yylloc = token[2];
parser.errorToken = token.origin || token;
this.yylineno = this.yylloc.first_line;
} else {
tag = '';
}
return tag;
},
setInput: function(tokens) {
parser.tokens = tokens;
return this.pos = 0;
},
upcomingInput: function() {
return "";
}
};
parser.yy = require('./nodes');
parser.yy.parseError = function(message, arg) {
var errorLoc, errorTag, errorText, errorToken, token, tokens;
token = arg.token;
errorToken = parser.errorToken, tokens = parser.tokens;
errorTag = errorToken[0], errorText = errorToken[1], errorLoc = errorToken[2];
errorText = (function() {
switch (false) {
case errorToken !== tokens[tokens.length - 1]:
return 'end of input';
case errorTag !== 'INDENT' && errorTag !== 'OUTDENT':
return 'indentation';
case errorTag !== 'IDENTIFIER' && errorTag !== 'NUMBER' && errorTag !== 'STRING' && errorTag !== 'STRING_START' && errorTag !== 'REGEX' && errorTag !== 'REGEX_START':
return errorTag.replace(/_START$/, '').toLowerCase();
default:
return helpers.nameWhitespaceCharacter(errorText);
}
})();
return helpers.throwSyntaxError("unexpected " + errorText, errorLoc);
};
formatSourcePosition = function(frame, getSourceMapping) {
var as, column, fileLocation, fileName, functionName, isConstructor, isMethodCall, line, methodName, source, tp, typeName;
fileName = void 0;
fileLocation = '';
if (frame.isNative()) {
fileLocation = "native";
} else {
if (frame.isEval()) {
fileName = frame.getScriptNameOrSourceURL();
if (!fileName) {
fileLocation = (frame.getEvalOrigin()) + ", ";
}
} else {
fileName = frame.getFileName();
}
fileName || (fileName = "<anonymous>");
line = frame.getLineNumber();
column = frame.getColumnNumber();
source = getSourceMapping(fileName, line, column);
fileLocation = source ? fileName + ":" + source[0] + ":" + source[1] : fileName + ":" + line + ":" + column;
}
functionName = frame.getFunctionName();
isConstructor = frame.isConstructor();
isMethodCall = !(frame.isToplevel() || isConstructor);
if (isMethodCall) {
methodName = frame.getMethodName();
typeName = frame.getTypeName();
if (functionName) {
tp = as = '';
if (typeName && functionName.indexOf(typeName)) {
tp = typeName + ".";
}
if (methodName && functionName.indexOf("." + methodName) !== functionName.length - methodName.length - 1) {
as = " [as " + methodName + "]";
}
return "" + tp + functionName + as + " (" + fileLocation + ")";
} else {
return typeName + "." + (methodName || '<anonymous>') + " (" + fileLocation + ")";
}
} else if (isConstructor) {
return "new " + (functionName || '<anonymous>') + " (" + fileLocation + ")";
} else if (functionName) {
return functionName + " (" + fileLocation + ")";
} else {
return fileLocation;
}
};
sourceMaps = {};
getSourceMap = function(filename) {
var answer, ref1;
if (sourceMaps[filename]) {
return sourceMaps[filename];
}
if (ref1 = path != null ? path.extname(filename) : void 0, indexOf.call(exports.FILE_EXTENSIONS, ref1) < 0) {
return;
}
answer = exports._compileFile(filename, true);
return sourceMaps[filename] = answer.sourceMap;
};
Error.prepareStackTrace = function(err, stack) {
var frame, frames, getSourceMapping;
getSourceMapping = function(filename, line, column) {
var answer, sourceMap;
sourceMap = getSourceMap(filename);
if (sourceMap) {
answer = sourceMap.sourceLocation([line - 1, column - 1]);
}
if (answer) {
return [answer[0] + 1, answer[1] + 1];
} else {
return null;
}
};
frames = (function() {
var j, len1, results;
results = [];
for (j = 0, len1 = stack.length; j < len1; j++) {
frame = stack[j];
if (frame.getFunction() === exports.run) {
break;
}
results.push(" at " + (formatSourcePosition(frame, getSourceMapping)));
}
return results;
})();
return (err.toString()) + "\n" + (frames.join('\n')) + "\n";
};
}).call(this);
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./helpers":199,"./lexer":200,"./nodes":201,"./parser":202,"./register":203,"./sourcemap":206,"_process":25,"fs":1,"module":1,"path":24,"vm":41}],199:[function(require,module,exports){
(function (process){
// Generated by CoffeeScript 1.9.1
(function() {
var buildLocationData, extend, flatten, ref, repeat, syntaxErrorToString;
exports.starts = function(string, literal, start) {
return literal === string.substr(start, literal.length);
};
exports.ends = function(string, literal, back) {
var len;
len = literal.length;
return literal === string.substr(string.length - len - (back || 0), len);
};
exports.repeat = repeat = function(str, n) {
var res;
res = '';
while (n > 0) {
if (n & 1) {
res += str;
}
n >>>= 1;
str += str;
}
return res;
};
exports.compact = function(array) {
var i, item, len1, results;
results = [];
for (i = 0, len1 = array.length; i < len1; i++) {
item = array[i];
if (item) {
results.push(item);
}
}
return results;
};
exports.count = function(string, substr) {
var num, pos;
num = pos = 0;
if (!substr.length) {
return 1 / 0;
}
while (pos = 1 + string.indexOf(substr, pos)) {
num++;
}
return num;
};
exports.merge = function(options, overrides) {
return extend(extend({}, options), overrides);
};
extend = exports.extend = function(object, properties) {
var key, val;
for (key in properties) {
val = properties[key];
object[key] = val;
}
return object;
};
exports.flatten = flatten = function(array) {
var element, flattened, i, len1;
flattened = [];
for (i = 0, len1 = array.length; i < len1; i++) {
element = array[i];
if (element instanceof Array) {
flattened = flattened.concat(flatten(element));
} else {
flattened.push(element);
}
}
return flattened;
};
exports.del = function(obj, key) {
var val;
val = obj[key];
delete obj[key];
return val;
};
exports.some = (ref = Array.prototype.some) != null ? ref : function(fn) {
var e, i, len1;
for (i = 0, len1 = this.length; i < len1; i++) {
e = this[i];
if (fn(e)) {
return true;
}
}
return false;
};
exports.invertLiterate = function(code) {
var line, lines, maybe_code;
maybe_code = true;
lines = (function() {
var i, len1, ref1, results;
ref1 = code.split('\n');
results = [];
for (i = 0, len1 = ref1.length; i < len1; i++) {
line = ref1[i];
if (maybe_code && /^([ ]{4}|[ ]{0,3}\t)/.test(line)) {
results.push(line);
} else if (maybe_code = /^\s*$/.test(line)) {
results.push(line);
} else {
results.push('# ' + line);
}
}
return results;
})();
return lines.join('\n');
};
buildLocationData = function(first, last) {
if (!last) {
return first;
} else {
return {
first_line: first.first_line,
first_column: first.first_column,
last_line: last.last_line,
last_column: last.last_column
};
}
};
exports.addLocationDataFn = function(first, last) {
return function(obj) {
if (((typeof obj) === 'object') && (!!obj['updateLocationDataIfMissing'])) {
obj.updateLocationDataIfMissing(buildLocationData(first, last));
}
return obj;
};
};
exports.locationDataToString = function(obj) {
var locationData;
if (("2" in obj) && ("first_line" in obj[2])) {
locationData = obj[2];
} else if ("first_line" in obj) {
locationData = obj;
}
if (locationData) {
return ((locationData.first_line + 1) + ":" + (locationData.first_column + 1) + "-") + ((locationData.last_line + 1) + ":" + (locationData.last_column + 1));
} else {
return "No location data";
}
};
exports.baseFileName = function(file, stripExt, useWinPathSep) {
var parts, pathSep;
if (stripExt == null) {
stripExt = false;
}
if (useWinPathSep == null) {
useWinPathSep = false;
}
pathSep = useWinPathSep ? /\\|\// : /\//;
parts = file.split(pathSep);
file = parts[parts.length - 1];
if (!(stripExt && file.indexOf('.') >= 0)) {
return file;
}
parts = file.split('.');
parts.pop();
if (parts[parts.length - 1] === 'coffee' && parts.length > 1) {
parts.pop();
}
return parts.join('.');
};
exports.isCoffee = function(file) {
return /\.((lit)?coffee|coffee\.md)$/.test(file);
};
exports.isLiterate = function(file) {
return /\.(litcoffee|coffee\.md)$/.test(file);
};
exports.throwSyntaxError = function(message, location) {
var error;
error = new SyntaxError(message);
error.location = location;
error.toString = syntaxErrorToString;
error.stack = error.toString();
throw error;
};
exports.updateSyntaxError = function(error, code, filename) {
if (error.toString === syntaxErrorToString) {
error.code || (error.code = code);
error.filename || (error.filename = filename);
error.stack = error.toString();
}
return error;
};
syntaxErrorToString = function() {
var codeLine, colorize, colorsEnabled, end, filename, first_column, first_line, last_column, last_line, marker, ref1, ref2, start;
if (!(this.code && this.location)) {
return Error.prototype.toString.call(this);
}
ref1 = this.location, first_line = ref1.first_line, first_column = ref1.first_column, last_line = ref1.last_line, last_column = ref1.last_column;
if (last_line == null) {
last_line = first_line;
}
if (last_column == null) {
last_column = first_column;
}
filename = this.filename || '[stdin]';
codeLine = this.code.split('\n')[first_line];
start = first_column;
end = first_line === last_line ? last_column + 1 : codeLine.length;
marker = codeLine.slice(0, start).replace(/[^\s]/g, ' ') + repeat('^', end - start);
if (typeof process !== "undefined" && process !== null) {
colorsEnabled = process.stdout.isTTY && !process.env.NODE_DISABLE_COLORS;
}
if ((ref2 = this.colorful) != null ? ref2 : colorsEnabled) {
colorize = function(str) {
return "\x1B[1;31m" + str + "\x1B[0m";
};
codeLine = codeLine.slice(0, start) + colorize(codeLine.slice(start, end)) + codeLine.slice(end);
marker = colorize(marker);
}
return filename + ":" + (first_line + 1) + ":" + (first_column + 1) + ": error: " + this.message + "\n" + codeLine + "\n" + marker;
};
exports.nameWhitespaceCharacter = function(string) {
switch (string) {
case ' ':
return 'space';
case '\n':
return 'newline';
case '\r':
return 'carriage return';
case '\t':
return 'tab';
default:
return string;
}
};
}).call(this);
}).call(this,require('_process'))
},{"_process":25}],200:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var BOM, BOOL, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_ALIAS_MAP, COFFEE_KEYWORDS, COMMENT, COMPARE, COMPOUND_ASSIGN, HERECOMMENT_ILLEGAL, HEREDOC_DOUBLE, HEREDOC_INDENT, HEREDOC_SINGLE, HEREGEX, HEREGEX_OMIT, IDENTIFIER, INDENTABLE_CLOSERS, INDEXABLE, INVALID_ESCAPE, INVERSES, JSTOKEN, JS_FORBIDDEN, JS_KEYWORDS, LEADING_BLANK_LINE, LINE_BREAK, LINE_CONTINUER, LOGIC, Lexer, MATH, MULTI_DENT, NOT_REGEX, NUMBER, OPERATOR, POSSIBLY_DIVISION, REGEX, REGEX_FLAGS, REGEX_ILLEGAL, RELATION, RESERVED, Rewriter, SHIFT, SIMPLE_STRING_OMIT, STRICT_PROSCRIBED, STRING_DOUBLE, STRING_OMIT, STRING_SINGLE, STRING_START, TRAILING_BLANK_LINE, TRAILING_SPACES, UNARY, UNARY_MATH, VALID_FLAGS, WHITESPACE, compact, count, invertLiterate, key, locationDataToString, ref, ref1, repeat, starts, throwSyntaxError,
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
ref = require('./rewriter'), Rewriter = ref.Rewriter, INVERSES = ref.INVERSES;
ref1 = require('./helpers'), count = ref1.count, starts = ref1.starts, compact = ref1.compact, repeat = ref1.repeat, invertLiterate = ref1.invertLiterate, locationDataToString = ref1.locationDataToString, throwSyntaxError = ref1.throwSyntaxError;
exports.Lexer = Lexer = (function() {
function Lexer() {}
Lexer.prototype.tokenize = function(code, opts) {
var consumed, end, i, ref2;
if (opts == null) {
opts = {};
}
this.literate = opts.literate;
this.indent = 0;
this.baseIndent = 0;
this.indebt = 0;
this.outdebt = 0;
this.indents = [];
this.ends = [];
this.tokens = [];
this.chunkLine = opts.line || 0;
this.chunkColumn = opts.column || 0;
code = this.clean(code);
i = 0;
while (this.chunk = code.slice(i)) {
consumed = this.identifierToken() || this.commentToken() || this.whitespaceToken() || this.lineToken() || this.stringToken() || this.numberToken() || this.regexToken() || this.jsToken() || this.literalToken();
ref2 = this.getLineAndColumnFromChunk(consumed), this.chunkLine = ref2[0], this.chunkColumn = ref2[1];
i += consumed;
if (opts.untilBalanced && this.ends.length === 0) {
return {
tokens: this.tokens,
index: i
};
}
}
this.closeIndentation();
if (end = this.ends.pop()) {
this.error("missing " + end.tag, end.origin[2]);
}
if (opts.rewrite === false) {
return this.tokens;
}
return (new Rewriter).rewrite(this.tokens);
};
Lexer.prototype.clean = function(code) {
if (code.charCodeAt(0) === BOM) {
code = code.slice(1);
}
code = code.replace(/\r/g, '').replace(TRAILING_SPACES, '');
if (WHITESPACE.test(code)) {
code = "\n" + code;
this.chunkLine--;
}
if (this.literate) {
code = invertLiterate(code);
}
return code;
};
Lexer.prototype.identifierToken = function() {
var colon, colonOffset, forcedIdentifier, id, idLength, input, match, poppedToken, prev, ref2, ref3, ref4, ref5, tag, tagToken;
if (!(match = IDENTIFIER.exec(this.chunk))) {
return 0;
}
input = match[0], id = match[1], colon = match[2];
idLength = id.length;
poppedToken = void 0;
if (id === 'own' && this.tag() === 'FOR') {
this.token('OWN', id);
return id.length;
}
if (id === 'from' && this.tag() === 'YIELD') {
this.token('FROM', id);
return id.length;
}
ref2 = this.tokens, prev = ref2[ref2.length - 1];
forcedIdentifier = colon || (prev != null) && (((ref3 = prev[0]) === '.' || ref3 === '?.' || ref3 === '::' || ref3 === '?::') || !prev.spaced && prev[0] === '@');
tag = 'IDENTIFIER';
if (!forcedIdentifier && (indexOf.call(JS_KEYWORDS, id) >= 0 || indexOf.call(COFFEE_KEYWORDS, id) >= 0)) {
tag = id.toUpperCase();
if (tag === 'WHEN' && (ref4 = this.tag(), indexOf.call(LINE_BREAK, ref4) >= 0)) {
tag = 'LEADING_WHEN';
} else if (tag === 'FOR') {
this.seenFor = true;
} else if (tag === 'UNLESS') {
tag = 'IF';
} else if (indexOf.call(UNARY, tag) >= 0) {
tag = 'UNARY';
} else if (indexOf.call(RELATION, tag) >= 0) {
if (tag !== 'INSTANCEOF' && this.seenFor) {
tag = 'FOR' + tag;
this.seenFor = false;
} else {
tag = 'RELATION';
if (this.value() === '!') {
poppedToken = this.tokens.pop();
id = '!' + id;
}
}
}
}
if (indexOf.call(JS_FORBIDDEN, id) >= 0) {
if (forcedIdentifier) {
tag = 'IDENTIFIER';
id = new String(id);
id.reserved = true;
} else if (indexOf.call(RESERVED, id) >= 0) {
this.error("reserved word '" + id + "'", {
length: id.length
});
}
}
if (!forcedIdentifier) {
if (indexOf.call(COFFEE_ALIASES, id) >= 0) {
id = COFFEE_ALIAS_MAP[id];
}
tag = (function() {
switch (id) {
case '!':
return 'UNARY';
case '==':
case '!=':
return 'COMPARE';
case '&&':
case '||':
return 'LOGIC';
case 'true':
case 'false':
return 'BOOL';
case 'break':
case 'continue':
return 'STATEMENT';
default:
return tag;
}
})();
}
tagToken = this.token(tag, id, 0, idLength);
tagToken.variable = !forcedIdentifier;
if (poppedToken) {
ref5 = [poppedToken[2].first_line, poppedToken[2].first_column], tagToken[2].first_line = ref5[0], tagToken[2].first_column = ref5[1];
}
if (colon) {
colonOffset = input.lastIndexOf(':');
this.token(':', ':', colonOffset, colon.length);
}
return input.length;
};
Lexer.prototype.numberToken = function() {
var binaryLiteral, lexedLength, match, number, octalLiteral;
if (!(match = NUMBER.exec(this.chunk))) {
return 0;
}
number = match[0];
lexedLength = number.length;
if (/^0[BOX]/.test(number)) {
this.error("radix prefix in '" + number + "' must be lowercase", {
offset: 1
});
} else if (/E/.test(number) && !/^0x/.test(number)) {
this.error("exponential notation in '" + number + "' must be indicated with a lowercase 'e'", {
offset: number.indexOf('E')
});
} else if (/^0\d*[89]/.test(number)) {
this.error("decimal literal '" + number + "' must not be prefixed with '0'", {
length: lexedLength
});
} else if (/^0\d+/.test(number)) {
this.error("octal literal '" + number + "' must be prefixed with '0o'", {
length: lexedLength
});
}
if (octalLiteral = /^0o([0-7]+)/.exec(number)) {
number = '0x' + parseInt(octalLiteral[1], 8).toString(16);
}
if (binaryLiteral = /^0b([01]+)/.exec(number)) {
number = '0x' + parseInt(binaryLiteral[1], 2).toString(16);
}
this.token('NUMBER', number, 0, lexedLength);
return lexedLength;
};
Lexer.prototype.stringToken = function() {
var $, attempt, delimiter, doc, end, heredoc, i, indent, indentRegex, match, quote, ref2, ref3, regex, token, tokens;
quote = (STRING_START.exec(this.chunk) || [])[0];
if (!quote) {
return 0;
}
regex = (function() {
switch (quote) {
case "'":
return STRING_SINGLE;
case '"':
return STRING_DOUBLE;
case "'''":
return HEREDOC_SINGLE;
case '"""':
return HEREDOC_DOUBLE;
}
})();
heredoc = quote.length === 3;
ref2 = this.matchWithInterpolations(regex, quote), tokens = ref2.tokens, end = ref2.index;
$ = tokens.length - 1;
delimiter = quote[0];
if (heredoc) {
indent = null;
doc = ((function() {
var j, len, results;
results = [];
for (i = j = 0, len = tokens.length; j < len; i = ++j) {
token = tokens[i];
if (token[0] === 'NEOSTRING') {
results.push(token[1]);
}
}
return results;
})()).join('#{}');
while (match = HEREDOC_INDENT.exec(doc)) {
attempt = match[1];
if (indent === null || (0 < (ref3 = attempt.length) && ref3 < indent.length)) {
indent = attempt;
}
}
if (indent) {
indentRegex = RegExp("^" + indent, "gm");
}
this.mergeInterpolationTokens(tokens, {
delimiter: delimiter
}, (function(_this) {
return function(value, i) {
value = _this.formatString(value);
if (i === 0) {
value = value.replace(LEADING_BLANK_LINE, '');
}
if (i === $) {
value = value.replace(TRAILING_BLANK_LINE, '');
}
if (indentRegex) {
value = value.replace(indentRegex, '');
}
return value;
};
})(this));
} else {
this.mergeInterpolationTokens(tokens, {
delimiter: delimiter
}, (function(_this) {
return function(value, i) {
value = _this.formatString(value);
value = value.replace(SIMPLE_STRING_OMIT, function(match, offset) {
if ((i === 0 && offset === 0) || (i === $ && offset + match.length === value.length)) {
return '';
} else {
return ' ';
}
});
return value;
};
})(this));
}
return end;
};
Lexer.prototype.commentToken = function() {
var comment, here, match;
if (!(match = this.chunk.match(COMMENT))) {
return 0;
}
comment = match[0], here = match[1];
if (here) {
if (match = HERECOMMENT_ILLEGAL.exec(comment)) {
this.error("block comments cannot contain " + match[0], {
offset: match.index,
length: match[0].length
});
}
if (here.indexOf('\n') >= 0) {
here = here.replace(RegExp("\\n" + (repeat(' ', this.indent)), "g"), '\n');
}
this.token('HERECOMMENT', here, 0, comment.length);
}
return comment.length;
};
Lexer.prototype.jsToken = function() {
var match, script;
if (!(this.chunk.charAt(0) === '`' && (match = JSTOKEN.exec(this.chunk)))) {
return 0;
}
this.token('JS', (script = match[0]).slice(1, -1), 0, script.length);
return script.length;
};
Lexer.prototype.regexToken = function() {
var body, closed, end, flags, index, match, origin, prev, ref2, ref3, ref4, regex, tokens;
switch (false) {
case !(match = REGEX_ILLEGAL.exec(this.chunk)):
this.error("regular expressions cannot begin with " + match[2], {
offset: match.index + match[1].length
});
break;
case !(match = this.matchWithInterpolations(HEREGEX, '///')):
tokens = match.tokens, index = match.index;
break;
case !(match = REGEX.exec(this.chunk)):
regex = match[0], body = match[1], closed = match[2];
this.validateEscapes(body, {
isRegex: true,
offsetInChunk: 1
});
index = regex.length;
ref2 = this.tokens, prev = ref2[ref2.length - 1];
if (prev) {
if (prev.spaced && (ref3 = prev[0], indexOf.call(CALLABLE, ref3) >= 0)) {
if (!closed || POSSIBLY_DIVISION.test(regex)) {
return 0;
}
} else if (ref4 = prev[0], indexOf.call(NOT_REGEX, ref4) >= 0) {
return 0;
}
}
if (!closed) {
this.error('missing / (unclosed regex)');
}
break;
default:
return 0;
}
flags = REGEX_FLAGS.exec(this.chunk.slice(index))[0];
end = index + flags.length;
origin = this.makeToken('REGEX', null, 0, end);
switch (false) {
case !!VALID_FLAGS.test(flags):
this.error("invalid regular expression flags " + flags, {
offset: index,
length: flags.length
});
break;
case !(regex || tokens.length === 1):
if (body == null) {
body = this.formatHeregex(tokens[0][1]);
}
this.token('REGEX', "" + (this.makeDelimitedLiteral(body, {
delimiter: '/'
})) + flags, 0, end, origin);
break;
default:
this.token('REGEX_START', '(', 0, 0, origin);
this.token('IDENTIFIER', 'RegExp', 0, 0);
this.token('CALL_START', '(', 0, 0);
this.mergeInterpolationTokens(tokens, {
delimiter: '"',
double: true
}, this.formatHeregex);
if (flags) {
this.token(',', ',', index, 0);
this.token('STRING', '"' + flags + '"', index, flags.length);
}
this.token(')', ')', end, 0);
this.token('REGEX_END', ')', end, 0);
}
return end;
};
Lexer.prototype.lineToken = function() {
var diff, indent, match, noNewlines, size;
if (!(match = MULTI_DENT.exec(this.chunk))) {
return 0;
}
indent = match[0];
this.seenFor = false;
size = indent.length - 1 - indent.lastIndexOf('\n');
noNewlines = this.unfinished();
if (size - this.indebt === this.indent) {
if (noNewlines) {
this.suppressNewlines();
} else {
this.newlineToken(0);
}
return indent.length;
}
if (size > this.indent) {
if (noNewlines) {
this.indebt = size - this.indent;
this.suppressNewlines();
return indent.length;
}
if (!this.tokens.length) {
this.baseIndent = this.indent = size;
return indent.length;
}
diff = size - this.indent + this.outdebt;
this.token('INDENT', diff, indent.length - size, size);
this.indents.push(diff);
this.ends.push({
tag: 'OUTDENT'
});
this.outdebt = this.indebt = 0;
this.indent = size;
} else if (size < this.baseIndent) {
this.error('missing indentation', {
offset: indent.length
});
} else {
this.indebt = 0;
this.outdentToken(this.indent - size, noNewlines, indent.length);
}
return indent.length;
};
Lexer.prototype.outdentToken = function(moveOut, noNewlines, outdentLength) {
var decreasedIndent, dent, lastIndent, ref2;
decreasedIndent = this.indent - moveOut;
while (moveOut > 0) {
lastIndent = this.indents[this.indents.length - 1];
if (!lastIndent) {
moveOut = 0;
} else if (lastIndent === this.outdebt) {
moveOut -= this.outdebt;
this.outdebt = 0;
} else if (lastIndent < this.outdebt) {
this.outdebt -= lastIndent;
moveOut -= lastIndent;
} else {
dent = this.indents.pop() + this.outdebt;
if (outdentLength && (ref2 = this.chunk[outdentLength], indexOf.call(INDENTABLE_CLOSERS, ref2) >= 0)) {
decreasedIndent -= dent - moveOut;
moveOut = dent;
}
this.outdebt = 0;
this.pair('OUTDENT');
this.token('OUTDENT', moveOut, 0, outdentLength);
moveOut -= dent;
}
}
if (dent) {
this.outdebt -= moveOut;
}
while (this.value() === ';') {
this.tokens.pop();
}
if (!(this.tag() === 'TERMINATOR' || noNewlines)) {
this.token('TERMINATOR', '\n', outdentLength, 0);
}
this.indent = decreasedIndent;
return this;
};
Lexer.prototype.whitespaceToken = function() {
var match, nline, prev, ref2;
if (!((match = WHITESPACE.exec(this.chunk)) || (nline = this.chunk.charAt(0) === '\n'))) {
return 0;
}
ref2 = this.tokens, prev = ref2[ref2.length - 1];
if (prev) {
prev[match ? 'spaced' : 'newLine'] = true;
}
if (match) {
return match[0].length;
} else {
return 0;
}
};
Lexer.prototype.newlineToken = function(offset) {
while (this.value() === ';') {
this.tokens.pop();
}
if (this.tag() !== 'TERMINATOR') {
this.token('TERMINATOR', '\n', offset, 0);
}
return this;
};
Lexer.prototype.suppressNewlines = function() {
if (this.value() === '\\') {
this.tokens.pop();
}
return this;
};
Lexer.prototype.literalToken = function() {
var match, prev, ref2, ref3, ref4, ref5, ref6, tag, token, value;
if (match = OPERATOR.exec(this.chunk)) {
value = match[0];
if (CODE.test(value)) {
this.tagParameters();
}
} else {
value = this.chunk.charAt(0);
}
tag = value;
ref2 = this.tokens, prev = ref2[ref2.length - 1];
if (value === '=' && prev) {
if (!prev[1].reserved && (ref3 = prev[1], indexOf.call(JS_FORBIDDEN, ref3) >= 0)) {
this.error("reserved word '" + prev[1] + "' can't be assigned", prev[2]);
}
if ((ref4 = prev[1]) === '||' || ref4 === '&&') {
prev[0] = 'COMPOUND_ASSIGN';
prev[1] += '=';
return value.length;
}
}
if (value === ';') {
this.seenFor = false;
tag = 'TERMINATOR';
} else if (indexOf.call(MATH, value) >= 0) {
tag = 'MATH';
} else if (indexOf.call(COMPARE, value) >= 0) {
tag = 'COMPARE';
} else if (indexOf.call(COMPOUND_ASSIGN, value) >= 0) {
tag = 'COMPOUND_ASSIGN';
} else if (indexOf.call(UNARY, value) >= 0) {
tag = 'UNARY';
} else if (indexOf.call(UNARY_MATH, value) >= 0) {
tag = 'UNARY_MATH';
} else if (indexOf.call(SHIFT, value) >= 0) {
tag = 'SHIFT';
} else if (indexOf.call(LOGIC, value) >= 0 || value === '?' && (prev != null ? prev.spaced : void 0)) {
tag = 'LOGIC';
} else if (prev && !prev.spaced) {
if (value === '(' && (ref5 = prev[0], indexOf.call(CALLABLE, ref5) >= 0)) {
if (prev[0] === '?') {
prev[0] = 'FUNC_EXIST';
}
tag = 'CALL_START';
} else if (value === '[' && (ref6 = prev[0], indexOf.call(INDEXABLE, ref6) >= 0)) {
tag = 'INDEX_START';
switch (prev[0]) {
case '?':
prev[0] = 'INDEX_SOAK';
}
}
}
token = this.makeToken(tag, value);
switch (value) {
case '(':
case '{':
case '[':
this.ends.push({
tag: INVERSES[value],
origin: token
});
break;
case ')':
case '}':
case ']':
this.pair(value);
}
this.tokens.push(token);
return value.length;
};
Lexer.prototype.tagParameters = function() {
var i, stack, tok, tokens;
if (this.tag() !== ')') {
return this;
}
stack = [];
tokens = this.tokens;
i = tokens.length;
tokens[--i][0] = 'PARAM_END';
while (tok = tokens[--i]) {
switch (tok[0]) {
case ')':
stack.push(tok);
break;
case '(':
case 'CALL_START':
if (stack.length) {
stack.pop();
} else if (tok[0] === '(') {
tok[0] = 'PARAM_START';
return this;
} else {
return this;
}
}
}
return this;
};
Lexer.prototype.closeIndentation = function() {
return this.outdentToken(this.indent);
};
Lexer.prototype.matchWithInterpolations = function(regex, delimiter) {
var close, column, firstToken, index, lastToken, line, nested, offsetInChunk, open, ref2, ref3, ref4, str, strPart, tokens;
tokens = [];
offsetInChunk = delimiter.length;
if (this.chunk.slice(0, offsetInChunk) !== delimiter) {
return null;
}
str = this.chunk.slice(offsetInChunk);
while (true) {
strPart = regex.exec(str)[0];
this.validateEscapes(strPart, {
isRegex: delimiter.charAt(0) === '/',
offsetInChunk: offsetInChunk
});
tokens.push(this.makeToken('NEOSTRING', strPart, offsetInChunk));
str = str.slice(strPart.length);
offsetInChunk += strPart.length;
if (str.slice(0, 2) !== '#{') {
break;
}
ref2 = this.getLineAndColumnFromChunk(offsetInChunk + 1), line = ref2[0], column = ref2[1];
ref3 = new Lexer().tokenize(str.slice(1), {
line: line,
column: column,
untilBalanced: true
}), nested = ref3.tokens, index = ref3.index;
index += 1;
open = nested[0], close = nested[nested.length - 1];
open[0] = open[1] = '(';
close[0] = close[1] = ')';
close.origin = ['', 'end of interpolation', close[2]];
if (((ref4 = nested[1]) != null ? ref4[0] : void 0) === 'TERMINATOR') {
nested.splice(1, 1);
}
tokens.push(['TOKENS', nested]);
str = str.slice(index);
offsetInChunk += index;
}
if (str.slice(0, delimiter.length) !== delimiter) {
this.error("missing " + delimiter, {
length: delimiter.length
});
}
firstToken = tokens[0], lastToken = tokens[tokens.length - 1];
firstToken[2].first_column -= delimiter.length;
lastToken[2].last_column += delimiter.length;
if (lastToken[1].length === 0) {
lastToken[2].last_column -= 1;
}
return {
tokens: tokens,
index: offsetInChunk + delimiter.length
};
};
Lexer.prototype.mergeInterpolationTokens = function(tokens, options, fn) {
var converted, firstEmptyStringIndex, firstIndex, i, j, lastToken, len, locationToken, lparen, plusToken, ref2, rparen, tag, token, tokensToPush, value;
if (tokens.length > 1) {
lparen = this.token('STRING_START', '(', 0, 0);
}
firstIndex = this.tokens.length;
for (i = j = 0, len = tokens.length; j < len; i = ++j) {
token = tokens[i];
tag = token[0], value = token[1];
switch (tag) {
case 'TOKENS':
if (value.length === 2) {
continue;
}
locationToken = value[0];
tokensToPush = value;
break;
case 'NEOSTRING':
converted = fn(token[1], i);
if (converted.length === 0) {
if (i === 0) {
firstEmptyStringIndex = this.tokens.length;
} else {
continue;
}
}
if (i === 2 && (firstEmptyStringIndex != null)) {
this.tokens.splice(firstEmptyStringIndex, 2);
}
token[0] = 'STRING';
token[1] = this.makeDelimitedLiteral(converted, options);
locationToken = token;
tokensToPush = [token];
}
if (this.tokens.length > firstIndex) {
plusToken = this.token('+', '+');
plusToken[2] = {
first_line: locationToken[2].first_line,
first_column: locationToken[2].first_column,
last_line: locationToken[2].first_line,
last_column: locationToken[2].first_column
};
}
(ref2 = this.tokens).push.apply(ref2, tokensToPush);
}
if (lparen) {
lastToken = tokens[tokens.length - 1];
lparen.origin = [
'STRING', null, {
first_line: lparen[2].first_line,
first_column: lparen[2].first_column,
last_line: lastToken[2].last_line,
last_column: lastToken[2].last_column
}
];
rparen = this.token('STRING_END', ')');
return rparen[2] = {
first_line: lastToken[2].last_line,
first_column: lastToken[2].last_column,
last_line: lastToken[2].last_line,
last_column: lastToken[2].last_column
};
}
};
Lexer.prototype.pair = function(tag) {
var lastIndent, prev, ref2, ref3, wanted;
ref2 = this.ends, prev = ref2[ref2.length - 1];
if (tag !== (wanted = prev != null ? prev.tag : void 0)) {
if ('OUTDENT' !== wanted) {
this.error("unmatched " + tag);
}
ref3 = this.indents, lastIndent = ref3[ref3.length - 1];
this.outdentToken(lastIndent, true);
return this.pair(tag);
}
return this.ends.pop();
};
Lexer.prototype.getLineAndColumnFromChunk = function(offset) {
var column, lastLine, lineCount, ref2, string;
if (offset === 0) {
return [this.chunkLine, this.chunkColumn];
}
if (offset >= this.chunk.length) {
string = this.chunk;
} else {
string = this.chunk.slice(0, +(offset - 1) + 1 || 9e9);
}
lineCount = count(string, '\n');
column = this.chunkColumn;
if (lineCount > 0) {
ref2 = string.split('\n'), lastLine = ref2[ref2.length - 1];
column = lastLine.length;
} else {
column += string.length;
}
return [this.chunkLine + lineCount, column];
};
Lexer.prototype.makeToken = function(tag, value, offsetInChunk, length) {
var lastCharacter, locationData, ref2, ref3, token;
if (offsetInChunk == null) {
offsetInChunk = 0;
}
if (length == null) {
length = value.length;
}
locationData = {};
ref2 = this.getLineAndColumnFromChunk(offsetInChunk), locationData.first_line = ref2[0], locationData.first_column = ref2[1];
lastCharacter = Math.max(0, length - 1);
ref3 = this.getLineAndColumnFromChunk(offsetInChunk + lastCharacter), locationData.last_line = ref3[0], locationData.last_column = ref3[1];
token = [tag, value, locationData];
return token;
};
Lexer.prototype.token = function(tag, value, offsetInChunk, length, origin) {
var token;
token = this.makeToken(tag, value, offsetInChunk, length);
if (origin) {
token.origin = origin;
}
this.tokens.push(token);
return token;
};
Lexer.prototype.tag = function() {
var ref2, token;
ref2 = this.tokens, token = ref2[ref2.length - 1];
return token != null ? token[0] : void 0;
};
Lexer.prototype.value = function() {
var ref2, token;
ref2 = this.tokens, token = ref2[ref2.length - 1];
return token != null ? token[1] : void 0;
};
Lexer.prototype.unfinished = function() {
var ref2;
return LINE_CONTINUER.test(this.chunk) || ((ref2 = this.tag()) === '\\' || ref2 === '.' || ref2 === '?.' || ref2 === '?::' || ref2 === 'UNARY' || ref2 === 'MATH' || ref2 === 'UNARY_MATH' || ref2 === '+' || ref2 === '-' || ref2 === 'YIELD' || ref2 === '**' || ref2 === 'SHIFT' || ref2 === 'RELATION' || ref2 === 'COMPARE' || ref2 === 'LOGIC' || ref2 === 'THROW' || ref2 === 'EXTENDS');
};
Lexer.prototype.formatString = function(str) {
return str.replace(STRING_OMIT, '$1');
};
Lexer.prototype.formatHeregex = function(str) {
return str.replace(HEREGEX_OMIT, '$1$2');
};
Lexer.prototype.validateEscapes = function(str, options) {
var before, hex, invalidEscape, match, message, octal, ref2, unicode;
if (options == null) {
options = {};
}
match = INVALID_ESCAPE.exec(str);
if (!match) {
return;
}
match[0], before = match[1], octal = match[2], hex = match[3], unicode = match[4];
if (options.isRegex && octal && octal.charAt(0) !== '0') {
return;
}
message = octal ? "octal escape sequences are not allowed" : "invalid escape sequence";
invalidEscape = "\\" + (octal || hex || unicode);
return this.error(message + " " + invalidEscape, {
offset: ((ref2 = options.offsetInChunk) != null ? ref2 : 0) + match.index + before.length,
length: invalidEscape.length
});
};
Lexer.prototype.makeDelimitedLiteral = function(body, options) {
var regex;
if (options == null) {
options = {};
}
if (body === '' && options.delimiter === '/') {
body = '(?:)';
}
regex = RegExp("(\\\\\\\\)|(\\\\0(?=[1-7]))|\\\\?(" + options.delimiter + ")|\\\\?(?:(\\n)|(\\r)|(\\u2028)|(\\u2029))|(\\\\.)", "g");
body = body.replace(regex, function(match, backslash, nul, delimiter, lf, cr, ls, ps, other) {
switch (false) {
case !backslash:
if (options.double) {
return backslash + backslash;
} else {
return backslash;
}
case !nul:
return '\\x00';
case !delimiter:
return "\\" + delimiter;
case !lf:
return '\\n';
case !cr:
return '\\r';
case !ls:
return '\\u2028';
case !ps:
return '\\u2029';
case !other:
if (options.double) {
return "\\" + other;
} else {
return other;
}
}
});
return "" + options.delimiter + body + options.delimiter;
};
Lexer.prototype.error = function(message, options) {
var first_column, first_line, location, ref2, ref3, ref4;
if (options == null) {
options = {};
}
location = 'first_line' in options ? options : ((ref3 = this.getLineAndColumnFromChunk((ref2 = options.offset) != null ? ref2 : 0), first_line = ref3[0], first_column = ref3[1], ref3), {
first_line: first_line,
first_column: first_column,
last_column: first_column + ((ref4 = options.length) != null ? ref4 : 1) - 1
});
return throwSyntaxError(message, location);
};
return Lexer;
})();
JS_KEYWORDS = ['true', 'false', 'null', 'this', 'new', 'delete', 'typeof', 'in', 'instanceof', 'return', 'throw', 'break', 'continue', 'debugger', 'yield', 'if', 'else', 'switch', 'for', 'while', 'do', 'try', 'catch', 'finally', 'class', 'extends', 'super'];
COFFEE_KEYWORDS = ['undefined', 'then', 'unless', 'until', 'loop', 'of', 'by', 'when'];
COFFEE_ALIAS_MAP = {
and: '&&',
or: '||',
is: '==',
isnt: '!=',
not: '!',
yes: 'true',
no: 'false',
on: 'true',
off: 'false'
};
COFFEE_ALIASES = (function() {
var results;
results = [];
for (key in COFFEE_ALIAS_MAP) {
results.push(key);
}
return results;
})();
COFFEE_KEYWORDS = COFFEE_KEYWORDS.concat(COFFEE_ALIASES);
RESERVED = ['case', 'default', 'function', 'var', 'void', 'with', 'const', 'let', 'enum', 'export', 'import', 'native', 'implements', 'interface', 'package', 'private', 'protected', 'public', 'static'];
STRICT_PROSCRIBED = ['arguments', 'eval', 'yield*'];
JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED).concat(STRICT_PROSCRIBED);
exports.RESERVED = RESERVED.concat(JS_KEYWORDS).concat(COFFEE_KEYWORDS).concat(STRICT_PROSCRIBED);
exports.STRICT_PROSCRIBED = STRICT_PROSCRIBED;
BOM = 65279;
IDENTIFIER = /^(?!\d)((?:(?!\s)[$\w\x7f-\uffff])+)([^\n\S]*:(?!:))?/;
NUMBER = /^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i;
OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>*\/%])\2=?|\?(\.|::)|\.{2,3})/;
WHITESPACE = /^[^\n\S]+/;
COMMENT = /^###([^#][\s\S]*?)(?:###[^\n\S]*|###$)|^(?:\s*#(?!##[^#]).*)+/;
CODE = /^[-=]>/;
MULTI_DENT = /^(?:\n[^\n\S]*)+/;
JSTOKEN = /^`[^\\`]*(?:\\.[^\\`]*)*`/;
STRING_START = /^(?:'''|"""|'|")/;
STRING_SINGLE = /^(?:[^\\']|\\[\s\S])*/;
STRING_DOUBLE = /^(?:[^\\"#]|\\[\s\S]|\#(?!\{))*/;
HEREDOC_SINGLE = /^(?:[^\\']|\\[\s\S]|'(?!''))*/;
HEREDOC_DOUBLE = /^(?:[^\\"#]|\\[\s\S]|"(?!"")|\#(?!\{))*/;
STRING_OMIT = /((?:\\\\)+)|\\[^\S\n]*\n\s*/g;
SIMPLE_STRING_OMIT = /\s*\n\s*/g;
HEREDOC_INDENT = /\n+([^\n\S]*)(?=\S)/g;
REGEX = /^\/(?!\/)((?:[^[\/\n\\]|\\[^\n]|\[(?:\\[^\n]|[^\]\n\\])*])*)(\/)?/;
REGEX_FLAGS = /^\w*/;
VALID_FLAGS = /^(?!.*(.).*\1)[imgy]*$/;
HEREGEX = /^(?:[^\\\/#]|\\[\s\S]|\/(?!\/\/)|\#(?!\{))*/;
HEREGEX_OMIT = /((?:\\\\)+)|\\(\s)|\s+(?:#.*)?/g;
REGEX_ILLEGAL = /^(\/|\/{3}\s*)(\*)/;
POSSIBLY_DIVISION = /^\/=?\s/;
HERECOMMENT_ILLEGAL = /\*\//;
LINE_CONTINUER = /^\s*(?:,|\??\.(?![.\d])|::)/;
INVALID_ESCAPE = /((?:^|[^\\])(?:\\\\)*)\\(?:(0[0-7]|[1-7])|(x(?![\da-fA-F]{2}).{0,2})|(u(?![\da-fA-F]{4}).{0,4}))/;
LEADING_BLANK_LINE = /^[^\n\S]*\n/;
TRAILING_BLANK_LINE = /\n[^\n\S]*$/;
TRAILING_SPACES = /\s+$/;
COMPOUND_ASSIGN = ['-=', '+=', '/=', '*=', '%=', '||=', '&&=', '?=', '<<=', '>>=', '>>>=', '&=', '^=', '|=', '**=', '//=', '%%='];
UNARY = ['NEW', 'TYPEOF', 'DELETE', 'DO'];
UNARY_MATH = ['!', '~'];
LOGIC = ['&&', '||', '&', '|', '^'];
SHIFT = ['<<', '>>', '>>>'];
COMPARE = ['==', '!=', '<', '>', '<=', '>='];
MATH = ['*', '/', '%', '//', '%%'];
RELATION = ['IN', 'OF', 'INSTANCEOF'];
BOOL = ['TRUE', 'FALSE'];
CALLABLE = ['IDENTIFIER', ')', ']', '?', '@', 'THIS', 'SUPER'];
INDEXABLE = CALLABLE.concat(['NUMBER', 'STRING', 'STRING_END', 'REGEX', 'REGEX_END', 'BOOL', 'NULL', 'UNDEFINED', '}', '::']);
NOT_REGEX = INDEXABLE.concat(['++', '--']);
LINE_BREAK = ['INDENT', 'OUTDENT', 'TERMINATOR'];
INDENTABLE_CLOSERS = [')', '}', ']'];
}).call(this);
},{"./helpers":199,"./rewriter":204}],201:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var Access, Arr, Assign, Base, Block, Call, Class, Code, CodeFragment, Comment, Existence, Expansion, Extends, For, HEXNUM, IDENTIFIER, IS_REGEX, IS_STRING, If, In, Index, LEVEL_ACCESS, LEVEL_COND, LEVEL_LIST, LEVEL_OP, LEVEL_PAREN, LEVEL_TOP, Literal, NEGATE, NO, NUMBER, Obj, Op, Param, Parens, RESERVED, Range, Return, SIMPLENUM, STRICT_PROSCRIBED, Scope, Slice, Splat, Switch, TAB, THIS, Throw, Try, UTILITIES, Value, While, YES, addLocationDataFn, compact, del, ends, extend, flatten, fragmentsToText, isComplexOrAssignable, isLiteralArguments, isLiteralThis, locationDataToString, merge, multident, parseNum, ref1, ref2, some, starts, throwSyntaxError, unfoldSoak, utility,
extend1 = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty,
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
slice = [].slice;
Error.stackTraceLimit = Infinity;
Scope = require('./scope').Scope;
ref1 = require('./lexer'), RESERVED = ref1.RESERVED, STRICT_PROSCRIBED = ref1.STRICT_PROSCRIBED;
ref2 = require('./helpers'), compact = ref2.compact, flatten = ref2.flatten, extend = ref2.extend, merge = ref2.merge, del = ref2.del, starts = ref2.starts, ends = ref2.ends, some = ref2.some, addLocationDataFn = ref2.addLocationDataFn, locationDataToString = ref2.locationDataToString, throwSyntaxError = ref2.throwSyntaxError;
exports.extend = extend;
exports.addLocationDataFn = addLocationDataFn;
YES = function() {
return true;
};
NO = function() {
return false;
};
THIS = function() {
return this;
};
NEGATE = function() {
this.negated = !this.negated;
return this;
};
exports.CodeFragment = CodeFragment = (function() {
function CodeFragment(parent, code) {
var ref3;
this.code = "" + code;
this.locationData = parent != null ? parent.locationData : void 0;
this.type = (parent != null ? (ref3 = parent.constructor) != null ? ref3.name : void 0 : void 0) || 'unknown';
}
CodeFragment.prototype.toString = function() {
return "" + this.code + (this.locationData ? ": " + locationDataToString(this.locationData) : '');
};
return CodeFragment;
})();
fragmentsToText = function(fragments) {
var fragment;
return ((function() {
var j, len1, results;
results = [];
for (j = 0, len1 = fragments.length; j < len1; j++) {
fragment = fragments[j];
results.push(fragment.code);
}
return results;
})()).join('');
};
exports.Base = Base = (function() {
function Base() {}
Base.prototype.compile = function(o, lvl) {
return fragmentsToText(this.compileToFragments(o, lvl));
};
Base.prototype.compileToFragments = function(o, lvl) {
var node;
o = extend({}, o);
if (lvl) {
o.level = lvl;
}
node = this.unfoldSoak(o) || this;
node.tab = o.indent;
if (o.level === LEVEL_TOP || !node.isStatement(o)) {
return node.compileNode(o);
} else {
return node.compileClosure(o);
}
};
Base.prototype.compileClosure = function(o) {
var args, argumentsNode, func, jumpNode, meth, parts;
if (jumpNode = this.jumps()) {
jumpNode.error('cannot use a pure statement in an expression');
}
o.sharedScope = true;
func = new Code([], Block.wrap([this]));
args = [];
if ((argumentsNode = this.contains(isLiteralArguments)) || this.contains(isLiteralThis)) {
args = [new Literal('this')];
if (argumentsNode) {
meth = 'apply';
args.push(new Literal('arguments'));
} else {
meth = 'call';
}
func = new Value(func, [new Access(new Literal(meth))]);
}
parts = (new Call(func, args)).compileNode(o);
if (func.isGenerator) {
parts.unshift(this.makeCode("(yield* "));
parts.push(this.makeCode(")"));
}
return parts;
};
Base.prototype.cache = function(o, level, isComplex) {
var complex, ref, sub;
complex = isComplex != null ? isComplex(this) : this.isComplex();
if (complex) {
ref = new Literal(o.scope.freeVariable('ref'));
sub = new Assign(ref, this);
if (level) {
return [sub.compileToFragments(o, level), [this.makeCode(ref.value)]];
} else {
return [sub, ref];
}
} else {
ref = level ? this.compileToFragments(o, level) : this;
return [ref, ref];
}
};
Base.prototype.cacheToCodeFragments = function(cacheValues) {
return [fragmentsToText(cacheValues[0]), fragmentsToText(cacheValues[1])];
};
Base.prototype.makeReturn = function(res) {
var me;
me = this.unwrapAll();
if (res) {
return new Call(new Literal(res + ".push"), [me]);
} else {
return new Return(me);
}
};
Base.prototype.contains = function(pred) {
var node;
node = void 0;
this.traverseChildren(false, function(n) {
if (pred(n)) {
node = n;
return false;
}
});
return node;
};
Base.prototype.lastNonComment = function(list) {
var i;
i = list.length;
while (i--) {
if (!(list[i] instanceof Comment)) {
return list[i];
}
}
return null;
};
Base.prototype.toString = function(idt, name) {
var tree;
if (idt == null) {
idt = '';
}
if (name == null) {
name = this.constructor.name;
}
tree = '\n' + idt + name;
if (this.soak) {
tree += '?';
}
this.eachChild(function(node) {
return tree += node.toString(idt + TAB);
});
return tree;
};
Base.prototype.eachChild = function(func) {
var attr, child, j, k, len1, len2, ref3, ref4;
if (!this.children) {
return this;
}
ref3 = this.children;
for (j = 0, len1 = ref3.length; j < len1; j++) {
attr = ref3[j];
if (this[attr]) {
ref4 = flatten([this[attr]]);
for (k = 0, len2 = ref4.length; k < len2; k++) {
child = ref4[k];
if (func(child) === false) {
return this;
}
}
}
}
return this;
};
Base.prototype.traverseChildren = function(crossScope, func) {
return this.eachChild(function(child) {
var recur;
recur = func(child);
if (recur !== false) {
return child.traverseChildren(crossScope, func);
}
});
};
Base.prototype.invert = function() {
return new Op('!', this);
};
Base.prototype.unwrapAll = function() {
var node;
node = this;
while (node !== (node = node.unwrap())) {
continue;
}
return node;
};
Base.prototype.children = [];
Base.prototype.isStatement = NO;
Base.prototype.jumps = NO;
Base.prototype.isComplex = YES;
Base.prototype.isChainable = NO;
Base.prototype.isAssignable = NO;
Base.prototype.unwrap = THIS;
Base.prototype.unfoldSoak = NO;
Base.prototype.assigns = NO;
Base.prototype.updateLocationDataIfMissing = function(locationData) {
if (this.locationData) {
return this;
}
this.locationData = locationData;
return this.eachChild(function(child) {
return child.updateLocationDataIfMissing(locationData);
});
};
Base.prototype.error = function(message) {
return throwSyntaxError(message, this.locationData);
};
Base.prototype.makeCode = function(code) {
return new CodeFragment(this, code);
};
Base.prototype.wrapInBraces = function(fragments) {
return [].concat(this.makeCode('('), fragments, this.makeCode(')'));
};
Base.prototype.joinFragmentArrays = function(fragmentsList, joinStr) {
var answer, fragments, i, j, len1;
answer = [];
for (i = j = 0, len1 = fragmentsList.length; j < len1; i = ++j) {
fragments = fragmentsList[i];
if (i) {
answer.push(this.makeCode(joinStr));
}
answer = answer.concat(fragments);
}
return answer;
};
return Base;
})();
exports.Block = Block = (function(superClass1) {
extend1(Block, superClass1);
function Block(nodes) {
this.expressions = compact(flatten(nodes || []));
}
Block.prototype.children = ['expressions'];
Block.prototype.push = function(node) {
this.expressions.push(node);
return this;
};
Block.prototype.pop = function() {
return this.expressions.pop();
};
Block.prototype.unshift = function(node) {
this.expressions.unshift(node);
return this;
};
Block.prototype.unwrap = function() {
if (this.expressions.length === 1) {
return this.expressions[0];
} else {
return this;
}
};
Block.prototype.isEmpty = function() {
return !this.expressions.length;
};
Block.prototype.isStatement = function(o) {
var exp, j, len1, ref3;
ref3 = this.expressions;
for (j = 0, len1 = ref3.length; j < len1; j++) {
exp = ref3[j];
if (exp.isStatement(o)) {
return true;
}
}
return false;
};
Block.prototype.jumps = function(o) {
var exp, j, jumpNode, len1, ref3;
ref3 = this.expressions;
for (j = 0, len1 = ref3.length; j < len1; j++) {
exp = ref3[j];
if (jumpNode = exp.jumps(o)) {
return jumpNode;
}
}
};
Block.prototype.makeReturn = function(res) {
var expr, len;
len = this.expressions.length;
while (len--) {
expr = this.expressions[len];
if (!(expr instanceof Comment)) {
this.expressions[len] = expr.makeReturn(res);
if (expr instanceof Return && !expr.expression) {
this.expressions.splice(len, 1);
}
break;
}
}
return this;
};
Block.prototype.compileToFragments = function(o, level) {
if (o == null) {
o = {};
}
if (o.scope) {
return Block.__super__.compileToFragments.call(this, o, level);
} else {
return this.compileRoot(o);
}
};
Block.prototype.compileNode = function(o) {
var answer, compiledNodes, fragments, index, j, len1, node, ref3, top;
this.tab = o.indent;
top = o.level === LEVEL_TOP;
compiledNodes = [];
ref3 = this.expressions;
for (index = j = 0, len1 = ref3.length; j < len1; index = ++j) {
node = ref3[index];
node = node.unwrapAll();
node = node.unfoldSoak(o) || node;
if (node instanceof Block) {
compiledNodes.push(node.compileNode(o));
} else if (top) {
node.front = true;
fragments = node.compileToFragments(o);
if (!node.isStatement(o)) {
fragments.unshift(this.makeCode("" + this.tab));
fragments.push(this.makeCode(";"));
}
compiledNodes.push(fragments);
} else {
compiledNodes.push(node.compileToFragments(o, LEVEL_LIST));
}
}
if (top) {
if (this.spaced) {
return [].concat(this.joinFragmentArrays(compiledNodes, '\n\n'), this.makeCode("\n"));
} else {
return this.joinFragmentArrays(compiledNodes, '\n');
}
}
if (compiledNodes.length) {
answer = this.joinFragmentArrays(compiledNodes, ', ');
} else {
answer = [this.makeCode("void 0")];
}
if (compiledNodes.length > 1 && o.level >= LEVEL_LIST) {
return this.wrapInBraces(answer);
} else {
return answer;
}
};
Block.prototype.compileRoot = function(o) {
var exp, fragments, i, j, len1, name, prelude, preludeExps, ref3, ref4, rest;
o.indent = o.bare ? '' : TAB;
o.level = LEVEL_TOP;
this.spaced = true;
o.scope = new Scope(null, this, null, (ref3 = o.referencedVars) != null ? ref3 : []);
ref4 = o.locals || [];
for (j = 0, len1 = ref4.length; j < len1; j++) {
name = ref4[j];
o.scope.parameter(name);
}
prelude = [];
if (!o.bare) {
preludeExps = (function() {
var k, len2, ref5, results;
ref5 = this.expressions;
results = [];
for (i = k = 0, len2 = ref5.length; k < len2; i = ++k) {
exp = ref5[i];
if (!(exp.unwrap() instanceof Comment)) {
break;
}
results.push(exp);
}
return results;
}).call(this);
rest = this.expressions.slice(preludeExps.length);
this.expressions = preludeExps;
if (preludeExps.length) {
prelude = this.compileNode(merge(o, {
indent: ''
}));
prelude.push(this.makeCode("\n"));
}
this.expressions = rest;
}
fragments = this.compileWithDeclarations(o);
if (o.bare) {
return fragments;
}
return [].concat(prelude, this.makeCode("(function() {\n"), fragments, this.makeCode("\n}).call(this);\n"));
};
Block.prototype.compileWithDeclarations = function(o) {
var assigns, declars, exp, fragments, i, j, len1, post, ref3, ref4, ref5, rest, scope, spaced;
fragments = [];
post = [];
ref3 = this.expressions;
for (i = j = 0, len1 = ref3.length; j < len1; i = ++j) {
exp = ref3[i];
exp = exp.unwrap();
if (!(exp instanceof Comment || exp instanceof Literal)) {
break;
}
}
o = merge(o, {
level: LEVEL_TOP
});
if (i) {
rest = this.expressions.splice(i, 9e9);
ref4 = [this.spaced, false], spaced = ref4[0], this.spaced = ref4[1];
ref5 = [this.compileNode(o), spaced], fragments = ref5[0], this.spaced = ref5[1];
this.expressions = rest;
}
post = this.compileNode(o);
scope = o.scope;
if (scope.expressions === this) {
declars = o.scope.hasDeclarations();
assigns = scope.hasAssignments;
if (declars || assigns) {
if (i) {
fragments.push(this.makeCode('\n'));
}
fragments.push(this.makeCode(this.tab + "var "));
if (declars) {
fragments.push(this.makeCode(scope.declaredVariables().join(', ')));
}
if (assigns) {
if (declars) {
fragments.push(this.makeCode(",\n" + (this.tab + TAB)));
}
fragments.push(this.makeCode(scope.assignedVariables().join(",\n" + (this.tab + TAB))));
}
fragments.push(this.makeCode(";\n" + (this.spaced ? '\n' : '')));
} else if (fragments.length && post.length) {
fragments.push(this.makeCode("\n"));
}
}
return fragments.concat(post);
};
Block.wrap = function(nodes) {
if (nodes.length === 1 && nodes[0] instanceof Block) {
return nodes[0];
}
return new Block(nodes);
};
return Block;
})(Base);
exports.Literal = Literal = (function(superClass1) {
extend1(Literal, superClass1);
function Literal(value1) {
this.value = value1;
}
Literal.prototype.makeReturn = function() {
if (this.isStatement()) {
return this;
} else {
return Literal.__super__.makeReturn.apply(this, arguments);
}
};
Literal.prototype.isAssignable = function() {
return IDENTIFIER.test(this.value);
};
Literal.prototype.isStatement = function() {
var ref3;
return (ref3 = this.value) === 'break' || ref3 === 'continue' || ref3 === 'debugger';
};
Literal.prototype.isComplex = NO;
Literal.prototype.assigns = function(name) {
return name === this.value;
};
Literal.prototype.jumps = function(o) {
if (this.value === 'break' && !((o != null ? o.loop : void 0) || (o != null ? o.block : void 0))) {
return this;
}
if (this.value === 'continue' && !(o != null ? o.loop : void 0)) {
return this;
}
};
Literal.prototype.compileNode = function(o) {
var answer, code, ref3;
code = this.value === 'this' ? ((ref3 = o.scope.method) != null ? ref3.bound : void 0) ? o.scope.method.context : this.value : this.value.reserved ? "\"" + this.value + "\"" : this.value;
answer = this.isStatement() ? "" + this.tab + code + ";" : code;
return [this.makeCode(answer)];
};
Literal.prototype.toString = function() {
return ' "' + this.value + '"';
};
return Literal;
})(Base);
exports.Undefined = (function(superClass1) {
extend1(Undefined, superClass1);
function Undefined() {
return Undefined.__super__.constructor.apply(this, arguments);
}
Undefined.prototype.isAssignable = NO;
Undefined.prototype.isComplex = NO;
Undefined.prototype.compileNode = function(o) {
return [this.makeCode(o.level >= LEVEL_ACCESS ? '(void 0)' : 'void 0')];
};
return Undefined;
})(Base);
exports.Null = (function(superClass1) {
extend1(Null, superClass1);
function Null() {
return Null.__super__.constructor.apply(this, arguments);
}
Null.prototype.isAssignable = NO;
Null.prototype.isComplex = NO;
Null.prototype.compileNode = function() {
return [this.makeCode("null")];
};
return Null;
})(Base);
exports.Bool = (function(superClass1) {
extend1(Bool, superClass1);
Bool.prototype.isAssignable = NO;
Bool.prototype.isComplex = NO;
Bool.prototype.compileNode = function() {
return [this.makeCode(this.val)];
};
function Bool(val1) {
this.val = val1;
}
return Bool;
})(Base);
exports.Return = Return = (function(superClass1) {
extend1(Return, superClass1);
function Return(expression) {
this.expression = expression;
}
Return.prototype.children = ['expression'];
Return.prototype.isStatement = YES;
Return.prototype.makeReturn = THIS;
Return.prototype.jumps = THIS;
Return.prototype.compileToFragments = function(o, level) {
var expr, ref3;
expr = (ref3 = this.expression) != null ? ref3.makeReturn() : void 0;
if (expr && !(expr instanceof Return)) {
return expr.compileToFragments(o, level);
} else {
return Return.__super__.compileToFragments.call(this, o, level);
}
};
Return.prototype.compileNode = function(o) {
var answer, exprIsYieldReturn, ref3;
answer = [];
exprIsYieldReturn = (ref3 = this.expression) != null ? typeof ref3.isYieldReturn === "function" ? ref3.isYieldReturn() : void 0 : void 0;
if (!exprIsYieldReturn) {
answer.push(this.makeCode(this.tab + ("return" + (this.expression ? " " : ""))));
}
if (this.expression) {
answer = answer.concat(this.expression.compileToFragments(o, LEVEL_PAREN));
}
if (!exprIsYieldReturn) {
answer.push(this.makeCode(";"));
}
return answer;
};
return Return;
})(Base);
exports.Value = Value = (function(superClass1) {
extend1(Value, superClass1);
function Value(base, props, tag) {
if (!props && base instanceof Value) {
return base;
}
this.base = base;
this.properties = props || [];
if (tag) {
this[tag] = true;
}
return this;
}
Value.prototype.children = ['base', 'properties'];
Value.prototype.add = function(props) {
this.properties = this.properties.concat(props);
return this;
};
Value.prototype.hasProperties = function() {
return !!this.properties.length;
};
Value.prototype.bareLiteral = function(type) {
return !this.properties.length && this.base instanceof type;
};
Value.prototype.isArray = function() {
return this.bareLiteral(Arr);
};
Value.prototype.isRange = function() {
return this.bareLiteral(Range);
};
Value.prototype.isComplex = function() {
return this.hasProperties() || this.base.isComplex();
};
Value.prototype.isAssignable = function() {
return this.hasProperties() || this.base.isAssignable();
};
Value.prototype.isSimpleNumber = function() {
return this.bareLiteral(Literal) && SIMPLENUM.test(this.base.value);
};
Value.prototype.isString = function() {
return this.bareLiteral(Literal) && IS_STRING.test(this.base.value);
};
Value.prototype.isRegex = function() {
return this.bareLiteral(Literal) && IS_REGEX.test(this.base.value);
};
Value.prototype.isAtomic = function() {
var j, len1, node, ref3;
ref3 = this.properties.concat(this.base);
for (j = 0, len1 = ref3.length; j < len1; j++) {
node = ref3[j];
if (node.soak || node instanceof Call) {
return false;
}
}
return true;
};
Value.prototype.isNotCallable = function() {
return this.isSimpleNumber() || this.isString() || this.isRegex() || this.isArray() || this.isRange() || this.isSplice() || this.isObject();
};
Value.prototype.isStatement = function(o) {
return !this.properties.length && this.base.isStatement(o);
};
Value.prototype.assigns = function(name) {
return !this.properties.length && this.base.assigns(name);
};
Value.prototype.jumps = function(o) {
return !this.properties.length && this.base.jumps(o);
};
Value.prototype.isObject = function(onlyGenerated) {
if (this.properties.length) {
return false;
}
return (this.base instanceof Obj) && (!onlyGenerated || this.base.generated);
};
Value.prototype.isSplice = function() {
var lastProp, ref3;
ref3 = this.properties, lastProp = ref3[ref3.length - 1];
return lastProp instanceof Slice;
};
Value.prototype.looksStatic = function(className) {
var ref3;
return this.base.value === className && this.properties.length === 1 && ((ref3 = this.properties[0].name) != null ? ref3.value : void 0) !== 'prototype';
};
Value.prototype.unwrap = function() {
if (this.properties.length) {
return this;
} else {
return this.base;
}
};
Value.prototype.cacheReference = function(o) {
var base, bref, name, nref, ref3;
ref3 = this.properties, name = ref3[ref3.length - 1];
if (this.properties.length < 2 && !this.base.isComplex() && !(name != null ? name.isComplex() : void 0)) {
return [this, this];
}
base = new Value(this.base, this.properties.slice(0, -1));
if (base.isComplex()) {
bref = new Literal(o.scope.freeVariable('base'));
base = new Value(new Parens(new Assign(bref, base)));
}
if (!name) {
return [base, bref];
}
if (name.isComplex()) {
nref = new Literal(o.scope.freeVariable('name'));
name = new Index(new Assign(nref, name.index));
nref = new Index(nref);
}
return [base.add(name), new Value(bref || base.base, [nref || name])];
};
Value.prototype.compileNode = function(o) {
var fragments, j, len1, prop, props;
this.base.front = this.front;
props = this.properties;
fragments = this.base.compileToFragments(o, (props.length ? LEVEL_ACCESS : null));
if ((this.base instanceof Parens || props.length) && SIMPLENUM.test(fragmentsToText(fragments))) {
fragments.push(this.makeCode('.'));
}
for (j = 0, len1 = props.length; j < len1; j++) {
prop = props[j];
fragments.push.apply(fragments, prop.compileToFragments(o));
}
return fragments;
};
Value.prototype.unfoldSoak = function(o) {
return this.unfoldedSoak != null ? this.unfoldedSoak : this.unfoldedSoak = (function(_this) {
return function() {
var fst, i, ifn, j, len1, prop, ref, ref3, ref4, snd;
if (ifn = _this.base.unfoldSoak(o)) {
(ref3 = ifn.body.properties).push.apply(ref3, _this.properties);
return ifn;
}
ref4 = _this.properties;
for (i = j = 0, len1 = ref4.length; j < len1; i = ++j) {
prop = ref4[i];
if (!prop.soak) {
continue;
}
prop.soak = false;
fst = new Value(_this.base, _this.properties.slice(0, i));
snd = new Value(_this.base, _this.properties.slice(i));
if (fst.isComplex()) {
ref = new Literal(o.scope.freeVariable('ref'));
fst = new Parens(new Assign(ref, fst));
snd.base = ref;
}
return new If(new Existence(fst), snd, {
soak: true
});
}
return false;
};
})(this)();
};
return Value;
})(Base);
exports.Comment = Comment = (function(superClass1) {
extend1(Comment, superClass1);
function Comment(comment1) {
this.comment = comment1;
}
Comment.prototype.isStatement = YES;
Comment.prototype.makeReturn = THIS;
Comment.prototype.compileNode = function(o, level) {
var code, comment;
comment = this.comment.replace(/^(\s*)# /gm, "$1 * ");
code = "/*" + (multident(comment, this.tab)) + (indexOf.call(comment, '\n') >= 0 ? "\n" + this.tab : '') + " */";
if ((level || o.level) === LEVEL_TOP) {
code = o.indent + code;
}
return [this.makeCode("\n"), this.makeCode(code)];
};
return Comment;
})(Base);
exports.Call = Call = (function(superClass1) {
extend1(Call, superClass1);
function Call(variable, args1, soak) {
this.args = args1 != null ? args1 : [];
this.soak = soak;
this.isNew = false;
this.isSuper = variable === 'super';
this.variable = this.isSuper ? null : variable;
if (variable instanceof Value && variable.isNotCallable()) {
variable.error("literal is not a function");
}
}
Call.prototype.children = ['variable', 'args'];
Call.prototype.newInstance = function() {
var base, ref3;
base = ((ref3 = this.variable) != null ? ref3.base : void 0) || this.variable;
if (base instanceof Call && !base.isNew) {
base.newInstance();
} else {
this.isNew = true;
}
return this;
};
Call.prototype.superReference = function(o) {
var accesses, base, bref, klass, method, name, nref, variable;
method = o.scope.namedMethod();
if (method != null ? method.klass : void 0) {
klass = method.klass, name = method.name, variable = method.variable;
if (klass.isComplex()) {
bref = new Literal(o.scope.parent.freeVariable('base'));
base = new Value(new Parens(new Assign(bref, klass)));
variable.base = base;
variable.properties.splice(0, klass.properties.length);
}
if (name.isComplex() || (name instanceof Index && name.index.isAssignable())) {
nref = new Literal(o.scope.parent.freeVariable('name'));
name = new Index(new Assign(nref, name.index));
variable.properties.pop();
variable.properties.push(name);
}
accesses = [new Access(new Literal('__super__'))];
if (method["static"]) {
accesses.push(new Access(new Literal('constructor')));
}
accesses.push(nref != null ? new Index(nref) : name);
return (new Value(bref != null ? bref : klass, accesses)).compile(o);
} else if (method != null ? method.ctor : void 0) {
return method.name + ".__super__.constructor";
} else {
return this.error('cannot call super outside of an instance method.');
}
};
Call.prototype.superThis = function(o) {
var method;
method = o.scope.method;
return (method && !method.klass && method.context) || "this";
};
Call.prototype.unfoldSoak = function(o) {
var call, ifn, j, left, len1, list, ref3, ref4, rite;
if (this.soak) {
if (this.variable) {
if (ifn = unfoldSoak(o, this, 'variable')) {
return ifn;
}
ref3 = new Value(this.variable).cacheReference(o), left = ref3[0], rite = ref3[1];
} else {
left = new Literal(this.superReference(o));
rite = new Value(left);
}
rite = new Call(rite, this.args);
rite.isNew = this.isNew;
left = new Literal("typeof " + (left.compile(o)) + " === \"function\"");
return new If(left, new Value(rite), {
soak: true
});
}
call = this;
list = [];
while (true) {
if (call.variable instanceof Call) {
list.push(call);
call = call.variable;
continue;
}
if (!(call.variable instanceof Value)) {
break;
}
list.push(call);
if (!((call = call.variable.base) instanceof Call)) {
break;
}
}
ref4 = list.reverse();
for (j = 0, len1 = ref4.length; j < len1; j++) {
call = ref4[j];
if (ifn) {
if (call.variable instanceof Call) {
call.variable = ifn;
} else {
call.variable.base = ifn;
}
}
ifn = unfoldSoak(o, call, 'variable');
}
return ifn;
};
Call.prototype.compileNode = function(o) {
var arg, argIndex, compiledArgs, compiledArray, fragments, j, len1, preface, ref3, ref4;
if ((ref3 = this.variable) != null) {
ref3.front = this.front;
}
compiledArray = Splat.compileSplattedArray(o, this.args, true);
if (compiledArray.length) {
return this.compileSplat(o, compiledArray);
}
compiledArgs = [];
ref4 = this.args;
for (argIndex = j = 0, len1 = ref4.length; j < len1; argIndex = ++j) {
arg = ref4[argIndex];
if (argIndex) {
compiledArgs.push(this.makeCode(", "));
}
compiledArgs.push.apply(compiledArgs, arg.compileToFragments(o, LEVEL_LIST));
}
fragments = [];
if (this.isSuper) {
preface = this.superReference(o) + (".call(" + (this.superThis(o)));
if (compiledArgs.length) {
preface += ", ";
}
fragments.push(this.makeCode(preface));
} else {
if (this.isNew) {
fragments.push(this.makeCode('new '));
}
fragments.push.apply(fragments, this.variable.compileToFragments(o, LEVEL_ACCESS));
fragments.push(this.makeCode("("));
}
fragments.push.apply(fragments, compiledArgs);
fragments.push(this.makeCode(")"));
return fragments;
};
Call.prototype.compileSplat = function(o, splatArgs) {
var answer, base, fun, idt, name, ref;
if (this.isSuper) {
return [].concat(this.makeCode((this.superReference(o)) + ".apply(" + (this.superThis(o)) + ", "), splatArgs, this.makeCode(")"));
}
if (this.isNew) {
idt = this.tab + TAB;
return [].concat(this.makeCode("(function(func, args, ctor) {\n" + idt + "ctor.prototype = func.prototype;\n" + idt + "var child = new ctor, result = func.apply(child, args);\n" + idt + "return Object(result) === result ? result : child;\n" + this.tab + "})("), this.variable.compileToFragments(o, LEVEL_LIST), this.makeCode(", "), splatArgs, this.makeCode(", function(){})"));
}
answer = [];
base = new Value(this.variable);
if ((name = base.properties.pop()) && base.isComplex()) {
ref = o.scope.freeVariable('ref');
answer = answer.concat(this.makeCode("(" + ref + " = "), base.compileToFragments(o, LEVEL_LIST), this.makeCode(")"), name.compileToFragments(o));
} else {
fun = base.compileToFragments(o, LEVEL_ACCESS);
if (SIMPLENUM.test(fragmentsToText(fun))) {
fun = this.wrapInBraces(fun);
}
if (name) {
ref = fragmentsToText(fun);
fun.push.apply(fun, name.compileToFragments(o));
} else {
ref = 'null';
}
answer = answer.concat(fun);
}
return answer = answer.concat(this.makeCode(".apply(" + ref + ", "), splatArgs, this.makeCode(")"));
};
return Call;
})(Base);
exports.Extends = Extends = (function(superClass1) {
extend1(Extends, superClass1);
function Extends(child1, parent1) {
this.child = child1;
this.parent = parent1;
}
Extends.prototype.children = ['child', 'parent'];
Extends.prototype.compileToFragments = function(o) {
return new Call(new Value(new Literal(utility('extend', o))), [this.child, this.parent]).compileToFragments(o);
};
return Extends;
})(Base);
exports.Access = Access = (function(superClass1) {
extend1(Access, superClass1);
function Access(name1, tag) {
this.name = name1;
this.name.asKey = true;
this.soak = tag === 'soak';
}
Access.prototype.children = ['name'];
Access.prototype.compileToFragments = function(o) {
var name;
name = this.name.compileToFragments(o);
if (IDENTIFIER.test(fragmentsToText(name))) {
name.unshift(this.makeCode("."));
} else {
name.unshift(this.makeCode("["));
name.push(this.makeCode("]"));
}
return name;
};
Access.prototype.isComplex = NO;
return Access;
})(Base);
exports.Index = Index = (function(superClass1) {
extend1(Index, superClass1);
function Index(index1) {
this.index = index1;
}
Index.prototype.children = ['index'];
Index.prototype.compileToFragments = function(o) {
return [].concat(this.makeCode("["), this.index.compileToFragments(o, LEVEL_PAREN), this.makeCode("]"));
};
Index.prototype.isComplex = function() {
return this.index.isComplex();
};
return Index;
})(Base);
exports.Range = Range = (function(superClass1) {
extend1(Range, superClass1);
Range.prototype.children = ['from', 'to'];
function Range(from1, to1, tag) {
this.from = from1;
this.to = to1;
this.exclusive = tag === 'exclusive';
this.equals = this.exclusive ? '' : '=';
}
Range.prototype.compileVariables = function(o) {
var isComplex, ref3, ref4, ref5, ref6, step;
o = merge(o, {
top: true
});
isComplex = del(o, 'isComplex');
ref3 = this.cacheToCodeFragments(this.from.cache(o, LEVEL_LIST, isComplex)), this.fromC = ref3[0], this.fromVar = ref3[1];
ref4 = this.cacheToCodeFragments(this.to.cache(o, LEVEL_LIST, isComplex)), this.toC = ref4[0], this.toVar = ref4[1];
if (step = del(o, 'step')) {
ref5 = this.cacheToCodeFragments(step.cache(o, LEVEL_LIST, isComplex)), this.step = ref5[0], this.stepVar = ref5[1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment