_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q22200
|
train
|
function(src, dest) {
var contents,
srcExists = fs.existsSync(src),
destExists = fs.existsSync(dest),
stats = srcExists && fs.statSync(src),
isDirectory = srcExists && stats.isDirectory();
if (srcExists) {
if (isDirectory) {
if (!destExists) {
fs.mkdirSync(dest);
}
fs.readdirSync(src).forEach(function(childItemName) {
copyRecursiveSync(path.join(src, childItemName),
path.join(dest, childItemName));
});
} else {
contents = fs.readFileSync(src);
fs.writeFileSync(dest, contents);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22201
|
train
|
function () {
var spaceCharCode = " ".charCodeAt(0);
var glyph = this.glyphs[spaceCharCode];
if (!glyph) {
glyph = new Glyph();
glyph.id = spaceCharCode;
glyph.xadvance = this._getFirstGlyph().xadvance;
this.glyphs[spaceCharCode] = glyph;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22202
|
train
|
function (response) {
// the overlap vector
var overlap = response.overlapV;
// FIXME: Respond proportionally to object mass
// Move out of the other object shape
this.ancestor.pos.sub(overlap);
// adjust velocity
if (overlap.x !== 0) {
this.vel.x = ~~(0.5 + this.vel.x - overlap.x) || 0;
if (this.bounce > 0) {
this.vel.x *= -this.bounce;
}
}
if (overlap.y !== 0) {
this.vel.y = ~~(0.5 + this.vel.y - overlap.y) || 0;
if (this.bounce > 0) {
this.vel.y *= -this.bounce;
}
// cancel the falling an jumping flags if necessary
var dir = Math.sign(this.gravity.y) || 1;
this.falling = overlap.y >= dir;
this.jumping = overlap.y <= -dir;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22203
|
train
|
function (vel) {
var fx = this.friction.x * me.timer.tick,
nx = vel.x + fx,
x = vel.x - fx,
fy = this.friction.y * me.timer.tick,
ny = vel.y + fy,
y = vel.y - fy;
vel.x = (
(nx < 0) ? nx :
( x > 0) ? x : 0
);
vel.y = (
(ny < 0) ? ny :
( y > 0) ? y : 0
);
}
|
javascript
|
{
"resource": ""
}
|
|
q22204
|
train
|
function (e) {
if (this.dragging === false) {
this.dragging = true;
this.grabOffset.set(e.gameX, e.gameY);
this.grabOffset.sub(this.pos);
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22205
|
train
|
function (e) {
if (this.dragging === true) {
this.pos.set(e.gameX, e.gameY, this.pos.z); //TODO : z ?
this.pos.sub(this.grabOffset);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22206
|
train
|
function (r, g, b, alpha) {
// Private initialization: copy Color value directly
if (r instanceof me.Color) {
this.glArray.set(r.glArray);
return r;
}
this.r = r;
this.g = g;
this.b = b;
this.alpha = alpha;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22207
|
train
|
function (color) {
if (color instanceof me.Color) {
this.glArray.set(color.glArray);
return this;
}
return this.parseCSS(color);
}
|
javascript
|
{
"resource": ""
}
|
|
q22208
|
train
|
function (color) {
this.glArray[0] = me.Math.clamp(this.glArray[0] + color.glArray[0], 0, 1);
this.glArray[1] = me.Math.clamp(this.glArray[1] + color.glArray[1], 0, 1);
this.glArray[2] = me.Math.clamp(this.glArray[2] + color.glArray[2], 0, 1);
this.glArray[3] = (this.glArray[3] + color.glArray[3]) / 2;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22209
|
train
|
function (scale) {
scale = me.Math.clamp(scale, 0, 1);
this.glArray[0] *= scale;
this.glArray[1] *= scale;
this.glArray[2] *= scale;
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22210
|
train
|
function (cssColor) {
// TODO : Memoize this function by caching its input
if (cssToRGB.has(cssColor)) {
return this.setColor.apply(this, cssToRGB.get(cssColor));
}
return this.parseRGB(cssColor);
}
|
javascript
|
{
"resource": ""
}
|
|
q22211
|
train
|
function (rgbColor) {
// TODO : Memoize this function by caching its input
var match = rgbaRx.exec(rgbColor);
if (match) {
return this.setColor(+match[1], +match[2], +match[3], +match[5]);
}
return this.parseHex(rgbColor);
}
|
javascript
|
{
"resource": ""
}
|
|
q22212
|
readLayer
|
train
|
function readLayer(map, data, z) {
var layer = new me.TMXLayer(data, map.tilewidth, map.tileheight, map.orientation, map.tilesets, z);
// set a renderer
layer.setRenderer(map.getRenderer());
return layer;
}
|
javascript
|
{
"resource": ""
}
|
q22213
|
readImageLayer
|
train
|
function readImageLayer(map, data, z) {
// Normalize properties
me.TMXUtils.applyTMXProperties(data.properties, data);
// create the layer
var imageLayer = me.pool.pull("me.ImageLayer",
// x/y is deprecated since 0.15 and replace by offsetx/y
+data.offsetx || +data.x || 0,
+data.offsety || +data.y || 0,
Object.assign({
name: data.name,
image: data.image,
z: z
}, data.properties)
);
// set some additional flags
var visible = typeof(data.visible) !== "undefined" ? data.visible : true;
imageLayer.setOpacity(visible ? +data.opacity : 0);
return imageLayer;
}
|
javascript
|
{
"resource": ""
}
|
q22214
|
train
|
function (data) {
if (this.initialized === true) {
return;
}
// to automatically increment z index
var zOrder = 0;
var self = this;
// Tileset information
if (!this.tilesets) {
// make sure we have a TilesetGroup Object
this.tilesets = new me.TMXTilesetGroup();
}
// parse all tileset objects
if (typeof (data.tilesets) !== "undefined") {
var tilesets = data.tilesets;
tilesets.forEach(function (tileset) {
// add the new tileset
self.tilesets.add(readTileset(tileset));
});
}
// check if a user-defined background color is defined
if (this.backgroundcolor) {
this.layers.push(
me.pool.pull("me.ColorLayer",
"background_color",
this.backgroundcolor,
zOrder++
)
);
}
// check if a background image is defined
if (this.background_image) {
// add a new image layer
this.layers.push(
me.pool.pull("me.ImageLayer",
0, 0, {
name : "background_image",
image : this.background_image,
z : zOrder++
}
));
}
data.layers.forEach(function (layer) {
switch (layer.type) {
case "imagelayer":
self.layers.push(readImageLayer(self, layer, zOrder++));
break;
case "tilelayer":
self.layers.push(readLayer(self, layer, zOrder++));
break;
// get the object groups information
case "objectgroup":
self.objectGroups.push(readObjectGroup(self, layer, zOrder++));
break;
// get the object groups information
case "group":
self.objectGroups.push(readObjectGroup(self, layer, zOrder++));
break;
default:
break;
}
});
this.initialized = true;
}
|
javascript
|
{
"resource": ""
}
|
|
q22215
|
train
|
function (container, flatten) {
var _sort = container.autoSort;
var _depth = container.autoDepth;
// disable auto-sort and auto-depth
container.autoSort = false;
container.autoDepth = false;
// add all layers instances
this.getLayers().forEach(function (layer) {
container.addChild(layer);
});
// add all Object instances
this.getObjects(flatten).forEach(function (object) {
container.addChild(object);
});
// set back auto-sort and auto-depth
container.autoSort = _sort;
container.autoDepth = _depth;
// force a sort
container.sort(true);
}
|
javascript
|
{
"resource": ""
}
|
|
q22216
|
train
|
function (data) {
var atlas = {};
var image = data.image;
var spacing = data.spacing || 0;
var margin = data.margin || 0;
var width = image.width;
var height = image.height;
// calculate the sprite count (line, col)
var spritecount = me.pool.pull("me.Vector2d",
~~((width - margin + spacing) / (data.framewidth + spacing)),
~~((height - margin + spacing) / (data.frameheight + spacing))
);
// verifying the texture size
if ((width % (data.framewidth + spacing)) !== 0 ||
(height % (data.frameheight + spacing)) !== 0) {
// "truncate size"
width = spritecount.x * (data.framewidth + spacing);
height = spritecount.y * (data.frameheight + spacing);
// warning message
console.warn(
"Spritesheet Texture for image: " + image.src +
" is not divisible by " + (data.framewidth + spacing) +
"x" + (data.frameheight + spacing) +
", truncating effective size to " + width + "x" + height
);
}
// build the local atlas
for (var frame = 0, count = spritecount.x * spritecount.y; frame < count; frame++) {
var name = "" + frame;
atlas[name] = {
name : name,
texture : "default", // the source texture
offset : new me.Vector2d(
margin + (spacing + data.framewidth) * (frame % spritecount.x),
margin + (spacing + data.frameheight) * ~~(frame / spritecount.x)
),
anchorPoint : (data.anchorPoint || null),
trimmed : false,
width : data.framewidth,
height : data.frameheight,
angle : 0
};
this.addUvsMap(atlas, name, width, height);
}
me.pool.push(spritecount);
return atlas;
}
|
javascript
|
{
"resource": ""
}
|
|
q22217
|
train
|
function (name) {
// Get the source texture region
var region = this.getRegion(name);
if (typeof(region) === "undefined") {
// TODO: Require proper atlas regions instead of caching arbitrary region keys
var keys = name.split(","),
sx = +keys[0],
sy = +keys[1],
sw = +keys[2],
sh = +keys[3];
region = this.addQuadRegion(name, sx, sy, sw, sh);
}
return region.uvs;
}
|
javascript
|
{
"resource": ""
}
|
|
q22218
|
train
|
function (name, settings) {
// instantiate a new sprite object
return me.pool.pull(
"me.Sprite",
0, 0,
Object.assign({
image: this,
region : name
}, settings || {})
);
}
|
javascript
|
{
"resource": ""
}
|
|
q22219
|
_renderFrame
|
train
|
function _renderFrame(time) {
var stage = _stages[_state].stage;
// update all game objects
me.game.update(time, stage);
// render all game objects
me.game.draw(stage);
// schedule the next frame update
if (_animFrameId !== -1) {
_animFrameId = window.requestAnimationFrame(_renderFrame);
}
}
|
javascript
|
{
"resource": ""
}
|
q22220
|
_switchState
|
train
|
function _switchState(state) {
// clear previous interval if any
_stopRunLoop();
// call the stage destroy method
if (_stages[_state]) {
// just notify the object
_stages[_state].stage.destroy();
}
if (_stages[state]) {
// set the global variable
_state = state;
// call the reset function with _extraArgs as arguments
_stages[_state].stage.reset.apply(_stages[_state].stage, _extraArgs);
// and start the main loop of the
// new requested state
_startRunLoop();
// execute callback if defined
if (_onSwitchComplete) {
_onSwitchComplete();
}
// force repaint
me.game.repaint();
}
}
|
javascript
|
{
"resource": ""
}
|
q22221
|
train
|
function (renderer, rect) {
var color = renderer.getColor();
var vpos = me.game.viewport.pos;
renderer.setColor(this.color);
renderer.fillRect(
rect.left - vpos.x, rect.top - vpos.y,
rect.width, rect.height
);
renderer.setColor(color);
}
|
javascript
|
{
"resource": ""
}
|
|
q22222
|
flattenPointsOn
|
train
|
function flattenPointsOn(points, normal, result) {
var min = Number.MAX_VALUE;
var max = -Number.MAX_VALUE;
var len = points.length;
for (var i = 0; i < len; i++) {
// The magnitude of the projection of the point onto the normal
var dot = points[i].dotProduct(normal);
if (dot < min) { min = dot; }
if (dot > max) { max = dot; }
}
result[0] = min;
result[1] = max;
}
|
javascript
|
{
"resource": ""
}
|
q22223
|
checkLoadStatus
|
train
|
function checkLoadStatus(onload) {
if (loadCount === resourceCount) {
// wait 1/2s and execute callback (cheap workaround to ensure everything is loaded)
if (onload || api.onload) {
// make sure we clear the timer
clearTimeout(timerId);
// trigger the onload callback
// we call either the supplied callback (which takes precedence) or the global one
var callback = onload || api.onload;
setTimeout(function () {
callback();
me.event.publish(me.event.LOADER_COMPLETE);
}, 300);
}
else {
throw new Error("no load callback defined");
}
}
else {
timerId = setTimeout(function() {
checkLoadStatus(onload);
}, 100);
}
}
|
javascript
|
{
"resource": ""
}
|
q22224
|
preloadFontFace
|
train
|
function preloadFontFace(data, onload, onerror) {
var font = new FontFace(data.name, data.src);
// loading promise
font.load().then(function() {
// apply the font after the font has finished downloading
document.fonts.add(font);
document.body.style.fontFamily = data.name;
// onloaded callback
onload();
}, function (e) {
// rejected
onerror(data.name);
});
}
|
javascript
|
{
"resource": ""
}
|
q22225
|
preloadJSON
|
train
|
function preloadJSON(data, onload, onerror) {
var xmlhttp = new XMLHttpRequest();
if (xmlhttp.overrideMimeType) {
xmlhttp.overrideMimeType("application/json");
}
xmlhttp.open("GET", data.src + api.nocache, true);
xmlhttp.withCredentials = me.loader.withCredentials;
// set the callbacks
xmlhttp.ontimeout = onerror;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
// status = 0 when file protocol is used, or cross-domain origin,
// (With Chrome use "--allow-file-access-from-files --disable-web-security")
if ((xmlhttp.status === 200) || ((xmlhttp.status === 0) && xmlhttp.responseText)) {
// get the Texture Packer Atlas content
jsonList[data.name] = JSON.parse(xmlhttp.responseText);
// fire the callback
onload();
}
else {
onerror(data.name);
}
}
};
// send the request
xmlhttp.send();
}
|
javascript
|
{
"resource": ""
}
|
q22226
|
train
|
function (x, y, points) {
this.pos.set(x, y);
if (!Array.isArray(points)) {
return this;
}
// convert given points to me.Vector2d if required
if (!(points[0] instanceof me.Vector2d)) {
var _points = this.points = [];
points.forEach(function (point) {
_points.push(new me.Vector2d(point.x, point.y));
});
} else {
// array of me.Vector2d
this.points = points;
}
this.recalc();
this.updateBounds();
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22227
|
train
|
function (x, y) {
y = typeof (y) !== "undefined" ? y : x;
var points = this.points;
var len = points.length;
for (var i = 0; i < len; i++) {
points[i].scale(x, y);
}
this.recalc();
this.updateBounds();
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q22228
|
train
|
function (body) {
// update the entity bounds to match with the body bounds
this.getBounds().resize(body.width, body.height);
// update the bounds pos
this.updateBoundsPos(this.pos.x, this.pos.y);
}
|
javascript
|
{
"resource": ""
}
|
|
q22229
|
train
|
function () {
return (isFinite(this.pos.x) && isFinite(this.pos.y) && isFinite(this._width) && isFinite(this._height));
}
|
javascript
|
{
"resource": ""
}
|
|
q22230
|
loadTMXLevel
|
train
|
function loadTMXLevel(levelId, container, flatten, setViewportBounds) {
var level = levels[levelId];
// disable auto-sort for the given container
var autoSort = container.autoSort;
container.autoSort = false;
var levelBounds = level.getBounds();
if (setViewportBounds) {
// update the viewport bounds
me.game.viewport.setBounds(
0, 0,
Math.max(levelBounds.width, me.game.viewport.width),
Math.max(levelBounds.height, me.game.viewport.height)
);
}
// reset the GUID generator
// and pass the level id as parameter
me.utils.resetGUID(levelId, level.nextobjectid);
// Tiled use 0,0 anchor coordinates
container.anchorPoint.set(0, 0);
// add all level elements to the target container
level.addTo(container, flatten);
// sort everything (recursively)
container.sort(true);
container.autoSort = autoSort;
container.resize(levelBounds.width, levelBounds.height);
function resize_container() {
// center the map if smaller than the current viewport
container.pos.set(
Math.max(0, ~~((me.game.viewport.width - levelBounds.width) / 2)),
Math.max(0, ~~((me.game.viewport.height - levelBounds.height) / 2)),
0
);
}
if (setViewportBounds) {
resize_container();
// Replace the resize handler
if (onresize_handler) {
me.event.unsubscribe(onresize_handler);
}
onresize_handler = me.event.subscribe(me.event.VIEWPORT_ONRESIZE, resize_container);
}
}
|
javascript
|
{
"resource": ""
}
|
q22231
|
train
|
function (x, y) {
// translate the given coordinates,
// rather than creating temp translated vectors
x -= this.pos.x; // Cx
y -= this.pos.y; // Cy
var start = this.points[0]; // Ax/Ay
var end = this.points[1]; // Bx/By
//(Cy - Ay) * (Bx - Ax) = (By - Ay) * (Cx - Ax)
return (y - start.y) * (end.x - start.x) === (end.y - start.y) * (x - start.x);
}
|
javascript
|
{
"resource": ""
}
|
|
q22232
|
train
|
function(context, font, stroke) {
context.font = font.font;
context.fillStyle = font.fillStyle.toRGBA();
if (stroke === true) {
context.strokeStyle = font.strokeStyle.toRGBA();
context.lineWidth = font.lineWidth;
}
context.textAlign = font.textAlign;
context.textBaseline = font.textBaseline;
}
|
javascript
|
{
"resource": ""
}
|
|
q22233
|
train
|
function (renderer, text, x, y, stroke) {
// "hacky patch" for backward compatibilty
if (typeof this.ancestor === "undefined") {
// update text cache
this.setText(text);
// update position if changed
if (this.pos.x !== x || this.pos.y !== y) {
this.pos.x = x;
this.pos.y = y;
this.isDirty = true;
}
// force update bounds
this.update(0);
// save the previous context
renderer.save();
// apply the defined alpha value
renderer.setGlobalAlpha(renderer.globalAlpha() * this.getOpacity());
} else {
// added directly to an object container
x = this.pos.x;
y = this.pos.y;
}
if (renderer.settings.subPixel === false) {
// clamp to pixel grid if required
x = ~~x;
y = ~~y;
}
// draw the text
renderer.drawFont(this._drawFont(renderer.getFontContext(), this._text, x, y, stroke || false));
// for backward compatibilty
if (typeof this.ancestor === "undefined") {
// restore previous context
renderer.restore();
}
// clear the dirty flag
this.isDirty = false;
}
|
javascript
|
{
"resource": ""
}
|
|
q22234
|
train
|
function (event) {
// Check if left mouse button is pressed
if (event.button === 0 && this.isClickable) {
this.updated = true;
this.released = false;
if (this.isHoldable) {
if (this.holdTimeout !== null) {
me.timer.clearTimeout(this.holdTimeout);
}
this.holdTimeout = me.timer.setTimeout(this.hold.bind(this), this.holdThreshold, false);
this.released = false;
}
return this.onClick.call(this, event);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22235
|
train
|
function (event) {
if (this.released === false) {
this.released = true;
me.timer.clearTimeout(this.holdTimeout);
return this.onRelease.call(this, event);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22236
|
train
|
function (count) {
for (var i = 0; i < ~~count; i++) {
// Add particle to the container
var particle = me.pool.pull("me.Particle", this);
this.container.addChild(particle);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22237
|
apply_methods
|
train
|
function apply_methods(Class, methods, descriptor) {
Object.keys(descriptor).forEach(function (method) {
methods[method] = descriptor[method];
if (typeof(descriptor[method]) !== "function") {
throw new TypeError(
"extend: Method `" + method + "` is not a function"
);
}
Object.defineProperty(Class.prototype, method, {
"configurable" : true,
"value" : descriptor[method]
});
});
}
|
javascript
|
{
"resource": ""
}
|
q22238
|
angle
|
train
|
function angle(v) {
return Math.acos(me.Math.clamp(this.dotProduct(v) / (this.length() * v.length()), -1, 1));
}
|
javascript
|
{
"resource": ""
}
|
q22239
|
floorSelf
|
train
|
function floorSelf() {
return this._set(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
}
|
javascript
|
{
"resource": ""
}
|
q22240
|
ceil
|
train
|
function ceil() {
return new me.Vector3d(Math.ceil(this.x), Math.ceil(this.y), Math.ceil(this.z));
}
|
javascript
|
{
"resource": ""
}
|
q22241
|
ceilSelf
|
train
|
function ceilSelf() {
return this._set(Math.ceil(this.x), Math.ceil(this.y), Math.ceil(this.z));
}
|
javascript
|
{
"resource": ""
}
|
q22242
|
setMuted
|
train
|
function setMuted(x, y, z) {
this._x = x;
this._y = y;
this._z = z;
return this;
}
|
javascript
|
{
"resource": ""
}
|
q22243
|
add
|
train
|
function add(v) {
return this._set(this._x + v.x, this._y + v.y, this._z + (v.z || 0));
}
|
javascript
|
{
"resource": ""
}
|
q22244
|
equals
|
train
|
function equals(v) {
return this._x === v.x && this._y === v.y && this._z === (v.z || this._z);
}
|
javascript
|
{
"resource": ""
}
|
q22245
|
dotProduct
|
train
|
function dotProduct(v) {
return this._x * v.x + this._y * v.y + this._z * (v.z || 1);
}
|
javascript
|
{
"resource": ""
}
|
q22246
|
setTransform
|
train
|
function setTransform() {
var a = this.val;
if (arguments.length === 9) {
a[0] = arguments[0]; // a - m00
a[1] = arguments[1]; // b - m10
a[2] = arguments[2]; // c - m20
a[3] = arguments[3]; // d - m01
a[4] = arguments[4]; // e - m11
a[5] = arguments[5]; // f - m21
a[6] = arguments[6]; // g - m02
a[7] = arguments[7]; // h - m12
a[8] = arguments[8]; // i - m22
} else if (arguments.length === 6) {
a[0] = arguments[0]; // a
a[1] = arguments[2]; // c
a[2] = arguments[4]; // e
a[3] = arguments[1]; // b
a[4] = arguments[3]; // d
a[5] = arguments[5]; // f
a[6] = 0; // g
a[7] = 0; // h
a[8] = 1; // i
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q22247
|
multiplyVectorInverse
|
train
|
function multiplyVectorInverse(v) {
var a = this.val,
x = v.x,
y = v.y;
var invD = 1 / (a[0] * a[4] + a[3] * -a[1]);
v.x = a[4] * invD * x + -a[3] * invD * y + (a[7] * a[3] - a[6] * a[4]) * invD;
v.y = a[0] * invD * y + -a[1] * invD * x + (-a[7] * a[0] + a[6] * a[1]) * invD;
return v;
}
|
javascript
|
{
"resource": ""
}
|
q22248
|
setShape
|
train
|
function setShape(x, y, w, h) {
var hW = w / 2;
var hH = h / 2;
this.pos.set(x, y);
this.radius = Math.max(hW, hH);
this.ratio.set(hW / this.radius, hH / this.radius);
this.radiusV.set(this.radius, this.radius).scaleV(this.ratio);
var r = this.radius * this.radius;
this.radiusSq.set(r, r).scaleV(this.ratio);
this.updateBounds();
return this;
}
|
javascript
|
{
"resource": ""
}
|
q22249
|
scale
|
train
|
function scale(x, y) {
y = typeof y !== "undefined" ? y : x;
return this.setShape(this.pos.x, this.pos.y, this.radiusV.x * 2 * x, this.radiusV.y * 2 * y);
}
|
javascript
|
{
"resource": ""
}
|
q22250
|
splitEarcut
|
train
|
function splitEarcut(start, triangles, dim, minX, minY, invSize) {
// look for a valid diagonal that divides the polygon into two
var a = start;
do {
var b = a.next.next;
while (b !== a.prev) {
if (a.i !== b.i && isValidDiagonal(a, b)) {
// split the polygon in two by the diagonal
var c = splitPolygon(a, b);
// filter colinear points around the cuts
a = filterPoints(a, a.next);
c = filterPoints(c, c.next);
// run earcut on each half
earcutLinked(a, triangles, dim, minX, minY, invSize);
earcutLinked(c, triangles, dim, minX, minY, invSize);
return;
}
b = b.next;
}
a = a.next;
} while (a !== start);
}
|
javascript
|
{
"resource": ""
}
|
q22251
|
zOrder
|
train
|
function zOrder(x, y, minX, minY, invSize) {
// coords are transformed into non-negative 15-bit integer range
x = 32767 * (x - minX) * invSize;
y = 32767 * (y - minY) * invSize;
x = (x | (x << 8)) & 0x00FF00FF;
x = (x | (x << 4)) & 0x0F0F0F0F;
x = (x | (x << 2)) & 0x33333333;
x = (x | (x << 1)) & 0x55555555;
y = (y | (y << 8)) & 0x00FF00FF;
y = (y | (y << 4)) & 0x0F0F0F0F;
y = (y | (y << 2)) & 0x33333333;
y = (y | (y << 1)) & 0x55555555;
return x | (y << 1);
}
|
javascript
|
{
"resource": ""
}
|
q22252
|
pointInTriangle
|
train
|
function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
(ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
(bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
}
|
javascript
|
{
"resource": ""
}
|
q22253
|
area
|
train
|
function area(p, q, r) {
return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
}
|
javascript
|
{
"resource": ""
}
|
q22254
|
splitPolygon
|
train
|
function splitPolygon(a, b) {
var a2 = new Node(a.i, a.x, a.y),
b2 = new Node(b.i, b.x, b.y),
an = a.next,
bp = b.prev;
a.next = b;
b.prev = a;
a2.next = an;
an.prev = a2;
b2.next = a2;
a2.prev = b2;
bp.next = b2;
b2.prev = bp;
return b2;
}
|
javascript
|
{
"resource": ""
}
|
q22255
|
transform
|
train
|
function transform(m) {
var points = this.points;
var len = points.length;
for (var i = 0; i < len; i++) {
m.multiplyVector(points[i]);
}
this.recalc();
this.updateBounds();
return this;
}
|
javascript
|
{
"resource": ""
}
|
q22256
|
clone
|
train
|
function clone() {
var copy = [];
this.points.forEach(function (point) {
copy.push(point.clone());
});
return new me.Polygon(this.pos.x, this.pos.y, copy);
}
|
javascript
|
{
"resource": ""
}
|
q22257
|
setShape
|
train
|
function setShape(x, y, w, h) {
var points = w; // assume w is an array by default
if (arguments.length === 4) {
points = this.points;
points[0].set(0, 0); // 0, 0
points[1].set(w, 0); // 1, 0
points[2].set(w, h); // 1, 1
points[3].set(0, h); // 0, 1
}
this._super(me.Polygon, "setShape", [x, y, points]); // private properties to cache width & height
this._width = this.points[2].x; // w
this._height = this.points[2].y; // h
return this;
}
|
javascript
|
{
"resource": ""
}
|
q22258
|
setPoints
|
train
|
function setPoints(points) {
var x = Infinity,
y = Infinity,
right = -Infinity,
bottom = -Infinity;
points.forEach(function (point) {
x = Math.min(x, point.x);
y = Math.min(y, point.y);
right = Math.max(right, point.x);
bottom = Math.max(bottom, point.y);
});
this.setShape(x, y, right - x, bottom - y);
return this;
}
|
javascript
|
{
"resource": ""
}
|
q22259
|
copy
|
train
|
function copy(rect) {
return this.setShape(rect.pos.x, rect.pos.y, rect._width, rect._height);
}
|
javascript
|
{
"resource": ""
}
|
q22260
|
union
|
train
|
function union(
/** {me.Rect} */
r) {
var x1 = Math.min(this.left, r.left);
var y1 = Math.min(this.top, r.top);
this.resize(Math.max(this.right, r.right) - x1, Math.max(this.bottom, r.bottom) - y1);
this.pos.set(x1, y1);
return this;
}
|
javascript
|
{
"resource": ""
}
|
q22261
|
containsPoint
|
train
|
function containsPoint(x, y) {
return x >= this.left && x <= this.right && y >= this.top && y <= this.bottom;
}
|
javascript
|
{
"resource": ""
}
|
q22262
|
equals
|
train
|
function equals(r) {
return r.left === this.left && r.right === this.right && r.top === this.top && r.bottom === this.bottom;
}
|
javascript
|
{
"resource": ""
}
|
q22263
|
removeShape
|
train
|
function removeShape(shape) {
me.utils.array.remove(this.shapes, shape); // update the body bounds to take in account the removed shape
this.updateBounds(); // return the length of the shape list
return this.shapes.length;
}
|
javascript
|
{
"resource": ""
}
|
q22264
|
computeVelocity
|
train
|
function computeVelocity(vel) {
// apply fore if defined
if (this.force.x) {
vel.x += this.force.x * me.timer.tick;
}
if (this.force.y) {
vel.y += this.force.y * me.timer.tick;
} // apply friction
if (this.friction.x || this.friction.y) {
this.applyFriction(vel);
} // apply gravity if defined
if (this.gravity.y) {
vel.x += this.gravity.x * this.mass * me.timer.tick;
}
if (this.gravity.y) {
vel.y += this.gravity.y * this.mass * me.timer.tick; // check if falling / jumping
this.falling = vel.y * Math.sign(this.gravity.y) > 0;
this.jumping = this.falling ? false : this.jumping;
} // cap velocity
if (vel.y !== 0) {
vel.y = me.Math.clamp(vel.y, -this.maxVel.y, this.maxVel.y);
}
if (vel.x !== 0) {
vel.x = me.Math.clamp(vel.x, -this.maxVel.x, this.maxVel.x);
}
}
|
javascript
|
{
"resource": ""
}
|
q22265
|
QT_ARRAY_POP
|
train
|
function QT_ARRAY_POP(bounds, max_objects, max_levels, level) {
if (QT_ARRAY.length > 0) {
var _qt = QT_ARRAY.pop();
_qt.bounds = bounds;
_qt.max_objects = max_objects || 4;
_qt.max_levels = max_levels || 4;
_qt.level = level || 0;
return _qt;
} else {
return new me.QuadTree(bounds, max_objects, max_levels, level);
}
}
|
javascript
|
{
"resource": ""
}
|
q22266
|
scale
|
train
|
function scale(x, y) {
var _x = x,
_y = typeof y === "undefined" ? _x : y; // set the scaleFlag
this.currentTransform.scale(_x, _y); // resize the bounding box
this.getBounds().resize(this.width * _x, this.height * _y);
return this;
}
|
javascript
|
{
"resource": ""
}
|
q22267
|
resize
|
train
|
function resize(w, h) {
this._super(me.Renderable, "resize", [this.repeatX ? Infinity : w, this.repeatY ? Infinity : h]);
}
|
javascript
|
{
"resource": ""
}
|
q22268
|
onDeactivateEvent
|
train
|
function onDeactivateEvent() {
// cancel all event subscriptions
me.event.unsubscribe(this.vpChangeHdlr);
me.event.unsubscribe(this.vpResizeHdlr);
me.event.unsubscribe(this.vpLoadedHdlr);
}
|
javascript
|
{
"resource": ""
}
|
q22269
|
reverseAnimation
|
train
|
function reverseAnimation(name) {
if (typeof name !== "undefined" && typeof this.anim[name] !== "undefined") {
this.anim[name].frames.reverse();
} else {
this.anim[this.current.name].frames.reverse();
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q22270
|
setRegion
|
train
|
function setRegion(region) {
if (this.source !== null) {
// set the source texture for the given region
this.image = this.source.getTexture(region);
} // set the sprite offset within the texture
this.current.offset.setV(region.offset); // set angle if defined
this.current.angle = region.angle; // update the default "current" size
this.width = this.current.width = region.width;
this.height = this.current.height = region.height; // set global anchortPoint if defined
if (region.anchorPoint) {
this.anchorPoint.set(this._flip.x && region.trimmed === true ? 1 - region.anchorPoint.x : region.anchorPoint.x, this._flip.y && region.trimmed === true ? 1 - region.anchorPoint.y : region.anchorPoint.y);
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q22271
|
setAnimationFrame
|
train
|
function setAnimationFrame(idx) {
this.current.idx = (idx || 0) % this.current.length;
return this.setRegion(this.getAnimationFrameObjectByIndex(this.current.idx));
}
|
javascript
|
{
"resource": ""
}
|
q22272
|
onAnchorUpdate
|
train
|
function onAnchorUpdate(newX, newY) {
// since the callback is called before setting the new value
// manually update the anchor point (required for updateBoundsPos)
this.anchorPoint.setMuted(newX, newY); // then call updateBouds
this.updateBoundsPos(this.pos.x, this.pos.y);
}
|
javascript
|
{
"resource": ""
}
|
q22273
|
update
|
train
|
function update(dt) {
// call the parent constructor
var updated = this._super(me.Sprite, "update", [dt]); // check if the button was updated
if (this.updated) {
// clear the flag
if (!this.released) {
this.updated = false;
}
return true;
} // else only return true/false based on the parent function
return updated;
}
|
javascript
|
{
"resource": ""
}
|
q22274
|
leave
|
train
|
function leave(event) {
this.hover = false;
this.release.call(this, event);
return this.onOut.call(this, event);
}
|
javascript
|
{
"resource": ""
}
|
q22275
|
onActivateEvent
|
train
|
function onActivateEvent() {
// register pointer events
me.input.registerPointerEvent("pointerdown", this, this.clicked.bind(this));
me.input.registerPointerEvent("pointerup", this, this.release.bind(this));
me.input.registerPointerEvent("pointercancel", this, this.release.bind(this));
me.input.registerPointerEvent("pointerenter", this, this.enter.bind(this));
me.input.registerPointerEvent("pointerleave", this, this.leave.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q22276
|
onDeactivateEvent
|
train
|
function onDeactivateEvent() {
// release pointer events
me.input.releasePointerEvent("pointerdown", this);
me.input.releasePointerEvent("pointerup", this);
me.input.releasePointerEvent("pointercancel", this);
me.input.releasePointerEvent("pointerenter", this);
me.input.releasePointerEvent("pointerleave", this);
me.timer.clearTimeout(this.holdTimeout);
}
|
javascript
|
{
"resource": ""
}
|
q22277
|
getChildAt
|
train
|
function getChildAt(index) {
if (index >= 0 && index < this.children.length) {
return this.children[index];
} else {
throw new Error("Index (" + index + ") Out Of Bounds for getChildAt()");
}
}
|
javascript
|
{
"resource": ""
}
|
q22278
|
getNextChild
|
train
|
function getNextChild(child) {
var index = this.children.indexOf(child) - 1;
if (index >= 0 && index < this.children.length) {
return this.getChildAt(index);
}
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
q22279
|
getChildByType
|
train
|
function getChildByType(_class) {
var objList = [];
for (var i = this.children.length - 1; i >= 0; i--) {
var obj = this.children[i];
if (obj instanceof _class) {
objList.push(obj);
}
if (obj instanceof me.Container) {
objList = objList.concat(obj.getChildByType(_class));
}
}
return objList;
}
|
javascript
|
{
"resource": ""
}
|
q22280
|
updateChildBounds
|
train
|
function updateChildBounds() {
this.childBounds.pos.set(Infinity, Infinity);
this.childBounds.resize(-Infinity, -Infinity);
var childBounds;
for (var i = this.children.length, child; i--, child = this.children[i];) {
if (child.isRenderable) {
if (child instanceof me.Container) {
childBounds = child.childBounds;
} else {
childBounds = child.getBounds();
} // TODO : returns an "empty" rect instead of null (e.g. EntityObject)
// TODO : getBounds should always return something anyway
if (childBounds !== null) {
this.childBounds.union(childBounds);
}
}
}
return this.childBounds;
}
|
javascript
|
{
"resource": ""
}
|
q22281
|
isAttachedToRoot
|
train
|
function isAttachedToRoot() {
if (this.root === true) {
return true;
} else {
var ancestor = this.ancestor;
while (ancestor) {
if (ancestor.root === true) {
return true;
}
ancestor = ancestor.ancestor;
}
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q22282
|
removeChild
|
train
|
function removeChild(child, keepalive) {
if (this.hasChild(child)) {
me.utils.function.defer(deferredRemove, this, child, keepalive);
} else {
throw new Error("Child is not mine.");
}
}
|
javascript
|
{
"resource": ""
}
|
q22283
|
setChildsProperty
|
train
|
function setChildsProperty(prop, val, recursive) {
for (var i = this.children.length; i >= 0; i--) {
var obj = this.children[i];
if (recursive === true && obj instanceof me.Container) {
obj.setChildsProperty(prop, val, recursive);
}
obj[prop] = val;
}
}
|
javascript
|
{
"resource": ""
}
|
q22284
|
_sortZ
|
train
|
function _sortZ(a, b) {
return b.pos && a.pos ? b.pos.z - a.pos.z : a.pos ? -Infinity : Infinity;
}
|
javascript
|
{
"resource": ""
}
|
q22285
|
setDeadzone
|
train
|
function setDeadzone(w, h) {
if (typeof this.deadzone === "undefined") {
this.deadzone = new me.Rect(0, 0, 0, 0);
} // reusing the old code for now...
this.deadzone.pos.set(~~((this.width - w) / 2), ~~((this.height - h) / 2 - h * 0.25));
this.deadzone.resize(w, h);
this.smoothFollow = false; // force a camera update
this.updateTarget();
this.smoothFollow = true;
}
|
javascript
|
{
"resource": ""
}
|
q22286
|
resize
|
train
|
function resize(w, h) {
// parent consctructor, resize camera rect
this._super(me.Renderable, "resize", [w, h]); // disable damping while resizing
this.smoothFollow = false; // update bounds
var level = me.levelDirector.getCurrentLevel();
this.setBounds(0, 0, Math.max(w, level ? level.width : 0), Math.max(h, level ? level.height : 0)); // reset everthing
this.setDeadzone(w / 6, h / 6);
this.update();
this.smoothFollow = true;
me.event.publish(me.event.VIEWPORT_ONRESIZE, [this.width, this.height]);
return this;
}
|
javascript
|
{
"resource": ""
}
|
q22287
|
move
|
train
|
function move(x, y) {
this.moveTo(this.pos.x + x, this.pos.y + y);
}
|
javascript
|
{
"resource": ""
}
|
q22288
|
shake
|
train
|
function shake(intensity, duration, axis, onComplete, force) {
if (this._shake.duration === 0 || force === true) {
this._shake.intensity = intensity;
this._shake.duration = duration;
this._shake.axis = axis || this.AXIS.BOTH;
this._shake.onComplete = typeof onComplete === "function" ? onComplete : undefined;
}
}
|
javascript
|
{
"resource": ""
}
|
q22289
|
drawFX
|
train
|
function drawFX(renderer) {
// fading effect
if (this._fadeIn.tween) {
renderer.clearColor(this._fadeIn.color); // remove the tween if over
if (this._fadeIn.color.alpha === 1.0) {
this._fadeIn.tween = null;
me.pool.push(this._fadeIn.color);
this._fadeIn.color = null;
}
} // flashing effect
if (this._fadeOut.tween) {
renderer.clearColor(this._fadeOut.color); // remove the tween if over
if (this._fadeOut.color.alpha === 0.0) {
this._fadeOut.tween = null;
me.pool.push(this._fadeOut.color);
this._fadeOut.color = null;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q22290
|
draw
|
train
|
function draw(renderer, container) {
var translateX = this.pos.x + this.offset.x;
var translateY = this.pos.y + this.offset.y; // translate the world coordinates by default to screen coordinates
container.currentTransform.translate(-translateX, -translateY); // clip to camera bounds
renderer.clipRect(0, 0, this.width, this.height);
this.preDraw(renderer);
container.preDraw(renderer); // draw all objects,
// specifying the viewport as the rectangle area to redraw
container.draw(renderer, this); // draw the viewport/camera effects
this.drawFX(renderer);
container.postDraw(renderer);
this.postDraw(renderer); // translate the world coordinates by default to screen coordinates
container.currentTransform.translate(translateX, translateY);
}
|
javascript
|
{
"resource": ""
}
|
q22291
|
distanceTo
|
train
|
function distanceTo(e) {
var a = this.getBounds();
var b = e.getBounds(); // the me.Vector2d object also implements the same function, but
// we have to use here the center of both entities
var dx = a.pos.x + a.width / 2 - (b.pos.x + b.width / 2);
var dy = a.pos.y + a.height / 2 - (b.pos.y + b.height / 2);
return Math.sqrt(dx * dx + dy * dy);
}
|
javascript
|
{
"resource": ""
}
|
q22292
|
distanceToPoint
|
train
|
function distanceToPoint(v) {
var a = this.getBounds(); // the me.Vector2d object also implements the same function, but
// we have to use here the center of both entities
var dx = a.pos.x + a.width / 2 - v.x;
var dy = a.pos.y + a.height / 2 - v.y;
return Math.sqrt(dx * dx + dy * dy);
}
|
javascript
|
{
"resource": ""
}
|
q22293
|
angleTo
|
train
|
function angleTo(e) {
var a = this.getBounds();
var b = e.getBounds(); // the me.Vector2d object also implements the same function, but
// we have to use here the center of both entities
var ax = b.pos.x + b.width / 2 - (a.pos.x + a.width / 2);
var ay = b.pos.y + b.height / 2 - (a.pos.y + a.height / 2);
return Math.atan2(ay, ax);
}
|
javascript
|
{
"resource": ""
}
|
q22294
|
angleToPoint
|
train
|
function angleToPoint(v) {
var a = this.getBounds(); // the me.Vector2d object also implements the same function, but
// we have to use here the center of both entities
var ax = v.x - (a.pos.x + a.width / 2);
var ay = v.y - (a.pos.y + a.height / 2);
return Math.atan2(ay, ax);
}
|
javascript
|
{
"resource": ""
}
|
q22295
|
updateBoundsPos
|
train
|
function updateBoundsPos(x, y) {
if (typeof this.body !== "undefined") {
var _pos = this.body.pos;
this._super(me.Renderable, "updateBoundsPos", [x + _pos.x, y + _pos.y]);
} else {
this._super(me.Renderable, "updateBoundsPos", [x, y]);
}
return this.getBounds();
}
|
javascript
|
{
"resource": ""
}
|
q22296
|
preloadTMX
|
train
|
function preloadTMX(tmxData, onload, onerror) {
function addToTMXList(data) {
// set the TMX content
tmxList[tmxData.name] = data; // add the tmx to the levelDirector
if (tmxData.type === "tmx") {
me.levelDirector.addTMXLevel(tmxData.name);
}
} //if the data is in the tmxData object, don't get it via a XMLHTTPRequest
if (tmxData.data) {
addToTMXList(tmxData.data);
onload();
return;
}
var xmlhttp = new XMLHttpRequest(); // check the data format ('tmx', 'json')
var format = me.utils.file.getExtension(tmxData.src);
if (xmlhttp.overrideMimeType) {
if (format === "json") {
xmlhttp.overrideMimeType("application/json");
} else {
xmlhttp.overrideMimeType("text/xml");
}
}
xmlhttp.open("GET", tmxData.src + api.nocache, true);
xmlhttp.withCredentials = me.loader.withCredentials; // set the callbacks
xmlhttp.ontimeout = onerror;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
// status = 0 when file protocol is used, or cross-domain origin,
// (With Chrome use "--allow-file-access-from-files --disable-web-security")
if (xmlhttp.status === 200 || xmlhttp.status === 0 && xmlhttp.responseText) {
var result = null; // parse response
switch (format) {
case "xml":
case "tmx":
case "tsx":
// ie9 does not fully implement the responseXML
if (me.device.ua.match(/msie/i) || !xmlhttp.responseXML) {
if (window.DOMParser) {
// manually create the XML DOM
result = new DOMParser().parseFromString(xmlhttp.responseText, "text/xml");
} else {
throw new Error("XML file format loading not supported, use the JSON file format instead");
}
} else {
result = xmlhttp.responseXML;
} // converts to a JS object
var data = me.TMXUtils.parse(result);
switch (format) {
case "tmx":
result = data.map;
break;
case "tsx":
result = data.tilesets[0];
break;
}
break;
case "json":
result = JSON.parse(xmlhttp.responseText);
break;
default:
throw new Error("TMX file format " + format + "not supported !");
} //set the TMX content
addToTMXList(result); // fire the callback
onload();
} else {
onerror(tmxData.name);
}
}
}; // send the request
xmlhttp.send();
}
|
javascript
|
{
"resource": ""
}
|
q22297
|
setFont
|
train
|
function setFont(font, size) {
// font name and type
var font_names = font.split(",").map(function (value) {
value = value.trim();
return !/(^".*"$)|(^'.*'$)/.test(value) ? "\"" + value + "\"" : value;
}); // font size
if (typeof size === "number") {
this._fontSize = size;
size += "px";
} else
/* string */
{
// extract the units and convert if necessary
var CSSval = size.match(/([-+]?[\d.]*)(.*)/);
this._fontSize = parseFloat(CSSval[1]);
if (CSSval[2]) {
this._fontSize *= toPX[runits.indexOf(CSSval[2])];
} else {
// no unit define, assume px
size += "px";
}
}
this.height = this._fontSize;
this.font = size + " " + font_names.join(",");
this.isDirty = true;
return this;
}
|
javascript
|
{
"resource": ""
}
|
q22298
|
setText
|
train
|
function setText(value) {
value = "" + value;
if (this._text !== value) {
if (Array.isArray(value)) {
this._text = value.join("\n");
} else {
this._text = value;
}
this.isDirty = true;
}
return this;
}
|
javascript
|
{
"resource": ""
}
|
q22299
|
measureTextWidth
|
train
|
function measureTextWidth(font, text) {
var characters = text.split("");
var width = 0;
var lastGlyph = null;
for (var i = 0; i < characters.length; i++) {
var ch = characters[i].charCodeAt(0);
var glyph = font.fontData.glyphs[ch];
var kerning = lastGlyph && lastGlyph.kerning ? lastGlyph.getKerning(ch) : 0;
width += (glyph.xadvance + kerning) * font.fontScale.x;
lastGlyph = glyph;
}
return width;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.