<commit_before>'use strict';

exports.BattleScripts = {
	moveHit: function (target, pokemon, move, moveData, isSecondary, isSelf) {
		let damage;
		move = this.getMoveCopy(move);

		if (!moveData) moveData = move;
		if (!moveData.flags) moveData.flags = {};
		let hitResult = true;

		// TryHit events:
		//   STEP 1: we see if the move will succeed at all:
		//   - TryHit, TryHitSide, or TryHitField are run on the move,
		//     depending on move target (these events happen in useMove
		//     or tryMoveHit, not below)
		//   == primary hit line ==
		//   Everything after this only happens on the primary hit (not on
		//   secondary or self-hits)
		//   STEP 2: we see if anything blocks the move from hitting:
		//   - TryFieldHit is run on the target
		//   STEP 3: we see if anything blocks the move from hitting the target:
		//   - If the move's target is a pokemon, TryHit is run on that pokemon

		// Note:
		//   If the move target is `foeSide`:
		//     event target = pokemon 0 on the target side
		//   If the move target is `allySide` or `all`:
		//     event target = the move user
		//
		//   This is because events can't accept actual sides or fields as
		//   targets. Choosing these event targets ensures that the correct
		//   side or field is hit.
		//
		//   It is the `TryHitField` event handler's responsibility to never
		//   use `target`.
		//   It is the `TryFieldHit` event handler's responsibility to read
		//   move.target and react accordingly.
		//   An exception is `TryHitSide` as a single event (but not as a normal
		//   event), which is passed the target side.

		if (move.target === 'all' && !isSelf) {
			hitResult = this.singleEvent('TryHitField', moveData, {}, target, pokemon, move);
		} else if ((move.target === 'foeSide' || move.target === 'allySide') && !isSelf) {
			hitResult = this.singleEvent('TryHitSide', moveData, {}, target.side, pokemon, move);
		} else if (target) {
			hitResult = this.singleEvent('TryHit', moveData, {}, target, pokemon, move);
		}
		if (!hitResult) {
			if (hitResult === false) this.add('-fail', target);
			return false;
		}

		if (target && !isSecondary && !isSelf) {
			if (move.target !== 'all' && move.target !== 'allySide' && move.target !== 'foeSide') {
				hitResult = this.runEvent('TryPrimaryHit', target, pokemon, moveData);
				if (hitResult === 0) {
					// special Substitute flag
					hitResult = true;
					target = null;
				}
			}
		}
		if (target && isSecondary && !moveData.self) {
			hitResult = true;
		}
		if (!hitResult) {
			return false;
		}

		if (target) {
			let didSomething = false;

			damage = this.getDamage(pokemon, target, moveData);

			// getDamage has several possible return values:
			//
			//   a number:
			//     means that much damage is dealt (0 damage still counts as dealing
			//     damage for the purposes of things like Static)
			//   false:
			//     gives error message: "But it failed!" and move ends
			//   null:
			//     the move ends, with no message (usually, a custom fail message
			//     was already output by an event handler)
			//   undefined:
			//     means no damage is dealt and the move continues
			//
			// basically, these values have the same meanings as they do for event
			// handlers.

			if ((damage || damage === 0) && !target.fainted) {
				if (move.noFaint && damage >= target.hp) {
					damage = target.hp - 1;
				}
				damage = this.damage(damage, target, pokemon, move);
				if (!(damage || damage === 0)) {
					this.debug('damage interrupted');
					return false;
				}
				didSomething = true;
			}
			if (damage === false || damage === null) {
				if (damage === false && !isSecondary && !isSelf) {
					this.add('-fail', target);
				}
				this.debug('damage calculation interrupted');
				return false;
			}

			if (moveData.boosts && !target.fainted) {
				hitResult = this.boost(moveData.boosts, target, pokemon, move, isSecondary, isSelf);
				didSomething = didSomething || hitResult;
			}
			if (moveData.heal && !target.fainted) {
				let d = target.heal((this.gen < 5 ? Math.floor : Math.round)(target.maxhp * moveData.heal[0] / moveData.heal[1]));
				if (!d && d !== 0) {
					this.add('-fail', target);
					this.debug('heal interrupted');
					return false;
				}
				this.add('-heal', target, target.getHealth);
				didSomething = true;
			}
			if (moveData.status) {
				hitResult = target.trySetStatus(moveData.status, pokemon, moveData.ability ? moveData.ability : move);
				if (!hitResult && move.status) return hitResult;
				didSomething = didSomething || hitResult;
			}
			if (moveData.forceStatus) {
				hitResult = target.setStatus(moveData.forceStatus, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.volatileStatus) {
				hitResult = target.addVolatile(moveData.volatileStatus, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.sideCondition) {
				hitResult = target.side.addSideCondition(moveData.sideCondition, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.weather) {
				hitResult = this.setWeather(moveData.weather, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.terrain) {
				hitResult = this.setTerrain(moveData.terrain, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.pseudoWeather) {
				hitResult = this.addPseudoWeather(moveData.pseudoWeather, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.forceSwitch) {
				if (this.canSwitch(target.side)) didSomething = true; // at least defer the fail message to later
			}
			if (moveData.selfSwitch) {
				if (this.canSwitch(pokemon.side)) didSomething = true; // at least defer the fail message to later
			}
			// Hit events
			//   These are like the TryHit events, except we don't need a FieldHit event.
			//   Scroll up for the TryHit event documentation, and just ignore the "Try" part. ;)
			hitResult = null;
			if (move.target === 'all' && !isSelf) {
				if (moveData.onHitField) hitResult = this.singleEvent('HitField', moveData, {}, target, pokemon, move);
			} else if ((move.target === 'foeSide' || move.target === 'allySide') && !isSelf) {
				if (moveData.onHitSide) hitResult = this.singleEvent('HitSide', moveData, {}, target.side, pokemon, move);
			} else {
				if (moveData.onHit) hitResult = this.singleEvent('Hit', moveData, {}, target, pokemon, move);
				if (!isSelf && !isSecondary) {
					this.runEvent('Hit', target, pokemon, move);
				}
				if (moveData.onAfterHit) hitResult = this.singleEvent('AfterHit', moveData, {}, target, pokemon, move);
			}

			if (!hitResult && !didSomething && !moveData.self && !moveData.selfdestruct) {
				if (!isSelf && !isSecondary) {
					if (hitResult === false || didSomething === false) this.add('-fail', target);
				}
				this.debug('move failed because it did nothing');
				return false;
			}
		}
		if (moveData.self) {
			let selfRoll;
			if (!isSecondary && moveData.self.boosts) selfRoll = this.random(100);
			// This is done solely to mimic in-game RNG behaviour. All self drops have a 100% chance of happening but still grab a random number.
			if (typeof moveData.self.chance === 'undefined' || selfRoll < moveData.self.chance) {
				this.moveHit(pokemon, pokemon, move, moveData.self, isSecondary, true);
			}
		}
		if (moveData.secondaries) {
			let secondaryRoll;
			let secondaries = this.runEvent('ModifySecondaries', target, pokemon, moveData, moveData.secondaries.slice());
			for (let i = 0; i < secondaries.length; i++) {
				secondaryRoll = this.random(100);
				if (typeof secondaries[i].chance === 'undefined' || secondaryRoll < secondaries[i].chance) {
					// mod for automagic start
					let flag = true;
					let canSetStatus = function (status, target, pokemon) {
						if (target.status) return false;
						let cantStatus = {
							brn: ['Fire', 'comatose', 'waterveil', 'waterbubble'],
							frz: ['Ice', 'comatose', 'magmaarmor'],
							par: ['Electric', 'comatose', 'limber'],
							psn: ['comatose', 'immunity'],
							slp: ['comatose', 'insomnia', 'vitalspirit'],
							tox: ['comatose', 'immunity'],
						};
						if (target.hasType(['Poison', 'Steel']) && (status === 'psn' || status === 'tox')) {
							if (pokemon.hasAbility('corrosion')) {
								return true;
							} else {
								return false;
							}
						}
						if (target.hasType(cantStatus[status][0])) return false;
						if (move.ignoreAbility) return true;
						if (target.hasAbility('leafguard') && this.isWeather(['sunnyday', 'desolateland'])) return false;
						if (target.hasAbility('shieldsdown') && target.template.speciesid === 'miniormeteor') return false;
						if (target.hasAbility(cantStatus[status])) return false;
						return true;
					};
					if (moveData.secondary.status) flag = canSetStatus(moveData.secondary.status, target, pokemon);
					if (moveData.secondary.volatileStatus) flag = !(moveData.secondary.volatileStatus in target.volatiles);
					if (moveData.secondary.volatileStatus === 'flinch') flag = flag && target.activeTurns && !target.moveThisTurn;
					this.moveHit(target, pokemon, move, secondaries[i], true, isSelf);
					if (moveData.secondary.self && moveData.secondary.self.boosts) {
						Object.keys(moveData.secondary.self.boosts).forEach(boost => {
							if (pokemon.boosts[boost] === 6) flag = false;
						});
					} else {
						flag = flag && !(target.hp === undefined || target.hp <= 0);
					}
					if (moveData.target !== 'self' && moveData.secondary.boosts) {
						let cantLower = {
							'atk': ['clearbody', 'fullmetalbody', 'hypercutter', 'whitesmoke'],
							'def': ['bigpecks', 'clearbody', 'fullmetalbody', 'whitesmoke'],
							'spa': ['clearbody', 'fullmetalbody', 'whitesmoke'],
							'spd': ['clearbody', 'fullmetalbody', 'whitesmoke'],
							'spe': ['clearbody', 'fullmetalbody', 'whitesmoke'],
							'accuracy': ['clearbody', 'fullmetalbody', 'keeneye', 'whitesmoke'],
						};
						for (let k in moveData.secondary.boosts) {
							if (target.boosts[k] === -6) {
								flag = false;
								continue;
							}
							if (moveData.secondary.boosts[k] < 0 && target.hasAbility(cantLower[k]) && !move.ignoreAbility) {
								flag = false;
								break;
							}
						}
					}
					if (pokemon.hasAbility('sheerforce')) flag = false;
					if (target && target.hasAbility('shielddust') && !move.ignoreAbility && !move.secondary.self.boosts) {
						flag = false;
					}
					if (flag) this.runEvent('AfterSecondaryEffect', target, pokemon, moveData);
					// mod for automagic end
				}
			}
		}
		if (target && target.hp > 0 && pokemon.hp > 0 && moveData.forceSwitch && this.canSwitch(target.side)) {
			hitResult = this.runEvent('DragOut', target, pokemon, move);
			if (hitResult) {
				target.forceSwitchFlag = true;
			} else if (hitResult === false && move.category === 'Status') {
				this.add('-fail', target);
			}
		}
		if (move.selfSwitch && pokemon.hp) {
			pokemon.switchFlag = move.selfSwitch;
		}
		return damage;
	},
};
<commit_msg>Automagic: Fix crash<commit_after>'use strict';

exports.BattleScripts = {
	moveHit: function (target, pokemon, move, moveData, isSecondary, isSelf) {
		let damage;
		move = this.getMoveCopy(move);

		if (!moveData) moveData = move;
		if (!moveData.flags) moveData.flags = {};
		let hitResult = true;

		// TryHit events:
		//   STEP 1: we see if the move will succeed at all:
		//   - TryHit, TryHitSide, or TryHitField are run on the move,
		//     depending on move target (these events happen in useMove
		//     or tryMoveHit, not below)
		//   == primary hit line ==
		//   Everything after this only happens on the primary hit (not on
		//   secondary or self-hits)
		//   STEP 2: we see if anything blocks the move from hitting:
		//   - TryFieldHit is run on the target
		//   STEP 3: we see if anything blocks the move from hitting the target:
		//   - If the move's target is a pokemon, TryHit is run on that pokemon

		// Note:
		//   If the move target is `foeSide`:
		//     event target = pokemon 0 on the target side
		//   If the move target is `allySide` or `all`:
		//     event target = the move user
		//
		//   This is because events can't accept actual sides or fields as
		//   targets. Choosing these event targets ensures that the correct
		//   side or field is hit.
		//
		//   It is the `TryHitField` event handler's responsibility to never
		//   use `target`.
		//   It is the `TryFieldHit` event handler's responsibility to read
		//   move.target and react accordingly.
		//   An exception is `TryHitSide` as a single event (but not as a normal
		//   event), which is passed the target side.

		if (move.target === 'all' && !isSelf) {
			hitResult = this.singleEvent('TryHitField', moveData, {}, target, pokemon, move);
		} else if ((move.target === 'foeSide' || move.target === 'allySide') && !isSelf) {
			hitResult = this.singleEvent('TryHitSide', moveData, {}, target.side, pokemon, move);
		} else if (target) {
			hitResult = this.singleEvent('TryHit', moveData, {}, target, pokemon, move);
		}
		if (!hitResult) {
			if (hitResult === false) this.add('-fail', target);
			return false;
		}

		if (target && !isSecondary && !isSelf) {
			if (move.target !== 'all' && move.target !== 'allySide' && move.target !== 'foeSide') {
				hitResult = this.runEvent('TryPrimaryHit', target, pokemon, moveData);
				if (hitResult === 0) {
					// special Substitute flag
					hitResult = true;
					target = null;
				}
			}
		}
		if (target && isSecondary && !moveData.self) {
			hitResult = true;
		}
		if (!hitResult) {
			return false;
		}

		if (target) {
			let didSomething = false;

			damage = this.getDamage(pokemon, target, moveData);

			// getDamage has several possible return values:
			//
			//   a number:
			//     means that much damage is dealt (0 damage still counts as dealing
			//     damage for the purposes of things like Static)
			//   false:
			//     gives error message: "But it failed!" and move ends
			//   null:
			//     the move ends, with no message (usually, a custom fail message
			//     was already output by an event handler)
			//   undefined:
			//     means no damage is dealt and the move continues
			//
			// basically, these values have the same meanings as they do for event
			// handlers.

			if ((damage || damage === 0) && !target.fainted) {
				if (move.noFaint && damage >= target.hp) {
					damage = target.hp - 1;
				}
				damage = this.damage(damage, target, pokemon, move);
				if (!(damage || damage === 0)) {
					this.debug('damage interrupted');
					return false;
				}
				didSomething = true;
			}
			if (damage === false || damage === null) {
				if (damage === false && !isSecondary && !isSelf) {
					this.add('-fail', target);
				}
				this.debug('damage calculation interrupted');
				return false;
			}

			if (moveData.boosts && !target.fainted) {
				hitResult = this.boost(moveData.boosts, target, pokemon, move, isSecondary, isSelf);
				didSomething = didSomething || hitResult;
			}
			if (moveData.heal && !target.fainted) {
				let d = target.heal((this.gen < 5 ? Math.floor : Math.round)(target.maxhp * moveData.heal[0] / moveData.heal[1]));
				if (!d && d !== 0) {
					this.add('-fail', target);
					this.debug('heal interrupted');
					return false;
				}
				this.add('-heal', target, target.getHealth);
				didSomething = true;
			}
			if (moveData.status) {
				hitResult = target.trySetStatus(moveData.status, pokemon, moveData.ability ? moveData.ability : move);
				if (!hitResult && move.status) return hitResult;
				didSomething = didSomething || hitResult;
			}
			if (moveData.forceStatus) {
				hitResult = target.setStatus(moveData.forceStatus, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.volatileStatus) {
				hitResult = target.addVolatile(moveData.volatileStatus, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.sideCondition) {
				hitResult = target.side.addSideCondition(moveData.sideCondition, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.weather) {
				hitResult = this.setWeather(moveData.weather, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.terrain) {
				hitResult = this.setTerrain(moveData.terrain, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.pseudoWeather) {
				hitResult = this.addPseudoWeather(moveData.pseudoWeather, pokemon, move);
				didSomething = didSomething || hitResult;
			}
			if (moveData.forceSwitch) {
				if (this.canSwitch(target.side)) didSomething = true; // at least defer the fail message to later
			}
			if (moveData.selfSwitch) {
				if (this.canSwitch(pokemon.side)) didSomething = true; // at least defer the fail message to later
			}
			// Hit events
			//   These are like the TryHit events, except we don't need a FieldHit event.
			//   Scroll up for the TryHit event documentation, and just ignore the "Try" part. ;)
			hitResult = null;
			if (move.target === 'all' && !isSelf) {
				if (moveData.onHitField) hitResult = this.singleEvent('HitField', moveData, {}, target, pokemon, move);
			} else if ((move.target === 'foeSide' || move.target === 'allySide') && !isSelf) {
				if (moveData.onHitSide) hitResult = this.singleEvent('HitSide', moveData, {}, target.side, pokemon, move);
			} else {
				if (moveData.onHit) hitResult = this.singleEvent('Hit', moveData, {}, target, pokemon, move);
				if (!isSelf && !isSecondary) {
					this.runEvent('Hit', target, pokemon, move);
				}
				if (moveData.onAfterHit) hitResult = this.singleEvent('AfterHit', moveData, {}, target, pokemon, move);
			}

			if (!hitResult && !didSomething && !moveData.self && !moveData.selfdestruct) {
				if (!isSelf && !isSecondary) {
					if (hitResult === false || didSomething === false) this.add('-fail', target);
				}
				this.debug('move failed because it did nothing');
				return false;
			}
		}
		if (moveData.self) {
			let selfRoll;
			if (!isSecondary && moveData.self.boosts) selfRoll = this.random(100);
			// This is done solely to mimic in-game RNG behaviour. All self drops have a 100% chance of happening but still grab a random number.
			if (typeof moveData.self.chance === 'undefined' || selfRoll < moveData.self.chance) {
				this.moveHit(pokemon, pokemon, move, moveData.self, isSecondary, true);
			}
		}
		if (moveData.secondaries) {
			let secondaryRoll;
			let secondaries = this.runEvent('ModifySecondaries', target, pokemon, moveData, moveData.secondaries.slice());
			for (let i = 0; i < secondaries.length; i++) {
				secondaryRoll = this.random(100);
				if (typeof secondaries[i].chance === 'undefined' || secondaryRoll < secondaries[i].chance) {
					// mod for automagic start
					let flag = true;
					let canSetStatus = function (status, target, pokemon) {
						if (target.status) return false;
						let cantStatus = {
							brn: ['Fire', 'comatose', 'waterveil', 'waterbubble'],
							frz: ['Ice', 'comatose', 'magmaarmor'],
							par: ['Electric', 'comatose', 'limber'],
							psn: ['comatose', 'immunity'],
							slp: ['comatose', 'insomnia', 'vitalspirit'],
							tox: ['comatose', 'immunity'],
						};
						if (target.hasType(['Poison', 'Steel']) && (status === 'psn' || status === 'tox')) {
							if (pokemon.hasAbility('corrosion')) {
								return true;
							} else {
								return false;
							}
						}
						if (target.hasType(cantStatus[status][0])) return false;
						if (move.ignoreAbility) return true;
						if (target.hasAbility('leafguard') && this.isWeather(['sunnyday', 'desolateland'])) return false;
						if (target.hasAbility('shieldsdown') && target.template.speciesid === 'miniormeteor') return false;
						if (target.hasAbility(cantStatus[status])) return false;
						return true;
					};
					if (moveData.secondary.status) flag = canSetStatus(moveData.secondary.status, target, pokemon);
					if (moveData.secondary.volatileStatus) flag = !(moveData.secondary.volatileStatus in target.volatiles);
					if (moveData.secondary.volatileStatus === 'flinch') flag = flag && target.activeTurns && !target.moveThisTurn;
					this.moveHit(target, pokemon, move, secondaries[i], true, isSelf);
					if (moveData.secondary.self && moveData.secondary.self.boosts) {
						Object.keys(moveData.secondary.self.boosts).forEach(boost => {
							if (pokemon.boosts[boost] === 6) flag = false;
						});
					} else {
						flag = flag && target && !(target.hp === undefined || target.hp <= 0);
					}
					if (moveData.target !== 'self' && moveData.secondary.boosts) {
						let cantLower = {
							'atk': ['clearbody', 'fullmetalbody', 'hypercutter', 'whitesmoke'],
							'def': ['bigpecks', 'clearbody', 'fullmetalbody', 'whitesmoke'],
							'spa': ['clearbody', 'fullmetalbody', 'whitesmoke'],
							'spd': ['clearbody', 'fullmetalbody', 'whitesmoke'],
							'spe': ['clearbody', 'fullmetalbody', 'whitesmoke'],
							'accuracy': ['clearbody', 'fullmetalbody', 'keeneye', 'whitesmoke'],
						};
						for (let k in moveData.secondary.boosts) {
							if (target.boosts[k] === -6) {
								flag = false;
								continue;
							}
							if (moveData.secondary.boosts[k] < 0 && target.hasAbility(cantLower[k]) && !move.ignoreAbility) {
								flag = false;
								break;
							}
						}
					}
					if (pokemon.hasAbility('sheerforce')) flag = false;
					if (target && target.hasAbility('shielddust') && !move.ignoreAbility && !move.secondary.self.boosts) {
						flag = false;
					}
					if (flag) this.runEvent('AfterSecondaryEffect', target, pokemon, moveData);
					// mod for automagic end
				}
			}
		}
		if (target && target.hp > 0 && pokemon.hp > 0 && moveData.forceSwitch && this.canSwitch(target.side)) {
			hitResult = this.runEvent('DragOut', target, pokemon, move);
			if (hitResult) {
				target.forceSwitchFlag = true;
			} else if (hitResult === false && move.category === 'Status') {
				this.add('-fail', target);
			}
		}
		if (move.selfSwitch && pokemon.hp) {
			pokemon.switchFlag = move.selfSwitch;
		}
		return damage;
	},
};
<|endoftext|>


<commit_before>exports.command = 'modReload';

const Discord = require('discord.js');
const mod = require('../../modules.js');
const Config = require('../../config.json');

exports.modReload = {
	run: function(bot,suffix,msg) {
		if(msg.author.id === Config.ownerID){

			mod.reload()
			const embed = new Discord.RichEmbed()
				.setTitle('Module Reload')
				.setDescription(`Modules Reloaded! Now Running ${mod.commandCount} modules!`)
				.setFooter('BaconHawkJS')
				.setTimestamp()
				.setColor(0xbb0000);

			msg.channel.sendEmbed(embed)
		} else {
			const embed = new Discord.RichEmbed()
			msg.channel.sendEmbed(embed.setTimestamp().setTitle('Module Reload').addField('Error:', 'No Permission!').setColor(0xff0000).setFooter('BaconHawkJS'));
		}
	}
}<commit_msg>Delete modReload.js<commit_after><|endoftext|>


<commit_before>exports.BattlePokedex = {
rhydon:{num:112,species:"Rhydon",types:["Ground","Rock"],baseStats:{hp:210,atk:260,def:240,spa:90,spd:90,spe:80},abilities:{0:"Lightningrod",1:"Rock Head",DW:"Reckless"},heightm:1.9,weightkg:120,color:"Gray",prevo:"rhyhorn",evos:["rhyperior"],evoLevel:42,eggGroups:["Monster","Ground"]},

};
<commit_msg>Update pokedex.js<commit_after>exports.BattlePokedex = {
rhydon:{num:112,species:"Rhydon",types:["Ground","Rock"],baseStats:{hp:210,atk:260,def:240,spa:90,spd:90,spe:80},abilities:{0:"Lightningrod",1:"Rock Head",DW:"Reckless"},heightm:1.9,weightkg:120,color:"Gray",prevo:"rhyhorn",evos:["rhyperior"],evoLevel:42,eggGroups:["Monster","Ground"]}
};
<|endoftext|>


<commit_before>exports.BattleScripts = {
	init: function () {
		this.modData('Pokedex', 'archeops').abilities['1'] = 'Vital Spirit';
		this.modData('Pokedex', 'porygonz').types = ['Normal', 'Ghost'];
		this.modData('Pokedex', 'weezing').types = ['Poison', 'Steel'];
		this.modData('Pokedex', 'moltres').abilities['1'] = 'Magic Guard';
		this.modData('Pokedex', 'abomasnowmega').abilities['0'] = 'Technician';
		this.modData('Pokedex', 'cradily').abilities['1'] = 'Sand Stream';
		this.modData('Pokedex', 'froslass').abilities['1'] = 'Prankster';
		this.modData('Learnsets', 'absol').learnset.partingshot = ['6T'];
		this.modData('Pokedex', 'goodra').abilities['1'] = 'Protean';
		this.modData('Pokedex', 'entei').abilities['1'] = 'Defiant';
		this.modData('Pokedex', 'milotic').abilities['H'] = 'Multiscale';
		this.modData('Pokedex', 'empoleon').abilities['1'] = 'Lightning Rod';
		this.modData('Learnsets', 'reuniclus').learnset.voltswitch = ['6T'];
		this.modData('Pokedex', 'steelixmega').abilities['0'] = 'Arena Trap';
		this.modData('Pokedex', 'audinomega').abilities['0'] = 'Simple';
		this.modData('Learnsets', 'ampharos').learnset.wish = ['6T'];
		this.modData('Pokedex', 'absolmega').types = ['Dark', 'Fairy'];
		this.modData('Pokedex', 'weavile').abilities['1'] = 'Moxie';
		this.modData('Learnsets', 'pangoro').learnset.suckerpunch = ['6T'];
		this.modData('Pokedex', 'rotomfan').types = ['Electric', 'Steel'];
		this.modData('Learnsets', 'rotomfan').learnset.flashcannon = this.data.Learnsets.rotomfan.learnset.airslash;
		this.modData('Learnsets', 'rotomfan').learnset.airslash = null;
		this.modData('Learnsets', 'mantine').learnset.roost = ['6T'];
		this.modData('Learnsets', 'pidgeot').learnset.focusblast = ['6T'];
		this.modData('Pokedex', 'granbull').abilities['1'] = 'Fur Coat';
		this.modData('Pokedex', 'aggronmega').types = ['Steel', 'Dragon'];
		this.modData('Learnsets', 'floatzel').learnset.bellydrum = ['6T'];
		this.modData('Pokedex', 'forretress').abilities['1'] = 'Water Absorb';
		this.modData('Learnsets', 'bronzong').learnset.recover = ['6T'];
		this.modData('Learnsets', 'sandslash').learnset.thousandarrows = ['6T'];
		this.modData('Learnsets', 'braviary').learnset.extremespeed = ['6T'];
		this.modData('Pokedex', 'cacturne').abilities['1'] = 'Sand Rush';
		this.modData('Pokedex', 'beedrillmega').types = ['Bug', 'Ground'];
	}
};
<commit_msg>Theorymon: Add new changes<commit_after>exports.BattleScripts = {
	init: function () {
		this.modData('Pokedex', 'archeops').abilities['1'] = 'Vital Spirit';
		this.modData('Pokedex', 'porygonz').types = ['Normal', 'Ghost'];
		this.modData('Pokedex', 'weezing').types = ['Poison', 'Steel'];
		this.modData('Pokedex', 'moltres').abilities['1'] = 'Magic Guard';
		this.modData('Pokedex', 'abomasnowmega').abilities['0'] = 'Technician';
		this.modData('Pokedex', 'cradily').abilities['1'] = 'Sand Stream';
		this.modData('Pokedex', 'froslass').abilities['1'] = 'Prankster';
		this.modData('Learnsets', 'absol').learnset.partingshot = ['6T'];
		this.modData('Pokedex', 'goodra').abilities['1'] = 'Protean';
		this.modData('Pokedex', 'entei').abilities['1'] = 'Defiant';
		this.modData('Pokedex', 'milotic').abilities['H'] = 'Multiscale';
		this.modData('Pokedex', 'empoleon').abilities['1'] = 'Lightning Rod';
		this.modData('Learnsets', 'reuniclus').learnset.voltswitch = ['6T'];
		this.modData('Pokedex', 'steelixmega').abilities['0'] = 'Arena Trap';
		this.modData('Pokedex', 'audinomega').abilities['0'] = 'Simple';
		this.modData('Learnsets', 'ampharos').learnset.wish = ['6T'];
		this.modData('Pokedex', 'absolmega').types = ['Dark', 'Fairy'];
		this.modData('Pokedex', 'weavile').abilities['1'] = 'Moxie';
		this.modData('Learnsets', 'pangoro').learnset.suckerpunch = ['6T'];
		this.modData('Pokedex', 'rotomfan').types = ['Electric', 'Steel'];
		this.modData('Learnsets', 'rotomfan').learnset.flashcannon = this.data.Learnsets.rotomfan.learnset.airslash;
		this.modData('Learnsets', 'rotomfan').learnset.airslash = null;
		this.modData('Learnsets', 'mantine').learnset.roost = ['6T'];
		this.modData('Learnsets', 'pidgeot').learnset.focusblast = ['6T'];
		this.modData('Pokedex', 'granbull').abilities['1'] = 'Fur Coat';
		this.modData('Pokedex', 'aggronmega').types = ['Steel', 'Dragon'];
		this.modData('Learnsets', 'floatzel').learnset.bellydrum = ['6T'];
		this.modData('Pokedex', 'forretress').abilities['1'] = 'Water Absorb';
		this.modData('Learnsets', 'bronzong').learnset.recover = ['6T'];
		this.modData('Learnsets', 'sandslash').learnset.thousandarrows = ['6T'];
		this.modData('Learnsets', 'braviary').learnset.extremespeed = ['6T'];
		this.modData('Pokedex', 'cacturne').abilities['1'] = 'Sand Rush';
		this.modData('Pokedex', 'beedrillmega').types = ['Bug', 'Ground'];
		this.modData('Pokedex', 'swanna').abilities['1'] = 'Gale Wings';
		this.modData('Pokedex', 'kyurem').abilities['1'] = 'Sheer Force';
	}
};
<|endoftext|>


<commit_before>
var datawire = angular.module('datawire', [], function($routeProvider, $locationProvider) {
  $routeProvider.when('/profile', {
    templateUrl: '/static/partials/profile.html',
    controller: ProfileCtrl,
    accessPolicy: 'user'
  });

  $routeProvider.when('/feed', {
    templateUrl: '/static/partials/feed.html',
    controller: FeedCtrl,
    accessPolicy: 'user'
  });

  $routeProvider.when('/', {
    templateUrl: '/static/partials/home.html',
    controller: HomeCtrl
  });

  $routeProvider.otherwise({
    redirectTo: '/'
  });

  $locationProvider.html5Mode(true);
});

datawire.directive('external', function ($window) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                $window.location.href = attrs.external;
            });
        }
    };
});

Handlebars.registerHelper('entity', function(text) {
    text = Handlebars.Utils.escapeExpression(text);
    var result = '' + text + '';
    return new Handlebars.SafeString(result);
});

datawire.factory('identity', function($http) {
    var dfd = $http.get('/api/1/sessions');
    return {
        session: dfd.success,
        checkSession: function(callback) {
            dfd.success(function(data) {
                if (!data.logged_in) {
                    callback(data);
                }
            });
        }
    };
});

datawire.factory('services', function($q, $http) {
    var serviceDfds = {};

    function getService(name, callback) {
        if(!serviceDfds[name]) {
            serviceDfds[name] = $http.get('/api/1/services/' + name);
        }
        serviceDfds[name].success(callback);
        return serviceDfds[name];
    }

    function getFrame(ref) {
        $http.get(ref.store_uri).success(function(frame) {
            getService(frame.service, function(service) {
                ref.event = _.find(service.events, function(e) {
                    return e.key == frame.event;
                });
                if(ref.event.tmpl===undefined) {
                    ref.event.tmpl = Handlebars.compile(ref.event.template);
                }
                ref.service = service;
                ref.data = frame.data;
                ref.message = ref.event.tmpl(frame.data);
            });
        });
    }

    return {
        getService: getService,
        getFrame: getFrame
    };
});

function FeedCtrl($scope, $routeParams, $http, services) {
    $scope.tableObject = function(obj) {
        var table = {};
        angular.forEach(obj, function(v, k) {
            if (v && v.length) {
                table[k] = v;
            }
        });
        return table;
    };

    $http.get('/api/1/frames?limit=20').success(function(data) {
        $scope.frames = data.results;
        angular.forEach($scope.frames, function(frame, i) {
            services.getFrame(frame);
        });
    });
}

function EntityCtrl($scope, $routeParams, $http, identity) {
    $scope._new = {};
    $scope.entities = {};

    $http.get('/api/1/facets').success(function(data) {
        $scope.facets = data.results;
        angular.forEach(data.results, function(facet) {
            loadFacetEntities(facet.key);
        });
    });

    function loadFacetEntities(facet_name) {
        identity.session(function(ident) {
            $http.get('/api/1/users/' + ident.user.id + '/entities?facet='+facet_name)
            .success(function(data) {
                $scope.entities[facet_name] = data.results;
            });
        });
    }

    $scope.create = function(facet) {
        data = {facet: facet, text: $scope._new[facet]};
        $scope._new[facet] = '';
        console.log(data);
        $http.post('/api/1/entities', data).success(function(data) {
            $scope.entities[facet].push(data);
        });
    };

    $scope.remove = function(facet, id) {
        $http({method: 'delete', url: '/api/1/entities/' + id}).error(function(data, status) {
            if (status===410) {
                var entities = [];
                angular.forEach($scope.entities[facet], function(entity) {
                    console.log(entity);
                    if (entity.id!==id) entities.push(entity);
                });
                $scope.entities[facet] = entities;
            }
        });
    };
}
<commit_msg>Fix up app.'s and extract a feed service. <commit_after>
var datawire = angular.module('datawire', [], function($routeProvider, $locationProvider) {
  $routeProvider.when('/profile', {
    templateUrl: '/static/partials/profile.html',
    controller: ProfileCtrl,
    accessPolicy: 'user'
  });

  $routeProvider.when('/feed', {
    templateUrl: '/static/partials/feed.html',
    controller: FeedCtrl,
    accessPolicy: 'user'
  });

  $routeProvider.when('/', {
    templateUrl: '/static/partials/home.html',
    controller: HomeCtrl
  });

  $routeProvider.otherwise({
    redirectTo: '/'
  });

  $locationProvider.html5Mode(true);
});

datawire.directive('external', function ($window) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                $window.location.href = attrs.external;
            });
        }
    };
});

Handlebars.registerHelper('entity', function(text) {
    text = Handlebars.Utils.escapeExpression(text);
    var result = '' + text + '';
    return new Handlebars.SafeString(result);
});

datawire.factory('feed', function($http, identity, services) {

    function update(callback) {
        identity.session(function(ident) {
            $http.get('/api/1/users/' + ident.user.id + '/feed').success(function(data) {
                angular.forEach(data.results, function(frame, i) {
                    services.getFrame(frame);
                });
                callback(data);
            });
        });
    }

    return {
        update: update
    };
});

function FeedCtrl($scope, $routeParams, feed) {
    $scope.tableObject = function(obj) {
        var table = {};
        angular.forEach(obj, function(v, k) {
            if (v && v.length) {
                table[k] = v;
            }
        });
        return table;
    };

    feed.update(function(data) {
        $scope.frames = data.results;
    });

}
<|endoftext|>


<commit_before>/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2012 Google Inc.
 * https://blockly.googlecode.com/
 *
 * 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 Variable input field.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.TypedFieldVariable');

goog.require('Blockly.FieldDropdown');
goog.require('Blockly.Msg');
goog.require('Blockly.Variables');
goog.require('Blockly.FieldVariable');

/**
 * Class for a variable's dropdown field.
 * @param {?string} varname The default name for the variable.  If null,
 *     a unique variable name will be generated.
 * @param {Function} opt_changeHandler A function that is executed when a new
 *     option is selected.  Its sole argument is the new option value.  Its
 *     return value is ignored.
 * @extends {Blockly.FieldDropdown}
 * @constructor
 */
Blockly.TypedFieldVariable = function(varname, type, createVar, opt_changeHandler) {
  var changeHandler;
  this.vartype = type;
  this.createVar = createVar;

  this.createVar = false;
  if (typeof createVar === "boolean") {
    this.createVar = createVar;
  };
  if (opt_changeHandler) {
    // Wrap the user's change handler together with the variable rename handler.
    var thisObj = this;
    changeHandler = function(value) {
      var retVal = Blockly.TypedFieldVariable.dropdownChange.call(thisObj, value);
      var newVal;
      if (retVal === undefined) {
        newVal = value;  // Existing variable selected.
      } else if (retVal === null) {
        newVal = thisObj.getValue();  // Abort, no change.
      } else {
        newVal = retVal;  // Variable name entered.
      }
      opt_changeHandler.call(thisObj, newVal);
      return retVal;
    };
  } else {
    changeHandler = Blockly.TypedFieldVariable.dropdownChange;
  }

  Blockly.TypedFieldVariable.superClass_.constructor.call(this,
      Blockly.TypedFieldVariable.dropdownCreate, changeHandler);

  if (varname) {
    this.setValue(varname);
  } else {
    this.setValue(Blockly.Variables.generateUniqueName());
  }
};
goog.inherits(Blockly.TypedFieldVariable, Blockly.FieldDropdown);

/**
 * True if this TypedFieldVariable provides the variable
 * @type {Boolean}
 */
// Blockly.TypedFieldVariable.prototype.createVar = false;

/**
 * Clone this FieldVariable.
 * @return {!Blockly.TypedFieldVariable} The result of calling the constructor again
 *   with the current values of the arguments used during construction.
 */
Blockly.TypedFieldVariable.prototype.clone = function() {
  return new Blockly.TypedFieldVariable(this.getValue(), this.changeHandler_);
};

/**
 * Get the variable's name (use a variableDB to convert into a real name).
 * Unline a regular dropdown, variables are literal and have no neutral value.
 * @return {string} Current text.
 */
Blockly.TypedFieldVariable.prototype.getValue = function() {
  return this.getText();
};

/**
 * Set the variable name.
 * @param {string} text New text.
 */
Blockly.TypedFieldVariable.prototype.setValue = function(text) {
  this.value_ = text;
  this.setText(text);
};

/**
 * Return a sorted list of variable names for variable dropdown menus.
 * Include a special option at the end for creating a new variable name.
 * @return {!Array.<string>} Array of variable names.
 * @this {!Blockly.TypedFieldVariable}
 */
Blockly.TypedFieldVariable.dropdownCreate = function() {
  var variableList = Blockly.Variables.allVariablesOfType(this.vartype);
  // Ensure that the currently selected variable is an option.
  var name = this.getText();
  if (name && variableList.indexOf(name) == -1 && this.createVar) {
    variableList.push(name);
  }
  variableList.sort(goog.string.caseInsensitiveCompare);
  variableList.push(Blockly.Msg.RENAME_VARIABLE);
  if (this.createVar) {
    variableList.push(Blockly.Msg.NEW_VARIABLE);
  }
  // Variables are not language-specific, use the name as both the user-facing
  // text and the internal representation.
  var options = [];
  for (var x = 0; x < variableList.length; x++) {
    options[x] = [variableList[x], variableList[x]];
  }
  return options;
};

/**
 * Event handler for a change in variable name.
 * Special case the 'New variable...' and 'Rename variable...' options.
 * In both of these special cases, prompt the user for a new name.
 * @param {string} text The selected dropdown menu option.
 * @return {null|undefined|string} An acceptable new variable name, or null if
 *     change is to be either aborted (cancel button) or has been already
 *     handled (rename), or undefined if an existing variable was chosen.
 * @this {!Blockly.TypedFieldVariable}
 */
Blockly.TypedFieldVariable.dropdownChange = function(text) {
  function promptName(promptText, defaultText) {
    Blockly.hideChaff();
    var newVar = window.prompt(promptText, defaultText);
    // Merge runs of whitespace.  Strip leading and trailing whitespace.
    // Beyond this, all names are legal.
    return newVar && newVar.replace(/[\s\xa0]+/g, ' ').replace(/^ | $/g, '');
  }
  if (text == Blockly.Msg.RENAME_VARIABLE) {
    var oldVar = this.getText();
    text = promptName(Blockly.Msg.RENAME_VARIABLE_TITLE.replace('%1', oldVar),
                      oldVar);
    if (text) {
      Blockly.Variables.renameVariable(oldVar, text);
    }
    return null;
  } else if (text == Blockly.Msg.NEW_VARIABLE) {
    text = promptName(Blockly.Msg.NEW_VARIABLE_TITLE, '');
    // Since variables are case-insensitive, ensure that if the new variable
    // matches with an existing variable, the new case prevails throughout.
    if (text) {
      Blockly.Variables.renameVariable(text, text);
      return text;
    }
    return null;
  }
  return undefined;
};
<commit_msg>Make sure that the required variables are not undefined<commit_after>/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2012 Google Inc.
 * https://blockly.googlecode.com/
 *
 * 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 Variable input field.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.TypedFieldVariable');

goog.require('Blockly.FieldDropdown');
goog.require('Blockly.Msg');
goog.require('Blockly.Variables');
goog.require('Blockly.FieldVariable');

/**
 * Class for a variable's dropdown field.
 * @param {?string} varname The default name for the variable.  If null,
 *     a unique variable name will be generated.
 * @param {Function} opt_changeHandler A function that is executed when a new
 *     option is selected.  Its sole argument is the new option value.  Its
 *     return value is ignored.
 * @extends {Blockly.FieldDropdown}
 * @constructor
 */
Blockly.TypedFieldVariable = function(varname, type, createVar, opt_changeHandler) {
  var changeHandler;
  if (typeof varname == "undefined") {
    throw new Error("Variable name is undefined.");
  }
  if (typeof type == "undefined") {
    throw new Error("Variable type is undefined.");
  }
  this.vartype = type;
  this.createVar = createVar;

  this.createVar = false;
  if (typeof createVar === "boolean") {
    this.createVar = createVar;
  };
  if (opt_changeHandler) {
    // Wrap the user's change handler together with the variable rename handler.
    var thisObj = this;
    changeHandler = function(value) {
      var retVal = Blockly.TypedFieldVariable.dropdownChange.call(thisObj, value);
      var newVal;
      if (retVal === undefined) {
        newVal = value;  // Existing variable selected.
      } else if (retVal === null) {
        newVal = thisObj.getValue();  // Abort, no change.
      } else {
        newVal = retVal;  // Variable name entered.
      }
      opt_changeHandler.call(thisObj, newVal);
      return retVal;
    };
  } else {
    changeHandler = Blockly.TypedFieldVariable.dropdownChange;
  }

  Blockly.TypedFieldVariable.superClass_.constructor.call(this,
      Blockly.TypedFieldVariable.dropdownCreate, changeHandler);

  if (varname) {
    this.setValue(varname);
  } else {
    this.setValue(Blockly.Variables.generateUniqueName());
  }
};
goog.inherits(Blockly.TypedFieldVariable, Blockly.FieldDropdown);

/**
 * True if this TypedFieldVariable provides the variable
 * @type {Boolean}
 */
// Blockly.TypedFieldVariable.prototype.createVar = false;

/**
 * Clone this FieldVariable.
 * @return {!Blockly.TypedFieldVariable} The result of calling the constructor again
 *   with the current values of the arguments used during construction.
 */
Blockly.TypedFieldVariable.prototype.clone = function() {
  return new Blockly.TypedFieldVariable(this.getValue(), this.changeHandler_);
};

/**
 * Get the variable's name (use a variableDB to convert into a real name).
 * Unline a regular dropdown, variables are literal and have no neutral value.
 * @return {string} Current text.
 */
Blockly.TypedFieldVariable.prototype.getValue = function() {
  return this.getText();
};

/**
 * Set the variable name.
 * @param {string} text New text.
 */
Blockly.TypedFieldVariable.prototype.setValue = function(text) {
  this.value_ = text;
  this.setText(text);
};

/**
 * Return a sorted list of variable names for variable dropdown menus.
 * Include a special option at the end for creating a new variable name.
 * @return {!Array.<string>} Array of variable names.
 * @this {!Blockly.TypedFieldVariable}
 */
Blockly.TypedFieldVariable.dropdownCreate = function() {
  var variableList = Blockly.Variables.allVariablesOfType(this.vartype);
  // Ensure that the currently selected variable is an option.
  var name = this.getText();
  if (name && variableList.indexOf(name) == -1 && this.createVar) {
    variableList.push(name);
  }
  variableList.sort(goog.string.caseInsensitiveCompare);
  variableList.push(Blockly.Msg.RENAME_VARIABLE);
  if (this.createVar) {
    variableList.push(Blockly.Msg.NEW_VARIABLE);
  }
  // Variables are not language-specific, use the name as both the user-facing
  // text and the internal representation.
  var options = [];
  for (var x = 0; x < variableList.length; x++) {
    options[x] = [variableList[x], variableList[x]];
  }
  return options;
};

/**
 * Event handler for a change in variable name.
 * Special case the 'New variable...' and 'Rename variable...' options.
 * In both of these special cases, prompt the user for a new name.
 * @param {string} text The selected dropdown menu option.
 * @return {null|undefined|string} An acceptable new variable name, or null if
 *     change is to be either aborted (cancel button) or has been already
 *     handled (rename), or undefined if an existing variable was chosen.
 * @this {!Blockly.TypedFieldVariable}
 */
Blockly.TypedFieldVariable.dropdownChange = function(text) {
  function promptName(promptText, defaultText) {
    Blockly.hideChaff();
    var newVar = window.prompt(promptText, defaultText);
    // Merge runs of whitespace.  Strip leading and trailing whitespace.
    // Beyond this, all names are legal.
    return newVar && newVar.replace(/[\s\xa0]+/g, ' ').replace(/^ | $/g, '');
  }
  if (text == Blockly.Msg.RENAME_VARIABLE) {
    var oldVar = this.getText();
    text = promptName(Blockly.Msg.RENAME_VARIABLE_TITLE.replace('%1', oldVar),
                      oldVar);
    if (text) {
      Blockly.Variables.renameVariable(oldVar, text);
    }
    return null;
  } else if (text == Blockly.Msg.NEW_VARIABLE) {
    text = promptName(Blockly.Msg.NEW_VARIABLE_TITLE, '');
    // Since variables are case-insensitive, ensure that if the new variable
    // matches with an existing variable, the new case prevails throughout.
    if (text) {
      Blockly.Variables.renameVariable(text, text);
      return text;
    }
    return null;
  }
  return undefined;
};
<|endoftext|>


<commit_before>/*jshint node:true*/
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    fingerprint: {
      enabled: false
    }
  });

  // Use `app.import` to add additional libraries to the generated
  // output files.
  //
  // If you need to use different assets in different
  // environments, specify an object as the first parameter. That
  // object's keys should be the environment name and the values
  // should be the asset to use in that environment.
  //
  // If the library that you are including contains AMD or ES6
  // modules that you would like to import into your application
  // please specify an object with the list of modules as keys
  // along with the exports of each module as its value.

  // bootstrap
  app.import('bower_components/bootstrap/dist/css/bootstrap.css');
  app.import('bower_components/bootstrap/dist/js/bootstrap.js');

  // bootswatch
  app.import('bower_components/bootswatch/cosmo/bootstrap.css');

  // jQuery Countdown
  app.import('bower_components/jquery.countdown/dist/jquery.countdown.js');

  // webcam
  app.import('bower_components/webcamjs/webcam.js');

  return app.toTree();
};
<commit_msg>move to yeti theme, which is a bit cleaner looking<commit_after>/*jshint node:true*/
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    fingerprint: {
      enabled: false
    }
  });

  // Use `app.import` to add additional libraries to the generated
  // output files.
  //
  // If you need to use different assets in different
  // environments, specify an object as the first parameter. That
  // object's keys should be the environment name and the values
  // should be the asset to use in that environment.
  //
  // If the library that you are including contains AMD or ES6
  // modules that you would like to import into your application
  // please specify an object with the list of modules as keys
  // along with the exports of each module as its value.

  // bootstrap
  app.import('bower_components/bootstrap/dist/css/bootstrap.css');
  app.import('bower_components/bootstrap/dist/js/bootstrap.js');

  // bootswatch
  app.import('bower_components/bootswatch/yeti/bootstrap.css');

  // jQuery Countdown
  app.import('bower_components/jquery.countdown/dist/jquery.countdown.js');

  // webcam
  app.import('bower_components/webcamjs/webcam.js');

  return app.toTree();
};
<|endoftext|>


<commit_before>/*
options = {
    onPlayerConnect: function()
    onPlayerDisconnect: function (),
    onPlayerReconnect: function (),
    onPlayerUpdate: function (data),
    onPlayerRemove: function (id),
    onPing: function (data),
    onUpdatePlayerPhysics: function (state, inputs),
    onInterpolation: function(currentState, previousState, targetState, amount)
    logging: true,
    clientSidePrediction: true,
    interpolation: true,
    pingInterval: 2000
}
*/

window.GarageServerIO = (function (window, socketio) {

    function StateController () {
        this.state = {};
        this.time;
        this.frameTime = new Date().getTime();
        this.delta;
        this.playerId;
    }
    StateController.prototype = {
        setTime: function (serverTime, delay) {
            this.time = serverTime - delay / 2;
        }
    };

    function InputController () {
        this.inputs = [];
        this.sequenceNumber = 1;
    }
    InputController.prototype = {
        any: function () {
            return this.inputs.length > 0;
        },
        addInput: function (input) {
            this.sequenceNumber += 1;
            this.inputs.push({ input: input, seq: this.sequenceNumber });
        },
        removeUpToSequence: function (seq) {
            for (var i = 0; i < this.inputs.length; i ++) {
                if (this.inputs[i].seq == seq) {
                    this.inputs.splice(0, i + 1);
                    break;
                }
            }
        }
    };

    function Player (id) {
        this.updates = [];
        this.id = id;
    }
    Player.prototype = {
        anyUpdates: function () {
            return this.updates.length > 0;
        },
        addUpate: function (state, seq, time) {
            this.updates.push({ state: state, seq: seq, time: time });
            if (this.updates.length > 60) {
                this.updates.updates.splice(0, 1);
            }
        },
        getLatestUpdate: function () {
            return this.updates[this.updates.length - 1];
        },
        processState: function (playerState, time) {
            var updateFound = false;
            for (var i = 0; i < this.updates.length; i ++) {
                if (this.updates[i].seq === playerState.seq) {
                    this.updates[i].state = playerState.state;
                    updateFound = true;
                    break;
                }
            }
            if (!updateFound) {
                this.updates.push({ state: playerState.state, seq: playerState.seq, time: time });
                if (this.updates.length > 60) {
                    this.updates.splice(0, 1);
                }
            }
        },
        getPositions: function (time, frameTime) {
            var positions = {}, range, difference, amount;
            for (var i = 0; i < this.updates.length; i ++) {
                var previous = this.updates[i];
                var target = this.updates[i + 1];

                if(previous && target && time > previous.time && time < target.time) {
                    var frameDiff = new Date().getTime() - frameTime;
                    range = target.time - previous.time;
                    difference = time - previous.time + frameDiff;
                    amount = parseFloat((difference / range).toFixed(3));
                    positions.previousState = previous.state;
                    positions.targetState = target.state;
                    positions.amount = amount;
                    break;
                }
            }
            return positions;
        }
    };

    function PlayerController () {
        this.players = [];
    }
    PlayerController.prototype = {
        addPlayer: function (id) {
            var player = new Player(id);
            this.players.push(player);
            return player;
        },
        removePlayer: function (id) {
            for (var i = 0; i < this.players.length; i ++) {
                this.players.splice(i, 1);
                return;
            }
        },
        forEach: function (callback) {
            for (var i = 0; i < this.players.length; i ++) {
                callback(this.players[i]);
            }
        }
    };

    var _io = socketio,
        _socket = null,
        _options = null,
        _pingDelay = 100,
        _stateController = new StateController(),
        _inputController = new InputController(),
        _playerController = new PlayerController(),

        connectToGarageServer = function (path, opts) {
            _options = opts;
            _socket = _io.connect(path + '/garageserver.io');
            registerSocketEvents();
            registerPinger();
        },

        registerSocketEvents = function () {
            _socket.on('connect', function () {
                _stateController.playerId = _socket.id;
                if (_options.onPlayerConnect) {
                    _options.onPlayerConnect();
                }
            });
            _socket.on('disconnect', function () {
                if (_options.onPlayerDisconnect) {
                    _options.onPlayerDisconnect();
                }
            });
            _socket.on('reconnect', function () {
                if (_options.onPlayerReconnect) {
                    _options.onPlayerReconnect();
                }
            });
            _socket.on('update', function(data) {
                updateState(data);
            });
            _socket.on('ping', function(data) {
                _pingDelay = new Date().getTime() - data;
                if (_options.logging) {
                    console.log('garageserver.io:: socket ping delay ' + _pingDelay);
                }
            });
            _socket.on('removePlayer', function(id) {
                removePlayer(id);
                if (_options.logging) {
                    console.log('garageserver.io:: socket removePlayer ' + id);
                }
            });
        },

        registerPinger = function () {
            var interval = 2000;
            if (_options.pingInterval) {
                interval = _options.pingInterval;
            }
            setInterval(function (){
                _socket.emit('ping', new Date().getTime());
            }, interval);
        },

        getPlayerId = function () {
            return _stateController.playerId;
        },

        setPlayerState = function (state) {
            _socket.emit('state', state);
        },

        removePlayer = function (id) {
            _playerController.removePlayer(id);

            if (_options.onPlayerRemove) {
                _options.onPlayerRemove(id);
            }
        },

        addPlayerInput = function (clientInput) {
            _inputController.addInput(clientInput);

            if (_options.clientSidePrediction && _options.onUpdatePlayerPhysics) {
                _stateController.state = _options.onUpdatePlayerPhysics(_stateController.state, [{ input: clientInput }]);
            }
            _socket.emit('input', { input: clientInput, seq: _inputController.sequenceNumber });
        },

        updateState = function (data) {
            _stateController.setTime(data.time, _pingDelay);
            _stateController.frameTime = new Date().getTime();
            _stateController.delta = data.delta;

            updatePlayerState(data);
            updateEntityState(data);
        },

        updatePlayerState = function (data) {
            var playerFound = false,
                stateIdx = 0,
                playerState;

            for(stateIdx = 0; stateIdx < data.playerStates.length; stateIdx ++) {
                playerFound = false;
                playerState = data.playerStates[stateIdx];

                if (_socket.socket.sessionid === playerState.id) {
                    _stateController.state = playerState.state;
                    _inputController.removeUpToSequence(playerState.seq);

                    if (_options.clientSidePrediction && _inputController.any()) {
                        _stateController.state = _options.onUpdatePlayerPhysics(_stateController.state, _inputController.inputs);
                    }
                } else {
                    _playerController.forEach(function (player) {
                        if (player.id === playerState.id) {
                            playerFound = true;
                            player.processState(playerState, data.time);
                        }
                        return;
                    });
                    if (!playerFound) {
                        var newPlayer = _playerController.addPlayer(playerState.id);
                        newPlayer.addUpate(playerState.state, playerState.seq, data.time);
                    }
                }

                if (_options.onPlayerUpdate) {
                    _options.onPlayerUpdate(playerState);
                }
            }
        },

        updateEntityState = function (data) {

        },

        getPlayerStates = function (stateCallback) {
            _playerController.forEach(function (player) {
                if (player.anyUpdates()) {
                    var latestUpdate = player.getLatestUpdate();

                    if (_options.interpolation && _options.onInterpolation) {
                        var positions = player.getPositions(_stateController.time, _stateController.frameTime);
                        if (positions.previousState && positions.targetState) {
                            stateCallback(_options.onInterpolation(latestUpdate.state, positions.previousState, positions.targetState, positions.amount));
                        }
                        else {
                            stateCallback(latestUpdate.state);
                        }
                    } else {
                        stateCallback(latestUpdate.state);
                    }
                }
            });
            stateCallback(_stateController.state);
        };

    return {
        connectToGarageServer: connectToGarageServer,
        addPlayerInput: addPlayerInput,
        getPlayerStates: getPlayerStates,
        getPlayerId: getPlayerId,
        setPlayerState: setPlayerState
    };

}) (window, io);<commit_msg>Code cleanup<commit_after>/*
options = {
    onPlayerConnect: function()
    onPlayerDisconnect: function (),
    onPlayerReconnect: function (),
    onPlayerUpdate: function (data),
    onPlayerRemove: function (id),
    onPing: function (data),
    onUpdatePlayerPhysics: function (state, inputs),
    onInterpolation: function(currentState, previousState, targetState, amount)
    logging: true,
    clientSidePrediction: true,
    interpolation: true,
    pingInterval: 2000
}
*/

window.GarageServerIO = (function (window, socketio) {

    function StateController () {
        this.state = {};
        this.time;
        this.frameTime = new Date().getTime();
        this.delta;
        this.playerId;
    }
    StateController.prototype = {
        setTime: function (serverTime, delay) {
            this.time = serverTime - delay / 2;
        }
    };

    function InputController () {
        this.inputs = [];
        this.sequenceNumber = 1;
    }
    InputController.prototype = {
        any: function () {
            return this.inputs.length > 0;
        },
        addInput: function (input) {
            this.sequenceNumber += 1;
            this.inputs.push({ input: input, seq: this.sequenceNumber });
        },
        removeUpToSequence: function (seq) {
            for (var i = 0; i < this.inputs.length; i ++) {
                if (this.inputs[i].seq == seq) {
                    this.inputs.splice(0, i + 1);
                    break;
                }
            }
        }
    };

    function Player (id) {
        this.updates = [];
        this.id = id;
    }
    Player.prototype = {
        anyUpdates: function () {
            return this.updates.length > 0;
        },
        addUpate: function (state, seq, time) {
            this.updates.push({ state: state, seq: seq, time: time });
            if (this.updates.length > 60) {
                this.updates.updates.splice(0, 1);
            }
        },
        getLatestUpdate: function () {
            return this.updates[this.updates.length - 1];
        },
        processState: function (playerState, time) {
            var updateFound = false;
            for (var i = 0; i < this.updates.length; i ++) {
                if (this.updates[i].seq === playerState.seq) {
                    this.updates[i].state = playerState.state;
                    updateFound = true;
                    break;
                }
            }
            if (!updateFound) {
                this.updates.push({ state: playerState.state, seq: playerState.seq, time: time });
                if (this.updates.length > 60) {
                    this.updates.splice(0, 1);
                }
            }
        },
        getPositions: function (time, frameTime) {
            var positions = {}, range, difference, amount;
            for (var i = 0; i < this.updates.length; i ++) {
                var previous = this.updates[i];
                var target = this.updates[i + 1];

                if(previous && target && time > previous.time && time < target.time) {
                    var frameDiff = new Date().getTime() - frameTime;
                    range = target.time - previous.time;
                    difference = time - previous.time + frameDiff;
                    amount = parseFloat((difference / range).toFixed(3));
                    positions.previousState = previous.state;
                    positions.targetState = target.state;
                    positions.amount = amount;
                    break;
                }
            }
            return positions;
        }
    };

    function PlayerController () {
        this.players = [];
    }
    PlayerController.prototype = {
        addPlayer: function (id) {
            var player = new Player(id);
            this.players.push(player);
            return player;
        },
        removePlayer: function (id) {
            for (var i = 0; i < this.players.length; i ++) {
                this.players.splice(i, 1);
                return;
            }
        },
        forEach: function (callback) {
            for (var i = 0; i < this.players.length; i ++) {
                callback(this.players[i]);
            }
        }
    };

    var _io = socketio,
        _socket = null,
        _options = null,
        _pingDelay = 100,
        _stateController = new StateController(),
        _inputController = new InputController(),
        _playerController = new PlayerController(),

        connectToGarageServer = function (path, opts) {
            _options = opts;
            _socket = _io.connect(path + '/garageserver.io');
            registerSocketEvents();
            registerPinger();
        },

        registerSocketEvents = function () {
            _socket.on('connect', function () {
                _stateController.playerId = _socket.id;
                if (_options.onPlayerConnect) {
                    _options.onPlayerConnect();
                }
            });
            _socket.on('disconnect', function () {
                if (_options.onPlayerDisconnect) {
                    _options.onPlayerDisconnect();
                }
            });
            _socket.on('reconnect', function () {
                if (_options.onPlayerReconnect) {
                    _options.onPlayerReconnect();
                }
            });
            _socket.on('update', function(data) {
                updateState(data);
            });
            _socket.on('ping', function(data) {
                _pingDelay = new Date().getTime() - data;
                if (_options.logging) {
                    console.log('garageserver.io:: socket ping delay ' + _pingDelay);
                }
            });
            _socket.on('removePlayer', function(id) {
                removePlayer(id);
                if (_options.logging) {
                    console.log('garageserver.io:: socket removePlayer ' + id);
                }
            });
        },

        registerPinger = function () {
            var interval = 2000;
            if (_options.pingInterval) {
                interval = _options.pingInterval;
            }
            setInterval(function (){
                _socket.emit('ping', new Date().getTime());
            }, interval);
        },

        getPlayerId = function () {
            return _stateController.playerId;
        },

        setPlayerState = function (state) {
            _socket.emit('state', state);
        },

        removePlayer = function (id) {
            _playerController.removePlayer(id);

            if (_options.onPlayerRemove) {
                _options.onPlayerRemove(id);
            }
        },

        addPlayerInput = function (clientInput) {
            _inputController.addInput(clientInput);

            if (_options.clientSidePrediction && _options.onUpdatePlayerPhysics) {
                _stateController.state = _options.onUpdatePlayerPhysics(_stateController.state, [{ input: clientInput }]);
            }
            _socket.emit('input', { input: clientInput, seq: _inputController.sequenceNumber });
        },

        updateState = function (data) {
            _stateController.setTime(data.time, _pingDelay);
            _stateController.frameTime = new Date().getTime();
            _stateController.delta = data.delta;

            updatePlayerState(data);
            updateEntityState(data);
        },

        updatePlayerState = function (data) {
            var playerFound = false,
                stateIdx = 0,
                playerState;

            for(stateIdx = 0; stateIdx < data.playerStates.length; stateIdx ++) {
                playerFound = false;
                playerState = data.playerStates[stateIdx];

                if (_socket.socket.sessionid === playerState.id) {
                    _stateController.state = playerState.state;
                    _inputController.removeUpToSequence(playerState.seq);

                    if (_options.clientSidePrediction && _inputController.any()) {
                        _stateController.state = _options.onUpdatePlayerPhysics(_stateController.state, _inputController.inputs);
                    }
                } else {
                    _playerController.forEach(function (player) {
                        if (player.id === playerState.id) {
                            playerFound = true;
                            player.processState(playerState, data.time);
                        }
                        return;
                    });
                    if (!playerFound) {
                        var newPlayer = _playerController.addPlayer(playerState.id);
                        newPlayer.addUpate(playerState.state, playerState.seq, data.time);
                    }
                }

                if (_options.onPlayerUpdate) {
                    _options.onPlayerUpdate(playerState);
                }
            }
        },

        updateEntityState = function (data) {

        },

        getPlayerStatesCurrent = function (stateCallback) {
            _playerController.forEach(function (player) {
                if (player.anyUpdates()) {
                    stateCallback(player.getLatestUpdate());
                }
            });
        },

        getPlayerStatesInterpolated = function (stateCallback) {
            _playerController.forEach(function (player) {
                if (player.anyUpdates()) {
                    var latestUpdate = player.getLatestUpdate(),
                        positions = player.getPositions(_stateController.time, _stateController.frameTime);
                    if (positions.previousState && positions.targetState) {
                        stateCallback(_options.onInterpolation(latestUpdate.state, positions.previousState, positions.targetState, positions.amount));
                    }
                    else {
                        stateCallback(latestUpdate.state);
                    }
                }
            });
        },

        getPlayerStates = function (stateCallback) {
            if(_options.interpolation && _options.onInterpolation) {
                getPlayerStatesInterpolated(stateCallback);
            }
            else {
                getPlayerStatesCurrent(stateCallback);
            }
            stateCallback(_stateController.state);
        };

    return {
        connectToGarageServer: connectToGarageServer,
        addPlayerInput: addPlayerInput,
        getPlayerStates: getPlayerStates,
        getPlayerId: getPlayerId,
        setPlayerState: setPlayerState
    };

}) (window, io);<|endoftext|>


<commit_before>module.exports = function (grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    src: {
      js: ['<%= pkg.config.jsPath %>*.js'],
      html: ['src/main/resources/angularjs-partials/*.html']
    },
    html2js: {
      templates: {
        options: {
          base: 'src/main/resources/angularjs-partials',
          module: 'io.wcm.caconfig.templates'
        },
        src: [ '<%= src.html %>' ],
        dest: '<%= pkg.config.jsPath %>templates.module.js'
      }
    },
    watch: {
      html: {
        files: ['src/main/resources/angularjs-partials/*.html'],
        tasks: ['html2js:templates']
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-html2js');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.registerTask('build', function() {
    grunt.task.run('html2js:templates');
  });
};
<commit_msg>WCON-20 - add default grunt task<commit_after>module.exports = function (grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    src: {
      js: ['<%= pkg.config.jsPath %>*.js'],
      html: ['src/main/resources/angularjs-partials/*.html']
    },
    html2js: {
      templates: {
        options: {
          base: 'src/main/resources/angularjs-partials',
          module: 'io.wcm.caconfig.templates'
        },
        src: [ '<%= src.html %>' ],
        dest: '<%= pkg.config.jsPath %>templates.module.js'
      }
    },
    watch: {
      html: {
        files: ['src/main/resources/angularjs-partials/*.html'],
        tasks: ['html2js:templates']
      }
    }
  });
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-html2js');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.registerTask('build', ['html2js:templates']);
  grunt.registerTask('default', ['build']);
};
<|endoftext|>


<commit_before>/*
 * @copyright Copyright (c) 2018 Julius Härtl <jus@bitgrid.net>
 *
 * @author Julius Härtl <jus@bitgrid.net>
 *
 * @license GNU AGPL version 3 or any later version
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

window.addEventListener('DOMContentLoaded', function () {

	$('#body-public').find('.header-right .menutoggle').click(function() {
		$(this).next('.popovermenu').toggleClass('open');
	});

	$('#save-external-share').click(function () {
		$('#external-share-menu-item').toggleClass('hidden')
		$('#remote_address').focus();
	});

});

$(document).mouseup(function(e) {
	var toggle = $('#body-public').find('.header-right .menutoggle');
	var container = toggle.next('.popovermenu');

	// if the target of the click isn't the menu toggle, nor a descendant of the
	// menu toggle, nor the container nor a descendant of the container
	if (!toggle.is(e.target) && toggle.has(e.target).length === 0 &&
		!container.is(e.target) && container.has(e.target).length === 0) {
		container.removeClass('open');
	}
});
<commit_msg>fix: only use jquery once it is available<commit_after>/*
 * @copyright Copyright (c) 2018 Julius Härtl <jus@bitgrid.net>
 *
 * @author Julius Härtl <jus@bitgrid.net>
 *
 * @license GNU AGPL version 3 or any later version
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

window.addEventListener('DOMContentLoaded', function () {

	$('#body-public').find('.header-right .menutoggle').click(function() {
		$(this).next('.popovermenu').toggleClass('open');
	});

	$('#save-external-share').click(function () {
		$('#external-share-menu-item').toggleClass('hidden')
		$('#remote_address').focus();
	});

	$(document).mouseup(function(e) {
		var toggle = $('#body-public').find('.header-right .menutoggle');
		var container = toggle.next('.popovermenu');

		// if the target of the click isn't the menu toggle, nor a descendant of the
		// menu toggle, nor the container nor a descendant of the container
		if (!toggle.is(e.target) && toggle.has(e.target).length === 0 &&
			!container.is(e.target) && container.has(e.target).length === 0) {
			container.removeClass('open');
		}
	});

});
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

var Editor = function () {

	var SIGNALS = signals;

	this.DEFAULT_CAMERA = new THREE.PerspectiveCamera( 50, 1, 1, 10000 );
	this.DEFAULT_CAMERA.name = 'Camera';
	this.DEFAULT_CAMERA.position.set( 20, 10, 20 );
	this.DEFAULT_CAMERA.lookAt( new THREE.Vector3() );

	this.signals = {

		// script

		editScript: new SIGNALS.Signal(),

		// player

		startPlayer: new SIGNALS.Signal(),
		stopPlayer: new SIGNALS.Signal(),

		// actions

		showModal: new SIGNALS.Signal(),

		// notifications

		editorCleared: new SIGNALS.Signal(),

		savingStarted: new SIGNALS.Signal(),
		savingFinished: new SIGNALS.Signal(),

		themeChanged: new SIGNALS.Signal(),

		transformModeChanged: new SIGNALS.Signal(),
		snapChanged: new SIGNALS.Signal(),
		spaceChanged: new SIGNALS.Signal(),
		rendererChanged: new SIGNALS.Signal(),

		sceneGraphChanged: new SIGNALS.Signal(),

		cameraChanged: new SIGNALS.Signal(),

		geometryChanged: new SIGNALS.Signal(),

		objectSelected: new SIGNALS.Signal(),
		objectFocused: new SIGNALS.Signal(),

		objectAdded: new SIGNALS.Signal(),
		objectChanged: new SIGNALS.Signal(),
		objectRemoved: new SIGNALS.Signal(),

		helperAdded: new SIGNALS.Signal(),
		helperRemoved: new SIGNALS.Signal(),

		materialChanged: new SIGNALS.Signal(),

		scriptAdded: new SIGNALS.Signal(),
		scriptChanged: new SIGNALS.Signal(),
		scriptRemoved: new SIGNALS.Signal(),

		fogTypeChanged: new SIGNALS.Signal(),
		fogColorChanged: new SIGNALS.Signal(),
		fogParametersChanged: new SIGNALS.Signal(),
		windowResize: new SIGNALS.Signal(),

		showGridChanged: new SIGNALS.Signal(),
		refreshSidebarObject3D: new SIGNALS.Signal(),
		historyChanged: new SIGNALS.Signal(),
		refreshScriptEditor: new SIGNALS.Signal()

	};

	this.config = new Config();
	this.history = new History( this );
	this.storage = new Storage();
	this.loader = new Loader( this );

	this.camera = this.DEFAULT_CAMERA.clone();

	this.scene = new THREE.Scene();
	this.scene.name = 'Scene';

	this.sceneHelpers = new THREE.Scene();

	this.object = {};
	this.geometries = {};
	this.materials = {};
	this.textures = {};
	this.scripts = {};

	this.selected = null;
	this.helpers = {};

};

Editor.prototype = {

	setTheme: function ( value ) {

		document.getElementById( 'theme' ).href = value;

		this.signals.themeChanged.dispatch( value );

	},

	//

	setScene: function ( scene ) {

		this.scene.uuid = scene.uuid;
		this.scene.name = scene.name;
		this.scene.userData = JSON.parse( JSON.stringify( scene.userData ) );

		// avoid render per object

		this.signals.sceneGraphChanged.active = false;

		while ( scene.children.length > 0 ) {

			this.addObject( scene.children[ 0 ] );

		}

		this.signals.sceneGraphChanged.active = true;
		this.signals.sceneGraphChanged.dispatch();

	},

	//

	addObject: function ( object ) {

		var scope = this;

		object.traverse( function ( child ) {

			if ( child.geometry !== undefined ) scope.addGeometry( child.geometry );
			if ( child.material !== undefined ) scope.addMaterial( child.material );

			scope.addHelper( child );

		} );

		this.scene.add( object );

		this.signals.objectAdded.dispatch( object );
		this.signals.sceneGraphChanged.dispatch();

	},

	moveObject: function ( object, parent, before ) {

		if ( parent === undefined ) {

			parent = this.scene;

		}

		parent.add( object );

		// sort children array

		if ( before !== undefined ) {

			var index = parent.children.indexOf( before );
			parent.children.splice( index, 0, object );
			parent.children.pop();

		}

		this.signals.sceneGraphChanged.dispatch();

	},

	nameObject: function ( object, name ) {

		object.name = name;
		this.signals.sceneGraphChanged.dispatch();

	},

	removeObject: function ( object ) {

		if ( object.parent === null ) return; // avoid deleting the camera or scene

		var scope = this;

		object.traverse( function ( child ) {

			scope.removeHelper( child );

		} );

		object.parent.remove( object );

		this.signals.objectRemoved.dispatch( object );
		this.signals.sceneGraphChanged.dispatch();

	},

	addGeometry: function ( geometry ) {

		this.geometries[ geometry.uuid ] = geometry;

	},

	setGeometryName: function ( geometry, name ) {

		geometry.name = name;
		this.signals.sceneGraphChanged.dispatch();

	},

	addMaterial: function ( material ) {

		this.materials[ material.uuid ] = material;

	},

	setMaterialName: function ( material, name ) {

		material.name = name;
		this.signals.sceneGraphChanged.dispatch();

	},

	addTexture: function ( texture ) {

		this.textures[ texture.uuid ] = texture;

	},

	//

	addHelper: function () {

		var geometry = new THREE.SphereBufferGeometry( 2, 4, 2 );
		var material = new THREE.MeshBasicMaterial( { color: 0xff0000, visible: false } );

		return function ( object ) {

			var helper;

			if ( object instanceof THREE.Camera ) {

				helper = new THREE.CameraHelper( object, 1 );

			} else if ( object instanceof THREE.PointLight ) {

				helper = new THREE.PointLightHelper( object, 1 );

			} else if ( object instanceof THREE.DirectionalLight ) {

				helper = new THREE.DirectionalLightHelper( object, 1 );

			} else if ( object instanceof THREE.SpotLight ) {

				helper = new THREE.SpotLightHelper( object, 1 );

			} else if ( object instanceof THREE.HemisphereLight ) {

				helper = new THREE.HemisphereLightHelper( object, 1 );

			} else if ( object instanceof THREE.SkinnedMesh ) {

				helper = new THREE.SkeletonHelper( object );

			} else {

				// no helper for this object type
				return;

			}

			var picker = new THREE.Mesh( geometry, material );
			picker.name = 'picker';
			picker.userData.object = object;
			helper.add( picker );

			this.sceneHelpers.add( helper );
			this.helpers[ object.id ] = helper;

			this.signals.helperAdded.dispatch( helper );

		};

	}(),

	removeHelper: function ( object ) {

		if ( this.helpers[ object.id ] !== undefined ) {

			var helper = this.helpers[ object.id ];
			helper.parent.remove( helper );

			delete this.helpers[ object.id ];

			this.signals.helperRemoved.dispatch( helper );

		}

	},

	//

	addScript: function ( object, script ) {

		if ( this.scripts[ object.uuid ] === undefined ) {

			this.scripts[ object.uuid ] = [];

		}

		this.scripts[ object.uuid ].push( script );

		this.signals.scriptAdded.dispatch( script );

	},

	removeScript: function ( object, script ) {

		if ( this.scripts[ object.uuid ] === undefined ) return;

		var index = this.scripts[ object.uuid ].indexOf( script );

		if ( index !== - 1 ) {

			this.scripts[ object.uuid ].splice( index, 1 );

		}

		this.signals.scriptRemoved.dispatch( script );

	},

	//

	select: function ( object ) {

		if ( this.selected === object ) return;

		var uuid = null;

		if ( object !== null ) {

			uuid = object.uuid;

		}

		this.selected = object;

		this.config.setKey( 'selected', uuid );
		this.signals.objectSelected.dispatch( object );

	},

	selectById: function ( id ) {

		if ( id === this.camera.id ) {

			this.select( this.camera );
			return;

		}

		this.select( this.scene.getObjectById( id, true ) );

	},

	selectByUuid: function ( uuid ) {

		var scope = this;

		this.scene.traverse( function ( child ) {

			if ( child.uuid === uuid ) {

				scope.select( child );

			}

		} );

	},

	deselect: function () {

		this.select( null );

	},

	focus: function ( object ) {

		this.signals.objectFocused.dispatch( object );

	},

	focusById: function ( id ) {

		this.focus( this.scene.getObjectById( id, true ) );

	},

	clear: function () {

		this.history.clear();
		this.storage.clear();

		this.camera.copy( this.DEFAULT_CAMERA );

		var objects = this.scene.children;

		while ( objects.length > 0 ) {

			this.removeObject( objects[ 0 ] );

		}

		this.geometries = {};
		this.materials = {};
		this.textures = {};
		this.scripts = {};

		this.deselect();

		this.signals.editorCleared.dispatch();

	},

	//

	fromJSON: function ( json ) {

		var loader = new THREE.ObjectLoader();

		// backwards

		if ( json.scene === undefined ) {

			this.setScene( loader.parse( json ) );
			return;

		}

		// TODO: Clean this up somehow

		if ( json.project !== undefined ) {

			this.config.setKey( 'project/renderer/shadows', json.project.shadows );
			this.config.setKey( 'project/vr', json.project.vr );

		}

		var camera = loader.parse( json.camera );

		this.camera.copy( camera );
		this.camera.aspect = this.DEFAULT_CAMERA.aspect;
		this.camera.updateProjectionMatrix();

		this.history.fromJSON( json.history );
		this.scripts = json.scripts;

		this.setScene( loader.parse( json.scene ) );

	},

	toJSON: function () {

		// scripts clean up

		var scene = this.scene;
		var scripts = this.scripts;

		for ( var key in scripts ) {

			var script = scripts[ key ];

			if ( script.length === 0 || scene.getObjectByProperty( 'uuid', key ) === undefined ) {

				delete scripts[ key ];

			}

		}

		//

		return {

			metadata: {},
			project: {
				shadows: this.config.getKey( 'project/renderer/shadows' ),
				vr: this.config.getKey( 'project/vr' )
			},
			camera: this.camera.toJSON(),
			scene: this.scene.toJSON(),
			scripts: this.scripts,
			history: this.history.toJSON()

		};

	},

	objectByUuid: function ( uuid ) {

		return this.scene.getObjectByProperty( 'uuid', uuid, true );

	},

	execute: function ( cmd, optionalName ) {

		this.history.execute( cmd, optionalName );

	},

	undo: function () {

		this.history.undo();

	},

	redo: function () {

		this.history.redo();

	}

};
<commit_msg>Editor: Changed default camera near.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

var Editor = function () {

	var SIGNALS = signals;

	this.DEFAULT_CAMERA = new THREE.PerspectiveCamera( 50, 1, 0.1, 10000 );
	this.DEFAULT_CAMERA.name = 'Camera';
	this.DEFAULT_CAMERA.position.set( 20, 10, 20 );
	this.DEFAULT_CAMERA.lookAt( new THREE.Vector3() );

	this.signals = {

		// script

		editScript: new SIGNALS.Signal(),

		// player

		startPlayer: new SIGNALS.Signal(),
		stopPlayer: new SIGNALS.Signal(),

		// actions

		showModal: new SIGNALS.Signal(),

		// notifications

		editorCleared: new SIGNALS.Signal(),

		savingStarted: new SIGNALS.Signal(),
		savingFinished: new SIGNALS.Signal(),

		themeChanged: new SIGNALS.Signal(),

		transformModeChanged: new SIGNALS.Signal(),
		snapChanged: new SIGNALS.Signal(),
		spaceChanged: new SIGNALS.Signal(),
		rendererChanged: new SIGNALS.Signal(),

		sceneGraphChanged: new SIGNALS.Signal(),

		cameraChanged: new SIGNALS.Signal(),

		geometryChanged: new SIGNALS.Signal(),

		objectSelected: new SIGNALS.Signal(),
		objectFocused: new SIGNALS.Signal(),

		objectAdded: new SIGNALS.Signal(),
		objectChanged: new SIGNALS.Signal(),
		objectRemoved: new SIGNALS.Signal(),

		helperAdded: new SIGNALS.Signal(),
		helperRemoved: new SIGNALS.Signal(),

		materialChanged: new SIGNALS.Signal(),

		scriptAdded: new SIGNALS.Signal(),
		scriptChanged: new SIGNALS.Signal(),
		scriptRemoved: new SIGNALS.Signal(),

		fogTypeChanged: new SIGNALS.Signal(),
		fogColorChanged: new SIGNALS.Signal(),
		fogParametersChanged: new SIGNALS.Signal(),
		windowResize: new SIGNALS.Signal(),

		showGridChanged: new SIGNALS.Signal(),
		refreshSidebarObject3D: new SIGNALS.Signal(),
		historyChanged: new SIGNALS.Signal(),
		refreshScriptEditor: new SIGNALS.Signal()

	};

	this.config = new Config();
	this.history = new History( this );
	this.storage = new Storage();
	this.loader = new Loader( this );

	this.camera = this.DEFAULT_CAMERA.clone();

	this.scene = new THREE.Scene();
	this.scene.name = 'Scene';

	this.sceneHelpers = new THREE.Scene();

	this.object = {};
	this.geometries = {};
	this.materials = {};
	this.textures = {};
	this.scripts = {};

	this.selected = null;
	this.helpers = {};

};

Editor.prototype = {

	setTheme: function ( value ) {

		document.getElementById( 'theme' ).href = value;

		this.signals.themeChanged.dispatch( value );

	},

	//

	setScene: function ( scene ) {

		this.scene.uuid = scene.uuid;
		this.scene.name = scene.name;
		this.scene.userData = JSON.parse( JSON.stringify( scene.userData ) );

		// avoid render per object

		this.signals.sceneGraphChanged.active = false;

		while ( scene.children.length > 0 ) {

			this.addObject( scene.children[ 0 ] );

		}

		this.signals.sceneGraphChanged.active = true;
		this.signals.sceneGraphChanged.dispatch();

	},

	//

	addObject: function ( object ) {

		var scope = this;

		object.traverse( function ( child ) {

			if ( child.geometry !== undefined ) scope.addGeometry( child.geometry );
			if ( child.material !== undefined ) scope.addMaterial( child.material );

			scope.addHelper( child );

		} );

		this.scene.add( object );

		this.signals.objectAdded.dispatch( object );
		this.signals.sceneGraphChanged.dispatch();

	},

	moveObject: function ( object, parent, before ) {

		if ( parent === undefined ) {

			parent = this.scene;

		}

		parent.add( object );

		// sort children array

		if ( before !== undefined ) {

			var index = parent.children.indexOf( before );
			parent.children.splice( index, 0, object );
			parent.children.pop();

		}

		this.signals.sceneGraphChanged.dispatch();

	},

	nameObject: function ( object, name ) {

		object.name = name;
		this.signals.sceneGraphChanged.dispatch();

	},

	removeObject: function ( object ) {

		if ( object.parent === null ) return; // avoid deleting the camera or scene

		var scope = this;

		object.traverse( function ( child ) {

			scope.removeHelper( child );

		} );

		object.parent.remove( object );

		this.signals.objectRemoved.dispatch( object );
		this.signals.sceneGraphChanged.dispatch();

	},

	addGeometry: function ( geometry ) {

		this.geometries[ geometry.uuid ] = geometry;

	},

	setGeometryName: function ( geometry, name ) {

		geometry.name = name;
		this.signals.sceneGraphChanged.dispatch();

	},

	addMaterial: function ( material ) {

		this.materials[ material.uuid ] = material;

	},

	setMaterialName: function ( material, name ) {

		material.name = name;
		this.signals.sceneGraphChanged.dispatch();

	},

	addTexture: function ( texture ) {

		this.textures[ texture.uuid ] = texture;

	},

	//

	addHelper: function () {

		var geometry = new THREE.SphereBufferGeometry( 2, 4, 2 );
		var material = new THREE.MeshBasicMaterial( { color: 0xff0000, visible: false } );

		return function ( object ) {

			var helper;

			if ( object instanceof THREE.Camera ) {

				helper = new THREE.CameraHelper( object, 1 );

			} else if ( object instanceof THREE.PointLight ) {

				helper = new THREE.PointLightHelper( object, 1 );

			} else if ( object instanceof THREE.DirectionalLight ) {

				helper = new THREE.DirectionalLightHelper( object, 1 );

			} else if ( object instanceof THREE.SpotLight ) {

				helper = new THREE.SpotLightHelper( object, 1 );

			} else if ( object instanceof THREE.HemisphereLight ) {

				helper = new THREE.HemisphereLightHelper( object, 1 );

			} else if ( object instanceof THREE.SkinnedMesh ) {

				helper = new THREE.SkeletonHelper( object );

			} else {

				// no helper for this object type
				return;

			}

			var picker = new THREE.Mesh( geometry, material );
			picker.name = 'picker';
			picker.userData.object = object;
			helper.add( picker );

			this.sceneHelpers.add( helper );
			this.helpers[ object.id ] = helper;

			this.signals.helperAdded.dispatch( helper );

		};

	}(),

	removeHelper: function ( object ) {

		if ( this.helpers[ object.id ] !== undefined ) {

			var helper = this.helpers[ object.id ];
			helper.parent.remove( helper );

			delete this.helpers[ object.id ];

			this.signals.helperRemoved.dispatch( helper );

		}

	},

	//

	addScript: function ( object, script ) {

		if ( this.scripts[ object.uuid ] === undefined ) {

			this.scripts[ object.uuid ] = [];

		}

		this.scripts[ object.uuid ].push( script );

		this.signals.scriptAdded.dispatch( script );

	},

	removeScript: function ( object, script ) {

		if ( this.scripts[ object.uuid ] === undefined ) return;

		var index = this.scripts[ object.uuid ].indexOf( script );

		if ( index !== - 1 ) {

			this.scripts[ object.uuid ].splice( index, 1 );

		}

		this.signals.scriptRemoved.dispatch( script );

	},

	//

	select: function ( object ) {

		if ( this.selected === object ) return;

		var uuid = null;

		if ( object !== null ) {

			uuid = object.uuid;

		}

		this.selected = object;

		this.config.setKey( 'selected', uuid );
		this.signals.objectSelected.dispatch( object );

	},

	selectById: function ( id ) {

		if ( id === this.camera.id ) {

			this.select( this.camera );
			return;

		}

		this.select( this.scene.getObjectById( id, true ) );

	},

	selectByUuid: function ( uuid ) {

		var scope = this;

		this.scene.traverse( function ( child ) {

			if ( child.uuid === uuid ) {

				scope.select( child );

			}

		} );

	},

	deselect: function () {

		this.select( null );

	},

	focus: function ( object ) {

		this.signals.objectFocused.dispatch( object );

	},

	focusById: function ( id ) {

		this.focus( this.scene.getObjectById( id, true ) );

	},

	clear: function () {

		this.history.clear();
		this.storage.clear();

		this.camera.copy( this.DEFAULT_CAMERA );

		var objects = this.scene.children;

		while ( objects.length > 0 ) {

			this.removeObject( objects[ 0 ] );

		}

		this.geometries = {};
		this.materials = {};
		this.textures = {};
		this.scripts = {};

		this.deselect();

		this.signals.editorCleared.dispatch();

	},

	//

	fromJSON: function ( json ) {

		var loader = new THREE.ObjectLoader();

		// backwards

		if ( json.scene === undefined ) {

			this.setScene( loader.parse( json ) );
			return;

		}

		// TODO: Clean this up somehow

		if ( json.project !== undefined ) {

			this.config.setKey( 'project/renderer/shadows', json.project.shadows );
			this.config.setKey( 'project/vr', json.project.vr );

		}

		var camera = loader.parse( json.camera );

		this.camera.copy( camera );
		this.camera.aspect = this.DEFAULT_CAMERA.aspect;
		this.camera.updateProjectionMatrix();

		this.history.fromJSON( json.history );
		this.scripts = json.scripts;

		this.setScene( loader.parse( json.scene ) );

	},

	toJSON: function () {

		// scripts clean up

		var scene = this.scene;
		var scripts = this.scripts;

		for ( var key in scripts ) {

			var script = scripts[ key ];

			if ( script.length === 0 || scene.getObjectByProperty( 'uuid', key ) === undefined ) {

				delete scripts[ key ];

			}

		}

		//

		return {

			metadata: {},
			project: {
				shadows: this.config.getKey( 'project/renderer/shadows' ),
				vr: this.config.getKey( 'project/vr' )
			},
			camera: this.camera.toJSON(),
			scene: this.scene.toJSON(),
			scripts: this.scripts,
			history: this.history.toJSON()

		};

	},

	objectByUuid: function ( uuid ) {

		return this.scene.getObjectByProperty( 'uuid', uuid, true );

	},

	execute: function ( cmd, optionalName ) {

		this.history.execute( cmd, optionalName );

	},

	undo: function () {

		this.history.undo();

	},

	redo: function () {

		this.history.redo();

	}

};
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import injectSheet from 'react-jss'

import Spacer from '../components/spacer'
import teamMemberInfo from './team-member-info'
import TeamMember from './team-member'

class Team extends Component {
	constructor(props) {
		super(props)
		this.state = {
			teamMemberId: 0,
		}
	}

	render() {
		const { classes } = this.props
		const { teamMemberId } = this.state
		const { name, title, bio } = teamMemberInfo[teamMemberId]

		return (

						{teamMemberInfo.map(teamMember => {
							return (

									<button
										className={classes.button}
										onClick={() => {
											this.handleClick(teamMember.id)
										}}
									>

										<Spacer width="16px" />
									</button>

							)
						})}

				<TeamMember name={name} title={title} bio={bio} />

		)
	}

	handleClick(teamMemberId) {
		this.setState({
			teamMemberId,
		})
	}
}

const styles = {
	headshotsContainer: {
		overflow: 'scroll',
	},
	flex: {
		display: 'flex',
		'justify-content': 'center',
	},
	headshot: {
		height: '240px',
		width: '240px',
	},
	button: {
		cursor: 'pointer',
		outline: 'none',
		border: 'none',
	},
}

export default injectSheet(styles)(Team)
<commit_msg>Fix scroll<commit_after>import React, { Component } from 'react'
import injectSheet from 'react-jss'

import Spacer from '../components/spacer'
import teamMemberInfo from './team-member-info'
import TeamMember from './team-member'

class Team extends Component {
	constructor(props) {
		super(props)
		this.state = {
			teamMemberId: 0,
		}
	}

	render() {
		const { classes } = this.props
		const { teamMemberId } = this.state
		const { name, title, bio } = teamMemberInfo[teamMemberId]

		return (

						{teamMemberInfo.map(teamMember => {
							return (

									<button
										className={classes.button}
										onClick={() => {
											this.handleClick(teamMember.id)
										}}
									>

										<Spacer width="16px" />
									</button>

							)
						})}

				<TeamMember name={name} title={title} bio={bio} />

		)
	}

	handleClick(teamMemberId) {
		this.setState({
			teamMemberId,
		})
	}
}

const styles = {
	scrollContainer: {
		overflow: 'auto',
	},
	teamMemberContainer: {
		display: 'flex',
	},
	imageAndButtonContainer: {
		display: 'flex',
		'justify-content': 'center',
	},
	headshot: {
		height: '240px',
		width: '240px',
	},
	button: {
		cursor: 'pointer',
		outline: 'none',
		border: 'none',
	},
}

export default injectSheet(styles)(Team)
<|endoftext|>