<commit_before>// (C) Copyright 2015 Martin Dougiamas
//
// 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.

// Dependencies will be automatically added here, the following line must declare ionic as first dependency
// and should not be split into multiple lines, see gulpfile.js.
angular.module('mm', ['ionic', 'ngCordova', 'angular-md5', 'pascalprecht.translate', 'ngAria', 'oc.lazyLoad', 'ckeditor',
            'ngMessages'])

.run(function($ionicPlatform) {
	$ionicPlatform.ready(function() {
		if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
			window.cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false);
		}
		if (window.StatusBar) {
			StatusBar.styleDefault();
		}
	});
});
<commit_msg>MOBILE-1849 ios: Disable keyboard scroll<commit_after>// (C) Copyright 2015 Martin Dougiamas
//
// 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.

// Dependencies will be automatically added here, the following line must declare ionic as first dependency
// and should not be split into multiple lines, see gulpfile.js.
angular.module('mm', ['ionic', 'ngCordova', 'angular-md5', 'pascalprecht.translate', 'ngAria', 'oc.lazyLoad', 'ckeditor',
            'ngMessages'])

.run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
        if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
            window.cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false);
            window.cordova.plugins.Keyboard.disableScroll(true);
        }
        if (window.StatusBar) {
            StatusBar.styleDefault();
        }
    });
});
<|endoftext|>


<commit_before>(function (root, factory) {
  'use strict';
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['angular'], factory);
  } else if (typeof module !== 'undefined' && typeof module.exports === 'object') {
    // CommonJS support (for us webpack/browserify/ComponentJS folks)
    module.exports = factory(require('angular'));
  } else {
    // in the case of no module loading system
    // then don't worry about creating a global
    // variable like you would in normal UMD.
    // It's not really helpful... Just call your factory
    return factory(root.angular);
  }
}(this, function (angular) {
	'use strict';

	var moduleName = 'ng-d3-charts';
	var mod = angular.module(moduleName, []);

	mod.service('d3Loader', ['$document', '$q', '$rootScope',
		function($document, $q, $rootScope) {

			var d = $q.defer();

			function onScriptLoad() {
				// Load client in the browser
				$rootScope.$apply(function() { d.resolve(window.d3); });
			}

			var scriptTag 		= $document[0].createElement('script');
			scriptTag.type 		= 'text/javascript';
			scriptTag.async 	= true;
			scriptTag.src 		= 'https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js';

			scriptTag.onreadystatechange = function () {
				if (this.readyState == 'complete') onScriptLoad();
			};
			scriptTag.onload 	= onScriptLoad;

			var s = $document[0].getElementsByTagName('body')[0];
			s.appendChild(scriptTag);

			return { d3: function() { return d.promise; } };

	}]);

	mod.factory('chartConfig',function(){

		var chartConfig = function(config){

			this.chartType = config.chartType || null;

			//Layout configuration
			this.margin = config.margin || {top: 30, right: 30, bottom: 30, left: 30};

			//Axis Configuration
			var xAxisConst = function(config){
				this.showAxis        = (config.showAxis == false) ? false : true;
				this.scale 	         = config.scale || 'd3.scale.linear().range([0, width])';
				this.orient  		 = config.orient || 'bottom';

				/**** Ticks configuration ****/
				this.ticks           = config.ticks || null;
				this.tickSize        = config.tickSize || 6;
				this.outerTickSize   = config.outerTickSize || 0;
				this.innerTickSize   = config.innerTickSize || 6;
				this.tickPadding 	 = config.tickPadding || 3;
				this.tickFormat      = config.tickFormat || null;
				this.tickValues      = config.tickValues|| null;

				/**** barChart specific ****/
				this.barPadding 	 = config.barPadding || .5;
				this.barOuterPadding = config.barOuterPadding || 0;
			};

			var yAxisConst = function(config){
				this.showAxis	     = (config.showAxis == false) ? false : true;
				this.scale 		     = config.scale || 'd3.scale.linear().range([height, 0])';
				this.orient  		 = config.orient || 'left';

				/**** Ticks configuration ****/
				this.ticks           = config.ticks || null;
				this.tickSize        = config.tickSize || 6;
				this.outerTickSize   = config.outerTickSize || 0;
				this.innerTickSize   = config.innerTickSize || 6;
				this.tickPadding 	 = config.tickPadding || 3;
				this.tickFormat      = config.tickFormat || null;
				this.tickValues      = config.tickValues|| null;
			};

			this.xAxis =  new xAxisConst(config.xAxis);
			this.yAxis =  new yAxisConst(config.yAxis);

			//Basic style configuration
			/**** barChart specific ****/
			this.barColor = config.barColor || '#3498DB';
			this.bakcgroundColor = config.bakcgroundColor || 'white';

			//Animation configuration
			/**** barChart specific ****/
			this.delayedEntrance = config.delayedEntrance || 100;
		};

		return chartConfig;

	});

	mod.directive('ngBarChart', ['d3Loader','$timeout', function(d3Loader,$timeout) {

		function barChart(config,data,element,attrs){

			var margin = config.margin,
				full_width = attrs.$$element[0].parentNode.clientWidth,
				full_height= attrs.$$element[0].parentNode.offsetHeight,
				width = full_width - margin.left - margin.right,
				height = full_height - margin.top - margin.bottom,
				barColor = config.barColor,
				backgroundColor = config.bakcgroundColor,
				colorScale;

			//If color_scale is provided
			(config.barColor.indexOf('d3.scale') > -1)
				? colorScale = eval(config.barColor)
				: false;

			/**** No custom x for now ****/
			var x = d3.scale.ordinal()
				.rangeRoundBands([0,width],config.xAxis.barPadding,config.xAxis.barOuterPadding);

			var y = eval(config.yAxis.scale);

			var x_axis = d3.svg.axis()
				.scale(x)
				.orient(config.xAxis.orient)
				.ticks(eval(config.xAxis.ticks))
				.tickSize(config.xAxis.tickSize)
				.outerTickSize(config.xAxis.outerTickSize)
				.innerTickSize(config.xAxis.innerTickSize)
				.tickPadding(config.xAxis.tickPadding)
				.tickFormat((config.xAxis.tickFormat) ? eval(config.xAxis.tickFormat) : null)
				.tickValues(eval(config.xAxis.tickValues));

			var y_axis = d3.svg.axis()
				.scale(y)
				.orient(config.yAxis.orient)
				.ticks(eval(config.yAxis.ticks))
				.tickSize(config.yAxis.tickSize)
				.outerTickSize(config.yAxis.outerTickSize)
				.innerTickSize(config.yAxis.innerTickSize)
				.tickPadding(config.yAxis.tickPadding)
				.tickFormat((config.yAxis.tickFormat) ? eval(config.yAxis.tickFormat) : null)
				.tickValues(eval(config.yAxis.tickValues));

			// Set up x_axis with non-numeric values.
			var x_domain = [];
			angular.forEach(data,function(d,i){	x_domain.push(d.x); });
			x.domain(x_domain);

			//Set up y_axis
			var max_y = d3.max(data,function(d){ return d.y; });
			y.domain([0,max_y * 1.1]);

			var svgNotExist =  d3.select(element[0])
					.select('svg')
					.select('g')[0][0] == null;

			(config.yAxis.showAxis)
				? margin = leftMarginToBiggestYLabelWidth(element,y_axis,margin)
				: false;

			var mask,x_axis_node,y_axis_node,initial,svg;

			(svgNotExist)
				? (svg = d3.select(element[0])
					.append("svg:svg")
					.attr("width", full_width)
					.attr("height", full_height)
					.attr("class","bar-chart")
						.append("svg:g")
					.attr("transform", "translate(" + margin.left + "," + margin.top +")"),
					initial = true
				)
				: svg = d3.select(element[0]).select('svg g');

			var bar_nodes = svg.selectAll(".bar")
				.data(data);

			bar_nodes.exit().remove();

			bar_nodes.enter().append("rect")
				.attr("class", "bar")
				.attr("y", function(d) { return y(0); });

			bar_nodes.style('fill',function(d,i){ return (colorScale != undefined)
						? colorScale(i)
						: barColor;
				});

			bar_nodes.transition().duration(300)
				.attr("x", function(d) { return x(d.x); })
				.attr("y", function(d,i) { return y(d.y); })
				.attr("width", x.rangeBand())
						.attr("height", function(d) { return height - y(d.y); })
						.delay(function(d,i) { return i*config.delayedEntrance; });

			//Remove and redraw x_axis because bottom to top animation.
			svg.select('.axis.x').remove();

			mask = svg.append('rect')
				.attr('class','mask')
				.attr("y",height)
				.attr("x",0)
				.attr("width",width)
				.attr("height",margin.bottom)
				.style("fill", backgroundColor);

			x_axis_node = svg.append('g')
				.attr('class','axis x')
				.attr('transform', 'translate(' + 0 + ',' + height + ')');

			(initial) ? (
				y_axis_node = svg.append('g')
					.attr('class','axis y')
					.attr('transform', 'translate(' + 0 + ',' + 0 + ')'),
					initial=false)
				: false;

			(config.xAxis.showAxis) ? svg.select('.x.axis').transition().duration(300).call(x_axis) : false;
			(config.yAxis.showAxis) ? svg.select('.y.axis').transition().duration(300).call(y_axis) : false;

		}

		function lineChart(config,data,element,attrs) {

			var margin = config.margin,
				full_width = attrs.$$element[0].parentNode.clientWidth,
				full_height = attrs.$$element[0].parentNode.offsetHeight,
				width = full_width - margin.left - margin.right,
				height = full_height - margin.top - margin.bottom;

			var x = eval(config.xAxis.scale);
			var y = eval(config.yAxis.scale);

			var xAxis = d3.svg.axis()
				.scale(x)
				.orient(config.xAxis.orient)
				.ticks(eval(config.xAxis.ticks))
				.tickSize(config.xAxis.tickSize)
				.outerTickSize(config.xAxis.outerTickSize)
				.innerTickSize(config.xAxis.innerTickSize)
				.tickPadding(config.xAxis.tickPadding)
				.tickFormat((config.xAxis.tickFormat) ? eval(config.xAxis.tickFormat) : null)
				.tickValues(eval(config.xAxis.tickValues));

			x.domain(d3.extent(data, function (d) { return d.x; }));

			var yAxis = d3.svg.axis()
				.scale(y)
				.orient(config.yAxis.orient)
				.ticks(eval(config.yAxis.ticks))
				.tickSize(config.yAxis.tickSize)
				.outerTickSize(config.yAxis.outerTickSize)
				.innerTickSize(config.yAxis.innerTickSize)
				.tickPadding(config.yAxis.tickPadding)
				.tickFormat((config.yAxis.tickFormat) ? eval(config.yAxis.tickFormat) : null)
				.tickValues(eval(config.yAxis.tickValues));

			y.domain(d3.extent(data, function (d) { return d.y;	}));

			var svgNotExist = d3.select(element[0]).select('svg')
					.select('g')[0][0] == null;

			var x_axis_node, y_axis_node, initial, svg;

			(config.yAxis.showAxis)
				? margin = leftMarginToBiggestYLabelWidth(element, yAxis, margin)
				: false;

			(svgNotExist)
				? (svg = d3.select(element[0])
					.append("svg:svg")
					.attr("class", "line-chart")
					.attr("width", full_width)
					.attr("height", full_height)
					.append("svg:g")
					.attr("transform", "translate(" + margin.left + "," + margin.top + ")"),

					initial = true
			)
				: svg = d3.select(element[0]).select('svg g');

			var line = d3.svg.line()
				.x(function (d) {
					return x(d.x);
				})
				.y(function (d) {
					return y(d.y);
				});

			(initial)
				? (
				x_axis_node = svg.append("g")
					.attr("class", "x axis")
					.attr("transform", "translate(0," + (height) + ")")
					.call(xAxis),

				x_axis_node.append("text")
					.style("text-anchor", "end")
					.style("font-size", ".6em")
					.attr("dx", (width - 5) + "px")
					.attr("dy", "1.5em")
					.text(config.XlabelText),

				y_axis_node = svg.append("g")
					.attr("class", "y axis")
					.call(yAxis),

				y_axis_node.append("text")
					.attr("class", "axis-label")
					.attr("transform", "rotate(-90)")
					.attr("y", 6)
					.attr("dy", ".6em")
					.style("text-anchor", "end")
					.style("font-size", ".6em")
					.text(config.YlabelText),

				svg.append("path")
					.attr("class", "line")
					.attr("d", line(data))
				)
				: (
					svg.select(".x.axis")
						.transition().duration(750)
						.call(xAxis),
					svg.select(".y.axis")
						.transition().duration(750)
						.call(yAxis),
					svg.select(".line")
						.transition().duration(750)
						.attr("d", line(data))
				)
		}

		//HELPERS
		function leftMarginToBiggestYLabelWidth(element,y_axis,margin){
				var y_format,widest_y_label;
				//Set the margin left to display the longest label on y axis.
				y_format = y_axis.scale().tickFormat(),
				widest_y_label = d3.select(element[0]).append('text')
					.text(y_format(y_axis.scale().ticks()[y_axis.scale().ticks().length -1])),
				//Only if the given margin.left on the config object is smaller than the biggest label.
				(margin.left < widest_y_label[0][0].offsetWidth * 1.5 )
					? (console.info('refactoring margin'),margin.left = (widest_y_label[0][0].offsetWidth * 1.5))
					: false;
				widest_y_label.remove();
				return margin;
			}

		return {
			restrict: 'E',
			scope: {
				dataset:'=',
				config:'='
			},
			link: function(scope,element,attrs){
				var d3isReady = d3Loader.d3();
				scope.$watch('dataset',function(newData,oldData){
					(newData)
						? (d3isReady.then(function(){ $timeout(function(){
							var chartToDraw = eval(scope.config.chartType);
							(chartToDraw)
								? chartToDraw(scope.config,newData,element,attrs)
								: console.error('Invalid chart name. Please adjust your chartType parameter.');
						});}))
						: false;
				});
			}
		};
	}]);
	return moduleName;
}));<commit_msg>Added markups<commit_after>(function (root, factory) {
  'use strict';
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['angular'], factory);
  } else if (typeof module !== 'undefined' && typeof module.exports === 'object') {
    // CommonJS support (for us webpack/browserify/ComponentJS folks)
    module.exports = factory(require('angular'));
  } else {
    // in the case of no module loading system
    // then don't worry about creating a global
    // variable like you would in normal UMD.
    // It's not really helpful... Just call your factory
    return factory(root.angular);
  }
}(this, function (angular) {
	'use strict';

	var moduleName = 'ng-d3-charts';
	var mod = angular.module(moduleName, []);

	mod.service('d3Loader', ['$document', '$q', '$rootScope',
		function($document, $q, $rootScope) {

			var d = $q.defer();

			function onScriptLoad() {
				// Load client in the browser
				$rootScope.$apply(function() { d.resolve(window.d3); });
			}

			var scriptTag 		= $document[0].createElement('script');
			scriptTag.type 		= 'text/javascript';
			scriptTag.async 	= true;
			scriptTag.src 		= 'https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js';

			scriptTag.onreadystatechange = function () {
				if (this.readyState == 'complete') onScriptLoad();
			};
			scriptTag.onload 	= onScriptLoad;

			var s = $document[0].getElementsByTagName('body')[0];
			s.appendChild(scriptTag);

			return { d3: function() { return d.promise; } };

	}]);

	mod.factory('chartConfig',function(){

		var chartConfig = function(config){

			this.chartType = config.chartType || null;

			//Layout configuration
			this.margin = config.margin || {top: 30, right: 30, bottom: 30, left: 30};

			//Axis Configuration
			var xAxisConst = function(config){
				this.showAxis        = (config.showAxis == false) ? false : true;
				this.scale 	         = config.scale || 'd3.scale.linear().range([0, width])';
				this.orient  		 = config.orient || 'bottom';

				/**** Ticks configuration ****/
				this.ticks           = config.ticks || null;
				this.tickSize        = config.tickSize || 6;
				this.outerTickSize   = config.outerTickSize || 0;
				this.innerTickSize   = config.innerTickSize || 6;
				this.tickPadding 	 = config.tickPadding || 3;
				this.tickFormat      = config.tickFormat || null;
				this.tickValues      = config.tickValues|| null;

				/**** barChart specific ****/
				this.barPadding 	 = config.barPadding || .5;
				this.barOuterPadding = config.barOuterPadding || 0;
			};

			var yAxisConst = function(config){
				this.showAxis	     = (config.showAxis == false) ? false : true;
				this.scale 		     = config.scale || 'd3.scale.linear().range([height, 0])';
				this.orient  		 = config.orient || 'left';

				/**** Ticks configuration ****/
				this.ticks           = config.ticks || null;
				this.tickSize        = config.tickSize || 6;
				this.outerTickSize   = config.outerTickSize || 0;
				this.innerTickSize   = config.innerTickSize || 6;
				this.tickPadding 	 = config.tickPadding || 3;
				this.tickFormat      = config.tickFormat || null;
				this.tickValues      = config.tickValues|| null;
			};

			this.xAxis =  new xAxisConst(config.xAxis);
			this.yAxis =  new yAxisConst(config.yAxis);

			//Basic style configuration
			/**** barChart specific ****/
			this.barColor = config.barColor || '#3498DB';
			this.bakcgroundColor = config.bakcgroundColor || 'white';

			//Animation configuration
			/**** barChart specific ****/
			this.delayedEntrance = config.delayedEntrance || 100;
		};

		return chartConfig;

	});

	mod.directive('ngBarChart', ['d3Loader','$timeout', function(d3Loader,$timeout) {

		/***********
		*
		* Chart functions
		*
		* **********/

		function barChart(config,data,element,attrs){

			var margin = config.margin,
				full_width = attrs.$$element[0].parentNode.clientWidth,
				full_height= attrs.$$element[0].parentNode.offsetHeight,
				width = full_width - margin.left - margin.right,
				height = full_height - margin.top - margin.bottom,
				barColor = config.barColor,
				backgroundColor = config.bakcgroundColor,
				colorScale;

			//If color_scale is provided
			(config.barColor.indexOf('d3.scale') > -1)
				? colorScale = eval(config.barColor)
				: false;

			/**** No custom x for now ****/
			var x = d3.scale.ordinal()
				.rangeRoundBands([0,width],config.xAxis.barPadding,config.xAxis.barOuterPadding);

			var y = eval(config.yAxis.scale);

			var x_axis = d3.svg.axis()
				.scale(x)
				.orient(config.xAxis.orient)
				.ticks(eval(config.xAxis.ticks))
				.tickSize(config.xAxis.tickSize)
				.outerTickSize(config.xAxis.outerTickSize)
				.innerTickSize(config.xAxis.innerTickSize)
				.tickPadding(config.xAxis.tickPadding)
				.tickFormat((config.xAxis.tickFormat) ? eval(config.xAxis.tickFormat) : null)
				.tickValues(eval(config.xAxis.tickValues));

			var y_axis = d3.svg.axis()
				.scale(y)
				.orient(config.yAxis.orient)
				.ticks(eval(config.yAxis.ticks))
				.tickSize(config.yAxis.tickSize)
				.outerTickSize(config.yAxis.outerTickSize)
				.innerTickSize(config.yAxis.innerTickSize)
				.tickPadding(config.yAxis.tickPadding)
				.tickFormat((config.yAxis.tickFormat) ? eval(config.yAxis.tickFormat) : null)
				.tickValues(eval(config.yAxis.tickValues));

			// Set up x_axis with non-numeric values.
			var x_domain = [];
			angular.forEach(data,function(d,i){	x_domain.push(d.x); });
			x.domain(x_domain);

			//Set up y_axis
			var max_y = d3.max(data,function(d){ return d.y; });
			y.domain([0,max_y * 1.1]);

			var svgNotExist =  d3.select(element[0])
					.select('svg')
					.select('g')[0][0] == null;

			(config.yAxis.showAxis)
				? margin = leftMarginToBiggestYLabelWidth(element,y_axis,margin)
				: false;

			var mask,x_axis_node,y_axis_node,initial,svg;

			(svgNotExist)
				? (svg = d3.select(element[0])
					.append("svg:svg")
					.attr("width", full_width)
					.attr("height", full_height)
					.attr("class","bar-chart")
						.append("svg:g")
					.attr("transform", "translate(" + margin.left + "," + margin.top +")"),
					initial = true
				)
				: svg = d3.select(element[0]).select('svg g');

			var bar_nodes = svg.selectAll(".bar")
				.data(data);

			bar_nodes.exit().remove();

			bar_nodes.enter().append("rect")
				.attr("class", "bar")
				.attr("y", function(d) { return y(0); });

			bar_nodes.style('fill',function(d,i){ return (colorScale != undefined)
						? colorScale(i)
						: barColor;
				});

			bar_nodes.transition().duration(300)
				.attr("x", function(d) { return x(d.x); })
				.attr("y", function(d,i) { return y(d.y); })
				.attr("width", x.rangeBand())
						.attr("height", function(d) { return height - y(d.y); })
						.delay(function(d,i) { return i*config.delayedEntrance; });

			//Remove and redraw x_axis because bottom to top animation.
			svg.select('.axis.x').remove();

			mask = svg.append('rect')
				.attr('class','mask')
				.attr("y",height)
				.attr("x",0)
				.attr("width",width)
				.attr("height",margin.bottom)
				.style("fill", backgroundColor);

			x_axis_node = svg.append('g')
				.attr('class','axis x')
				.attr('transform', 'translate(' + 0 + ',' + height + ')');

			(initial) ? (
				y_axis_node = svg.append('g')
					.attr('class','axis y')
					.attr('transform', 'translate(' + 0 + ',' + 0 + ')'),
					initial=false)
				: false;

			(config.xAxis.showAxis) ? svg.select('.x.axis').transition().duration(300).call(x_axis) : false;
			(config.yAxis.showAxis) ? svg.select('.y.axis').transition().duration(300).call(y_axis) : false;

		}

		function lineChart(config,data,element,attrs) {

			var margin = config.margin,
				full_width = attrs.$$element[0].parentNode.clientWidth,
				full_height = attrs.$$element[0].parentNode.offsetHeight,
				width = full_width - margin.left - margin.right,
				height = full_height - margin.top - margin.bottom;

			var x = eval(config.xAxis.scale);
			var y = eval(config.yAxis.scale);

			var xAxis = d3.svg.axis()
				.scale(x)
				.orient(config.xAxis.orient)
				.ticks(eval(config.xAxis.ticks))
				.tickSize(config.xAxis.tickSize)
				.outerTickSize(config.xAxis.outerTickSize)
				.innerTickSize(config.xAxis.innerTickSize)
				.tickPadding(config.xAxis.tickPadding)
				.tickFormat((config.xAxis.tickFormat) ? eval(config.xAxis.tickFormat) : null)
				.tickValues(eval(config.xAxis.tickValues));

			x.domain(d3.extent(data, function (d) { return d.x; }));

			var yAxis = d3.svg.axis()
				.scale(y)
				.orient(config.yAxis.orient)
				.ticks(eval(config.yAxis.ticks))
				.tickSize(config.yAxis.tickSize)
				.outerTickSize(config.yAxis.outerTickSize)
				.innerTickSize(config.yAxis.innerTickSize)
				.tickPadding(config.yAxis.tickPadding)
				.tickFormat((config.yAxis.tickFormat) ? eval(config.yAxis.tickFormat) : null)
				.tickValues(eval(config.yAxis.tickValues));

			y.domain(d3.extent(data, function (d) { return d.y;	}));

			var svgNotExist = d3.select(element[0]).select('svg')
					.select('g')[0][0] == null;

			var x_axis_node, y_axis_node, initial, svg;

			(config.yAxis.showAxis)
				? margin = leftMarginToBiggestYLabelWidth(element, yAxis, margin)
				: false;

			(svgNotExist)
				? (svg = d3.select(element[0])
					.append("svg:svg")
					.attr("class", "line-chart")
					.attr("width", full_width)
					.attr("height", full_height)
					.append("svg:g")
					.attr("transform", "translate(" + margin.left + "," + margin.top + ")"),

					initial = true
			)
				: svg = d3.select(element[0]).select('svg g');

			var line = d3.svg.line()
				.x(function (d) {
					return x(d.x);
				})
				.y(function (d) {
					return y(d.y);
				});

			(initial)
				? (
				x_axis_node = svg.append("g")
					.attr("class", "x axis")
					.attr("transform", "translate(0," + (height) + ")")
					.call(xAxis),

				x_axis_node.append("text")
					.style("text-anchor", "end")
					.style("font-size", ".6em")
					.attr("dx", (width - 5) + "px")
					.attr("dy", "1.5em")
					.text(config.XlabelText),

				y_axis_node = svg.append("g")
					.attr("class", "y axis")
					.call(yAxis),

				y_axis_node.append("text")
					.attr("class", "axis-label")
					.attr("transform", "rotate(-90)")
					.attr("y", 6)
					.attr("dy", ".6em")
					.style("text-anchor", "end")
					.style("font-size", ".6em")
					.text(config.YlabelText),

				svg.append("path")
					.attr("class", "line")
					.attr("d", line(data))
				)
				: (
					svg.select(".x.axis")
						.transition().duration(750)
						.call(xAxis),
					svg.select(".y.axis")
						.transition().duration(750)
						.call(yAxis),
					svg.select(".line")
						.transition().duration(750)
						.attr("d", line(data))
				)
		}

		/***********
		*
		* Utils
		*
		* **********/

		function leftMarginToBiggestYLabelWidth(element,y_axis,margin){
				var y_format,widest_y_label;
				//Set the margin left to display the longest label on y axis.
				y_format = y_axis.scale().tickFormat(),
				widest_y_label = d3.select(element[0]).append('text')
					.text(y_format(y_axis.scale().ticks()[y_axis.scale().ticks().length -1])),
				//Only if the given margin.left on the config object is smaller than the biggest label.
				(margin.left < widest_y_label[0][0].offsetWidth * 1.5 )
					? (console.info('refactoring margin'),margin.left = (widest_y_label[0][0].offsetWidth * 1.5))
					: false;
				widest_y_label.remove();
				return margin;
			}

		/***********
		*
		* Directive
		*
		* **********/

		return {
			restrict: 'E',
			scope: {
				dataset:'=',
				config:'='
			},
			link: function(scope,element,attrs){
				var d3isReady = d3Loader.d3();
				scope.$watch('dataset',function(newData,oldData){
					(newData)
						? (d3isReady.then(function(){ $timeout(function(){
							var chartToDraw = eval(scope.config.chartType);
							(chartToDraw)
								? chartToDraw(scope.config,newData,element,attrs)
								: console.error('Invalid chart name. Please adjust your chartType parameter.');
						});}))
						: false;
				});
			}
		};
	}]);
	return moduleName;
}));<|endoftext|>


<commit_before>// Copyright 2013 Traceur Authors.
//
// 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.

'use strict';

var path = require('path');
var flags;
var cmdName = path.basename(process.argv[1]);
try {
  flags = new (require('commander').Command)(cmdName);
} catch (ex) {
  console.error('Commander.js is required for this to work. To install it ' +
                'run:\n\n  npm install commander\n');
  process.exit(1);
}
flags.setMaxListeners(100);

var traceur = require('./traceur.js');

flags.option('--out <FILE>', 'Compile all input files into a single file');

flags.option('--sourcemap', 'Generate source maps');
flags.on('sourcemap', function() {
  flags.sourceMaps = traceur.options.sourceMaps = true;
});

flags.option('--longhelp', 'Show all known options');
flags.on('longhelp', function() {
  flags.help();
  process.exit();
});

flags.on('--help', function() {
  console.log('  Examples:');
  console.log('');
  console.log('    $ %s a.js [args]', cmdName);
  console.log('    $ %s --out compiled.js b.js c.js', cmdName);
  console.log('');
});

traceur.options.addOptions(flags);

flags.usage('[options] [files]');

// Override commander.js's optionHelp to filter out the Traceur feature flags
// from showing up in the help message.
var optionHelp = flags.optionHelp;
flags.optionHelp = function() {
  if (!flags.longhelp) {
    this.options = this.options.filter(function(command) {
      var dashedName = command.long.slice(2);
      return traceur.options.filterOption(dashedName);
    });
  }
  return optionHelp.call(this);
}

/**
 * HACK: Process arguments so that in interpret mode, commander.js only parses
 * the flags, without the file name and anything past that. If an invalid flag
 * is encountered, commander.js error reporting is emulated instead.
 * @param {Array.<string>} argv
 * @return {Array.<string>}
 */
function processArguments(argv) {
  // Preserve the original.
  argv = argv.slice();

  var interpretMode = true;
  for (var i = 2; i < argv.length; i++) {
    var arg = argv[i], index;
    if (arg === '--')
      break;

    // Normalize flags in-place.
    if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
      // TODO: Is this needed at all for traceur?
      arg = arg.slice(1).split('').map(function(flag) {
        return '-' + flag;
      });
      // Insert the normalized flags in argv.
      argv.splice.apply(argv, [i, 1].concat(arg));
      // Grab the first normalized flag and process it as usual.
      arg = argv[i];
    } else if (/^--/.test(arg) && (index = arg.indexOf('=')) !== -1) {
      // Insert the flag argument in argv.
      argv.splice(i + 1, 0, arg.slice(index + 1));
      // Replace the flag with the stripped version and process it as usual.
      arg = argv[i] = arg.slice(0, index);
    }

    var option = flags.optionFor(arg);
    if (option) {
      if (arg === '--out')
        interpretMode = false;

      if (option.required)
        i++;
      else if (option.optional) {
        arg = argv[i + 1];
        if (arg && arg[0] !== '-')
          i++;
      }
    } else if (arg[0] === '-') {
      // HACK: Because commander.js has a flexible policy, this is the only
      // reliable way of reporting invalid flags to the user, and it's limited
      // to the first invalid flag encountered.
      console.log('\n  error: unknown option `%s\'\n', arg);
      process.exit(1);
    } else if (interpretMode) {
      // Add a hint to stop commander.js from parsing following arguments.
      // Note that this means that --out must come before any unknown flag as
      // well as before any filename for it to be used as the out flag.
      argv.splice(i, 0, '--');
      // Save traceur flags for interpret.js.
      argv.flags = argv.slice(2, i);
      break;
    }
  }
  return argv;
}

var argv = processArguments(process.argv);
flags.parse(argv);

var includes = flags.args;

if (!includes.length) {
  // TODO: Start trepl
  console.error('\n  Error: At least one input file is needed');
  flags.help();
  process.exit(1);
}

var interpret = require('./interpreter.js');
var compiler = require('./compiler.js');
var compileToSingleFile = compiler.compileToSingleFile;
var compileToDirectory = compiler.compileToDirectory;

var out = flags.out;
if (out) {
  var isSingleFileCompile = /\.js$/.test(out);
  if (isSingleFileCompile)
    compileToSingleFile(out, includes, flags.sourceMaps);
  else
    compileToDirectory(out, includes, flags.sourceMaps);
} else {
  interpret(includes[0], includes.slice(1), argv.flags);
}<commit_msg>Interpreter: handle --help and -h correctly.<commit_after>// Copyright 2013 Traceur Authors.
//
// 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.

'use strict';

var path = require('path');
var flags;
var cmdName = path.basename(process.argv[1]);
try {
  flags = new (require('commander').Command)(cmdName);
} catch (ex) {
  console.error('Commander.js is required for this to work. To install it ' +
                'run:\n\n  npm install commander\n');
  process.exit(1);
}
flags.setMaxListeners(100);

var traceur = require('./traceur.js');

flags.option('--out <FILE>', 'Compile all input files into a single file');

flags.option('--sourcemap', 'Generate source maps');
flags.on('sourcemap', function() {
  flags.sourceMaps = traceur.options.sourceMaps = true;
});

flags.option('--longhelp', 'Show all known options');
flags.on('longhelp', function() {
  flags.help();
  process.exit();
});

flags.on('--help', function() {
  console.log('  Examples:');
  console.log('');
  console.log('    $ %s a.js [args]', cmdName);
  console.log('    $ %s --out compiled.js b.js c.js', cmdName);
  console.log('');
});

traceur.options.addOptions(flags);

flags.usage('[options] [files]');

// Override commander.js's optionHelp to filter out the Traceur feature flags
// from showing up in the help message.
var optionHelp = flags.optionHelp;
flags.optionHelp = function() {
  if (!flags.longhelp) {
    this.options = this.options.filter(function(command) {
      var dashedName = command.long.slice(2);
      return traceur.options.filterOption(dashedName);
    });
  }
  return optionHelp.call(this);
}

/**
 * HACK: Process arguments so that in interpret mode, commander.js only parses
 * the flags, without the file name and anything past that. If an invalid flag
 * is encountered, commander.js error reporting is emulated instead.
 * @param {Array.<string>} argv
 * @return {Array.<string>}
 */
function processArguments(argv) {
  // Preserve the original.
  argv = argv.slice();

  var interpretMode = true;
  for (var i = 2; i < argv.length; i++) {
    var arg = argv[i], index;
    if (arg === '--')
      break;

    // Normalize flags in-place.
    if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
      // TODO: Is this needed at all for traceur?
      arg = arg.slice(1).split('').map(function(flag) {
        return '-' + flag;
      });
      // Insert the normalized flags in argv.
      argv.splice.apply(argv, [i, 1].concat(arg));
      // Grab the first normalized flag and process it as usual.
      arg = argv[i];
    } else if (/^--/.test(arg) && (index = arg.indexOf('=')) !== -1) {
      // Insert the flag argument in argv.
      argv.splice(i + 1, 0, arg.slice(index + 1));
      // Replace the flag with the stripped version and process it as usual.
      arg = argv[i] = arg.slice(0, index);
    }

    var option = flags.optionFor(arg);
    if (option) {
      if (arg === '--out')
        interpretMode = false;

      if (option.required)
        i++;
      else if (option.optional) {
        arg = argv[i + 1];
        if (arg && arg[0] !== '-')
          i++;
      }
    } else if (arg === '-h' || arg === '--help') {
      // HACK: Special case for the implicit help flags, which can't have
      // their own option, as --help would set flags.help to true, shadowing
      // the flags.help() method.
    } else if (arg[0] === '-') {
      // HACK: Because commander.js has a flexible policy, this is the only
      // reliable way of reporting invalid flags to the user, and it's limited
      // to the first invalid flag encountered.
      console.log('\n  error: unknown option `%s\'\n', arg);
      process.exit(1);
    } else if (interpretMode) {
      // Add a hint to stop commander.js from parsing following arguments.
      // Note that this means that --out must come before any unknown flag as
      // well as before any filename for it to be used as the out flag.
      argv.splice(i, 0, '--');
      // Save traceur flags for interpret.js.
      argv.flags = argv.slice(2, i);
      break;
    }
  }
  return argv;
}

var argv = processArguments(process.argv);
flags.parse(argv);

var includes = flags.args;

if (!includes.length) {
  // TODO: Start trepl
  console.error('\n  Error: At least one input file is needed');
  flags.help();
  process.exit(1);
}

var interpret = require('./interpreter.js');
var compiler = require('./compiler.js');
var compileToSingleFile = compiler.compileToSingleFile;
var compileToDirectory = compiler.compileToDirectory;

var out = flags.out;
if (out) {
  var isSingleFileCompile = /\.js$/.test(out);
  if (isSingleFileCompile)
    compileToSingleFile(out, includes, flags.sourceMaps);
  else
    compileToDirectory(out, includes, flags.sourceMaps);
} else {
  interpret(includes[0], includes.slice(1), argv.flags);
}
<|endoftext|>


<commit_before>angular.module('oauth.reddit', ['oauth.utils'])
  .factory('$ngCordovaReddit', reddit);

function reddit($q, $http, $cordovaOauthUtility) {
  return { signin: oauthReddit };

  /*
   * Sign into the Reddit service
   *
   * @param    string clientId
   * @param    string clientSecret
   * @param    array appScope
   * @param    object options
   * @return   promise
   */
  function oauthReddit(clientId, clientSecret, appScope, compact, options) {
    var deferred = $q.defer();
    if(window.cordova) {
      if($cordovaOauthUtility.isInAppBrowserInstalled()) {
        var redirect_uri = "http://localhost/callback";
        if(options !== undefined) {
          if(options.hasOwnProperty("redirect_uri")) {
              redirect_uri = options.redirect_uri;
          }
        }
        var browserRef = window.cordova.InAppBrowser.open('https://ssl.reddit.com/api/v1/authorize' + (compact ? '.compact' : '') + '?client_id=' + clientId + '&redirect_uri=' + redirect_uri + '&duration=permanent&state=ngcordovaoauth&scope=' + appScope.join(",") + '&response_type=code', '_blank', 'location=no,clearsessioncache=yes,clearcache=yes');
        browserRef.addEventListener('loadstart', function(event) {
          if((event.url).indexOf(redirect_uri) === 0) {
            requestToken = (event.url).split("code=")[1];
            $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
            $http.defaults.headers.post.Authorization = 'Basic ' + btoa(clientId + ":" + clientSecret);
            $http({method: "post", url: "https://ssl.reddit.com/api/v1/access_token", data: "redirect_uri=" + redirect_uri + "&grant_type=authorization_code" + "&code=" + requestToken })
              .success(function(data) {
                deferred.resolve(data);
              })
              .error(function(data, status) {
                deferred.reject("Problem authenticating");
              })
              .finally(function() {
                setTimeout(function() {
                    browserRef.close();
                }, 10);
              });
          }
        });
        browserRef.addEventListener('exit', function(event) {
          deferred.reject("The sign in flow was canceled");
        });
      } else {
        deferred.reject("Could not find InAppBrowser plugin");
      }
    } else {
      deferred.reject("Cannot authenticate via a web browser");
    }
    return deferred.promise;
  }
}

reddit.$inject = ['$q', '$http', '$cordovaOauthUtility'];
<commit_msg>IIFE reddit<commit_after>(function() {
  'use strict';

  angular.module('oauth.reddit', ['oauth.utils'])
    .factory('$ngCordovaReddit', reddit);

  function reddit($q, $http, $cordovaOauthUtility) {
    return { signin: oauthReddit };

    /*
     * Sign into the Reddit service
     *
     * @param    string clientId
     * @param    string clientSecret
     * @param    array appScope
     * @param    object options
     * @return   promise
     */
    function oauthReddit(clientId, clientSecret, appScope, compact, options) {
      var deferred = $q.defer();
      if(window.cordova) {
        if($cordovaOauthUtility.isInAppBrowserInstalled()) {
          var redirect_uri = "http://localhost/callback";
          if(options !== undefined) {
            if(options.hasOwnProperty("redirect_uri")) {
                redirect_uri = options.redirect_uri;
            }
          }
          var browserRef = window.cordova.InAppBrowser.open('https://ssl.reddit.com/api/v1/authorize' + (compact ? '.compact' : '') + '?client_id=' + clientId + '&redirect_uri=' + redirect_uri + '&duration=permanent&state=ngcordovaoauth&scope=' + appScope.join(",") + '&response_type=code', '_blank', 'location=no,clearsessioncache=yes,clearcache=yes');
          browserRef.addEventListener('loadstart', function(event) {
            if((event.url).indexOf(redirect_uri) === 0) {
              requestToken = (event.url).split("code=")[1];
              $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
              $http.defaults.headers.post.Authorization = 'Basic ' + btoa(clientId + ":" + clientSecret);
              $http({method: "post", url: "https://ssl.reddit.com/api/v1/access_token", data: "redirect_uri=" + redirect_uri + "&grant_type=authorization_code" + "&code=" + requestToken })
                .success(function(data) {
                  deferred.resolve(data);
                })
                .error(function(data, status) {
                  deferred.reject("Problem authenticating");
                })
                .finally(function() {
                  setTimeout(function() {
                      browserRef.close();
                  }, 10);
                });
            }
          });
          browserRef.addEventListener('exit', function(event) {
            deferred.reject("The sign in flow was canceled");
          });
        } else {
          deferred.reject("Could not find InAppBrowser plugin");
        }
      } else {
        deferred.reject("Cannot authenticate via a web browser");
      }
      return deferred.promise;
    }
  }

  reddit.$inject = ['$q', '$http', '$cordovaOauthUtility'];
})();
<|endoftext|>


<commit_before>import { Vector3 } from '../math/Vector3.js';
import { Vector2 } from '../math/Vector2.js';
import { Sphere } from '../math/Sphere.js';
import { Ray } from '../math/Ray.js';
import { Matrix4 } from '../math/Matrix4.js';
import { Object3D } from '../core/Object3D.js';
import { Triangle } from '../math/Triangle.js';
import { Face3 } from '../core/Face3.js';
import { DoubleSide, BackSide, TrianglesDrawMode } from '../constants.js';
import { MeshBasicMaterial } from '../materials/MeshBasicMaterial.js';
import { BufferGeometry } from '../core/BufferGeometry.js';

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author mikael emtinger / http://gomo.se/
 * @author jonobr1 / http://jonobr1.com/
 */

function Mesh( geometry, material ) {

	Object3D.call( this );

	this.type = 'Mesh';

	this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
	this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );

	this.drawMode = TrianglesDrawMode;

	this.updateMorphTargets();

}

Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {

	constructor: Mesh,

	isMesh: true,

	setDrawMode: function ( value ) {

		this.drawMode = value;

	},

	copy: function ( source ) {

		Object3D.prototype.copy.call( this, source );

		this.drawMode = source.drawMode;

		if ( source.morphTargetInfluences !== undefined ) {

			this.morphTargetInfluences = source.morphTargetInfluences.slice();

		}

		if ( source.morphTargetDictionary !== undefined ) {

			this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );

		}

		return this;

	},

	updateMorphTargets: function () {

		var geometry = this.geometry;
		var m, ml, name;

		if ( geometry.isBufferGeometry ) {

			var morphAttributes = geometry.morphAttributes;
			var keys = Object.keys( morphAttributes );

			if ( keys.length > 0 ) {

				var morphAttribute = morphAttributes[ keys[ 0 ] ];

				if ( morphAttribute !== undefined ) {

					this.morphTargetInfluences = [];
					this.morphTargetDictionary = {};

					for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {

						name = morphAttribute[ m ].name || String( m );

						this.morphTargetInfluences.push( 0 );
						this.morphTargetDictionary[ name ] = m;

					}

				}

			}

		} else {

			var morphTargets = geometry.morphTargets;

			if ( morphTargets !== undefined && morphTargets.length > 0 ) {

				console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );

			}

		}

	},

	raycast: ( function () {

		var inverseMatrix = new Matrix4();
		var ray = new Ray();
		var sphere = new Sphere();

		var vA = new Vector3();
		var vB = new Vector3();
		var vC = new Vector3();

		var tempA = new Vector3();
		var tempB = new Vector3();
		var tempC = new Vector3();

		var uvA = new Vector2();
		var uvB = new Vector2();
		var uvC = new Vector2();

		var intersectionPoint = new Vector3();
		var intersectionPointWorld = new Vector3();

		function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {

			var intersect;

			if ( material.side === BackSide ) {

				intersect = ray.intersectTriangle( pC, pB, pA, true, point );

			} else {

				intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );

			}

			if ( intersect === null ) return null;

			intersectionPointWorld.copy( point );
			intersectionPointWorld.applyMatrix4( object.matrixWorld );

			var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );

			if ( distance < raycaster.near || distance > raycaster.far ) return null;

			return {
				distance: distance,
				point: intersectionPointWorld.clone(),
				object: object
			};

		}

		function checkBufferGeometryIntersection( object, material, raycaster, ray, position, uv, a, b, c ) {

			vA.fromBufferAttribute( position, a );
			vB.fromBufferAttribute( position, b );
			vC.fromBufferAttribute( position, c );

			var intersection = checkIntersection( object, material, raycaster, ray, vA, vB, vC, intersectionPoint );

			if ( intersection ) {

				if ( uv ) {

					uvA.fromBufferAttribute( uv, a );
					uvB.fromBufferAttribute( uv, b );
					uvC.fromBufferAttribute( uv, c );

					intersection.uv = Triangle.getUV( intersectionPoint, vA, vB, vC, uvA, uvB, uvC, new Vector2() );

				}

				var face = new Face3( a, b, c );
				Triangle.getNormal( vA, vB, vC, face.normal );

				intersection.face = face;

			}

			return intersection;

		}

		return function raycast( raycaster, intersects ) {

			var geometry = this.geometry;
			var material = this.material;
			var matrixWorld = this.matrixWorld;

			if ( material === undefined ) return;

			// Checking boundingSphere distance to ray

			if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();

			sphere.copy( geometry.boundingSphere );
			sphere.applyMatrix4( matrixWorld );

			if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;

			//

			inverseMatrix.getInverse( matrixWorld );
			ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );

			// Check boundingBox before continuing

			if ( geometry.boundingBox !== null ) {

				if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;

			}

			var intersection;

			if ( geometry.isBufferGeometry ) {

				var a, b, c;
				var index = geometry.index;
				var position = geometry.attributes.position;
				var uv = geometry.attributes.uv;
				var groups = geometry.groups;
				var drawRange = geometry.drawRange;
				var i, j, il, jl;
				var group, groupMaterial;
				var start, end;

				if ( index !== null ) {

					// indexed buffer geometry

					if ( Array.isArray( material ) ) {

						for ( i = 0, il = groups.length; i < il; i ++ ) {

							group = groups[ i ];
							groupMaterial = material[ group.materialIndex ];

							start = Math.max( group.start, drawRange.start );
							end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );

							for ( j = start, jl = end; j < jl; j += 3 ) {

								a = index.getX( j );
								b = index.getX( j + 1 );
								c = index.getX( j + 2 );

								intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, ray, position, uv, a, b, c );

								if ( intersection ) {

									intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
									intersects.push( intersection );

								}

							}

						}

					} else {

						start = Math.max( 0, drawRange.start );
						end = Math.min( index.count, ( drawRange.start + drawRange.count ) );

						for ( i = start, il = end; i < il; i += 3 ) {

							a = index.getX( i );
							b = index.getX( i + 1 );
							c = index.getX( i + 2 );

							intersection = checkBufferGeometryIntersection( this, material, raycaster, ray, position, uv, a, b, c );

							if ( intersection ) {

								intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
								intersects.push( intersection );

							}

						}

					}

				} else if ( position !== undefined ) {

					// non-indexed buffer geometry

					if ( Array.isArray( material ) ) {

						for ( i = 0, il = groups.length; i < il; i ++ ) {

							group = groups[ i ];
							groupMaterial = material[ group.materialIndex ];

							start = Math.max( group.start, drawRange.start );
							end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );

							for ( j = start, jl = end; j < jl; j += 3 ) {

								a = j;
								b = j + 1;
								c = j + 2;

								intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, ray, position, uv, a, b, c );

								if ( intersection ) {

									intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
									intersects.push( intersection );

								}

							}

						}

					} else {

						start = Math.max( 0, drawRange.start );
						end = Math.min( position.count, ( drawRange.start + drawRange.count ) );

						for ( i = start, il = end; i < il; i += 3 ) {

							a = i;
							b = i + 1;
							c = i + 2;

							intersection = checkBufferGeometryIntersection( this, material, raycaster, ray, position, uv, a, b, c );

							if ( intersection ) {

								intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
								intersects.push( intersection );

							}

						}

					}

				}

			} else if ( geometry.isGeometry ) {

				var fvA, fvB, fvC;
				var isMultiMaterial = Array.isArray( material );

				var vertices = geometry.vertices;
				var faces = geometry.faces;
				var uvs;

				var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
				if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;

				for ( var f = 0, fl = faces.length; f < fl; f ++ ) {

					var face = faces[ f ];
					var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;

					if ( faceMaterial === undefined ) continue;

					fvA = vertices[ face.a ];
					fvB = vertices[ face.b ];
					fvC = vertices[ face.c ];

					if ( faceMaterial.morphTargets === true ) {

						var morphTargets = geometry.morphTargets;
						var morphInfluences = this.morphTargetInfluences;

						vA.set( 0, 0, 0 );
						vB.set( 0, 0, 0 );
						vC.set( 0, 0, 0 );

						for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {

							var influence = morphInfluences[ t ];

							if ( influence === 0 ) continue;

							var targets = morphTargets[ t ].vertices;

							vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
							vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
							vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );

						}

						vA.add( fvA );
						vB.add( fvB );
						vC.add( fvC );

						fvA = vA;
						fvB = vB;
						fvC = vC;

					}

					intersection = checkIntersection( this, faceMaterial, raycaster, ray, fvA, fvB, fvC, intersectionPoint );

					if ( intersection ) {

						if ( uvs && uvs[ f ] ) {

							var uvs_f = uvs[ f ];
							uvA.copy( uvs_f[ 0 ] );
							uvB.copy( uvs_f[ 1 ] );
							uvC.copy( uvs_f[ 2 ] );

							intersection.uv = Triangle.getUV( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC, new Vector2() );

						}

						intersection.face = face;
						intersection.faceIndex = f;
						intersects.push( intersection );

					}

				}

			}

		};

	}() ),

	clone: function () {

		return new this.constructor( this.geometry, this.material ).copy( this );

	}

} );

export { Mesh };
<commit_msg>Mesh: Improve handling of material index.<commit_after>import { Vector3 } from '../math/Vector3.js';
import { Vector2 } from '../math/Vector2.js';
import { Sphere } from '../math/Sphere.js';
import { Ray } from '../math/Ray.js';
import { Matrix4 } from '../math/Matrix4.js';
import { Object3D } from '../core/Object3D.js';
import { Triangle } from '../math/Triangle.js';
import { Face3 } from '../core/Face3.js';
import { DoubleSide, BackSide, TrianglesDrawMode } from '../constants.js';
import { MeshBasicMaterial } from '../materials/MeshBasicMaterial.js';
import { BufferGeometry } from '../core/BufferGeometry.js';

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author mikael emtinger / http://gomo.se/
 * @author jonobr1 / http://jonobr1.com/
 */

function Mesh( geometry, material ) {

	Object3D.call( this );

	this.type = 'Mesh';

	this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
	this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );

	this.drawMode = TrianglesDrawMode;

	this.updateMorphTargets();

}

Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {

	constructor: Mesh,

	isMesh: true,

	setDrawMode: function ( value ) {

		this.drawMode = value;

	},

	copy: function ( source ) {

		Object3D.prototype.copy.call( this, source );

		this.drawMode = source.drawMode;

		if ( source.morphTargetInfluences !== undefined ) {

			this.morphTargetInfluences = source.morphTargetInfluences.slice();

		}

		if ( source.morphTargetDictionary !== undefined ) {

			this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );

		}

		return this;

	},

	updateMorphTargets: function () {

		var geometry = this.geometry;
		var m, ml, name;

		if ( geometry.isBufferGeometry ) {

			var morphAttributes = geometry.morphAttributes;
			var keys = Object.keys( morphAttributes );

			if ( keys.length > 0 ) {

				var morphAttribute = morphAttributes[ keys[ 0 ] ];

				if ( morphAttribute !== undefined ) {

					this.morphTargetInfluences = [];
					this.morphTargetDictionary = {};

					for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {

						name = morphAttribute[ m ].name || String( m );

						this.morphTargetInfluences.push( 0 );
						this.morphTargetDictionary[ name ] = m;

					}

				}

			}

		} else {

			var morphTargets = geometry.morphTargets;

			if ( morphTargets !== undefined && morphTargets.length > 0 ) {

				console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );

			}

		}

	},

	raycast: ( function () {

		var inverseMatrix = new Matrix4();
		var ray = new Ray();
		var sphere = new Sphere();

		var vA = new Vector3();
		var vB = new Vector3();
		var vC = new Vector3();

		var tempA = new Vector3();
		var tempB = new Vector3();
		var tempC = new Vector3();

		var uvA = new Vector2();
		var uvB = new Vector2();
		var uvC = new Vector2();

		var intersectionPoint = new Vector3();
		var intersectionPointWorld = new Vector3();

		function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {

			var intersect;

			if ( material.side === BackSide ) {

				intersect = ray.intersectTriangle( pC, pB, pA, true, point );

			} else {

				intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );

			}

			if ( intersect === null ) return null;

			intersectionPointWorld.copy( point );
			intersectionPointWorld.applyMatrix4( object.matrixWorld );

			var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );

			if ( distance < raycaster.near || distance > raycaster.far ) return null;

			return {
				distance: distance,
				point: intersectionPointWorld.clone(),
				object: object
			};

		}

		function checkBufferGeometryIntersection( object, material, raycaster, ray, position, uv, a, b, c ) {

			vA.fromBufferAttribute( position, a );
			vB.fromBufferAttribute( position, b );
			vC.fromBufferAttribute( position, c );

			var intersection = checkIntersection( object, material, raycaster, ray, vA, vB, vC, intersectionPoint );

			if ( intersection ) {

				if ( uv ) {

					uvA.fromBufferAttribute( uv, a );
					uvB.fromBufferAttribute( uv, b );
					uvC.fromBufferAttribute( uv, c );

					intersection.uv = Triangle.getUV( intersectionPoint, vA, vB, vC, uvA, uvB, uvC, new Vector2() );

				}

				var face = new Face3( a, b, c );
				Triangle.getNormal( vA, vB, vC, face.normal );

				intersection.face = face;

			}

			return intersection;

		}

		return function raycast( raycaster, intersects ) {

			var geometry = this.geometry;
			var material = this.material;
			var matrixWorld = this.matrixWorld;

			if ( material === undefined ) return;

			// Checking boundingSphere distance to ray

			if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();

			sphere.copy( geometry.boundingSphere );
			sphere.applyMatrix4( matrixWorld );

			if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;

			//

			inverseMatrix.getInverse( matrixWorld );
			ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );

			// Check boundingBox before continuing

			if ( geometry.boundingBox !== null ) {

				if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;

			}

			var intersection;

			if ( geometry.isBufferGeometry ) {

				var a, b, c;
				var index = geometry.index;
				var position = geometry.attributes.position;
				var uv = geometry.attributes.uv;
				var groups = geometry.groups;
				var drawRange = geometry.drawRange;
				var i, j, il, jl;
				var group, groupMaterial;
				var start, end;

				if ( index !== null ) {

					// indexed buffer geometry

					if ( Array.isArray( material ) ) {

						for ( i = 0, il = groups.length; i < il; i ++ ) {

							group = groups[ i ];
							groupMaterial = material[ group.materialIndex ];

							start = Math.max( group.start, drawRange.start );
							end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );

							for ( j = start, jl = end; j < jl; j += 3 ) {

								a = index.getX( j );
								b = index.getX( j + 1 );
								c = index.getX( j + 2 );

								intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, ray, position, uv, a, b, c );

								if ( intersection ) {

									intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
									intersection.face.materialIndex = group.materialIndex;
									intersects.push( intersection );

								}

							}

						}

					} else {

						start = Math.max( 0, drawRange.start );
						end = Math.min( index.count, ( drawRange.start + drawRange.count ) );

						for ( i = start, il = end; i < il; i += 3 ) {

							a = index.getX( i );
							b = index.getX( i + 1 );
							c = index.getX( i + 2 );

							intersection = checkBufferGeometryIntersection( this, material, raycaster, ray, position, uv, a, b, c );

							if ( intersection ) {

								intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
								intersects.push( intersection );

							}

						}

					}

				} else if ( position !== undefined ) {

					// non-indexed buffer geometry

					if ( Array.isArray( material ) ) {

						for ( i = 0, il = groups.length; i < il; i ++ ) {

							group = groups[ i ];
							groupMaterial = material[ group.materialIndex ];

							start = Math.max( group.start, drawRange.start );
							end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );

							for ( j = start, jl = end; j < jl; j += 3 ) {

								a = j;
								b = j + 1;
								c = j + 2;

								intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, ray, position, uv, a, b, c );

								if ( intersection ) {

									intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
									intersection.face.materialIndex = group.materialIndex;
									intersects.push( intersection );

								}

							}

						}

					} else {

						start = Math.max( 0, drawRange.start );
						end = Math.min( position.count, ( drawRange.start + drawRange.count ) );

						for ( i = start, il = end; i < il; i += 3 ) {

							a = i;
							b = i + 1;
							c = i + 2;

							intersection = checkBufferGeometryIntersection( this, material, raycaster, ray, position, uv, a, b, c );

							if ( intersection ) {

								intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
								intersects.push( intersection );

							}

						}

					}

				}

			} else if ( geometry.isGeometry ) {

				var fvA, fvB, fvC;
				var isMultiMaterial = Array.isArray( material );

				var vertices = geometry.vertices;
				var faces = geometry.faces;
				var uvs;

				var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
				if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;

				for ( var f = 0, fl = faces.length; f < fl; f ++ ) {

					var face = faces[ f ];
					var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;

					if ( faceMaterial === undefined ) continue;

					fvA = vertices[ face.a ];
					fvB = vertices[ face.b ];
					fvC = vertices[ face.c ];

					if ( faceMaterial.morphTargets === true ) {

						var morphTargets = geometry.morphTargets;
						var morphInfluences = this.morphTargetInfluences;

						vA.set( 0, 0, 0 );
						vB.set( 0, 0, 0 );
						vC.set( 0, 0, 0 );

						for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {

							var influence = morphInfluences[ t ];

							if ( influence === 0 ) continue;

							var targets = morphTargets[ t ].vertices;

							vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
							vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
							vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );

						}

						vA.add( fvA );
						vB.add( fvB );
						vC.add( fvC );

						fvA = vA;
						fvB = vB;
						fvC = vC;

					}

					intersection = checkIntersection( this, faceMaterial, raycaster, ray, fvA, fvB, fvC, intersectionPoint );

					if ( intersection ) {

						if ( uvs && uvs[ f ] ) {

							var uvs_f = uvs[ f ];
							uvA.copy( uvs_f[ 0 ] );
							uvB.copy( uvs_f[ 1 ] );
							uvC.copy( uvs_f[ 2 ] );

							intersection.uv = Triangle.getUV( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC, new Vector2() );

						}

						intersection.face = face;
						intersection.faceIndex = f;
						intersects.push( intersection );

					}

				}

			}

		};

	}() ),

	clone: function () {

		return new this.constructor( this.geometry, this.material ).copy( this );

	}

} );

export { Mesh };
<|endoftext|>


<commit_before>/**
 * @class Mesh
 * @extends Entity
 */

EZ3.Mesh = function(geometry, material) {
  EZ3.Entity.call(this);

  this._uv = new EZ3.Buffer();
  this._color = new EZ3.Buffer();
  this._index = new EZ3.Buffer();
  this._normal = new EZ3.Buffer();
  this._vertex = new EZ3.Buffer();
  this._tangent = new EZ3.Buffer();
  this._bitangent = new EZ3.Buffer();

  this._dynamic = false;
  this._material = (material instanceof EZ3.Material) ? material : null;
  this._geometry = (geometry instanceof EZ3.Geometry) ? geometry : null;
};

EZ3.Mesh.prototype = Object.create(EZ3.Entity.prototype);
EZ3.Mesh.prototype.constructor = EZ3.Mesh;

EZ3.Mesh.prototype._setupBuffer = function(gl) {
  if (this._geometry) {

    if (this._geometry.uvs.dirty) {
      this._geometry.uvs.dirty = false;
      this._uv.update(gl, gl.ARRAY_BUFFER, gl.FLOAT, this._geometry.uvs, gl.STATIC_DRAW);
    }

    if(this._geometry.colors.dirty) {
      this._geometry.colors.dirty = false;
      this._color.update(gl, gl.ARRAY_BUFFER, gl.FLOAT, this._geometry.colors, gl.STATIC_DRAW);
    }

    if(this._geometry.normals.dity) {
      this._geometry.normals.dirty = false;
      this._normal.update(gl, gl.ARRAY_BUFFER, gl.FLOAT, this._geometry.normals, gl.STATIC_DRAW);
    }

    if(this._geometry.vertices.dirty) {
      this._geometry.vertices.dirty = false;
      this._vertex.update(gl, gl.ARRAY_BUFFER, gl.FLOAT, this._geometry.vertices, gl.STATIC_DRAW);
    }

    if(this._geometry.tangents.dirty) {
      this._geometry.tangents.dirty = false;
      this._tangent.update(gl, gl.ARRAY_BUFFER, gl.FLOAT, this._geometry.tangents, gl.STATIC_DRAW);
    }

    if(this._geometry.bitangents.dirty) {
      this._geometry.bitangents.dirty = false;
      this._bitangent.update(gl, gl.ARRAY_BUFFER, gl.FLOAT, this._geometry.bitangents, gl.STATIC_DRAW);
    }

    if(this._geometry.indices.dirty) {
      this._geometry.indices.dirty = false;
      this._index.update(gl, gl.ELEMENT_ARRAY_BUFFER, gl.UNSIGNED_SHORT, this._geometry.indices, gl.STATIC_DRAW);
    }
  }
};

EZ3.Mesh.prototype._setupProgram = function(gl) {
  if (this._material.dirty) {
    this._material.dirty = false;

    var programBuilder = new EZ3.GLSLProgramBuilder();
    this._material.program = programBuilder.buildProgram(gl, this._material);
  }
};

Object.defineProperty(EZ3.Mesh.prototype, "material", {
  get: function() {
    return this._material;
  },
  set: function(material) {
    if(material instanceof EZ3.Material){
      this._material = material;
      this._material.dirty = true;
    }
  }
});

Object.defineProperty(EZ3.Mesh.prototype, "geometry", {
  get: function() {
    return this._geometry;
  },
  set: function(geometry) {
    if(geometry instanceof EZ3.Geometry)
      this._geometry = geometry;
  }
});

EZ3.Mesh.prototype.setup = function(gl) {
  this._setupProgram(gl);
  this._setupBuffer(gl);
};

EZ3.Mesh.prototype.render = function(gl) {
  var program = this._material.program;

  if(this._index.id)
    this._index.setup(gl, gl.ELEMENT_ARRAY_BUFFER);

  if (this._uv.id && (typeof program.uvLayout !== undefined))
    this._uv.setup(gl, gl.ARRAY_BUFFER, program.uvLayout, EZ3.Buffer.UV_LENGTH, gl.FLOAT, false, 0, 0);

  if (this._color.id && (typeof program.colorLayout !== undefined))
    this._color.setup(gl, gl.ARRAY_BUFFER, program.colorLayout, EZ3.Buffer.COLOR_LENGTH, gl.FLOAT, false, 0, 0);

  if(this._normal.id && (typeof program.normalLayout !== undefined))
    this._normal.setup(gl, gl.ARRAY_BUFFER, program.normalLayout, EZ3.Buffer.NORMAL_LENGTH, gl.FLOAT, false, 0, 0);

  if(this._vertex.id && (typeof program.vertexLayout !== undefined))
    this._vertex.setup(gl, gl.ARRAY_BUFFER, program.vertexLayout, EZ3.Buffer.VERTEX_LENGTH, gl.FLOAT, false, 0, 0);

  if(this._tangent.id && (typeof program.tangentLayout !== undefined))
    this._tangent.setup(gl, gl.ARRAY_BUFFER, program.tangentLayout, EZ3.Buffer.TANGENT_LENGTH, gl.FLOAT, false, 0, 0);

  if(this._bitangent.id && (typeof program.bitangentLayout !== undefined))
    this._bitangent.setup(gl, gl.ARRAY_BUFFER, program.bitangentLayout, EZ3.Buffer.BITANGENT_LENGTH, gl.FLOAT, false, 0, 0);

  if(this._index.id)
    gl.drawElements(gl.TRIANGLES, this._index.data.length, gl.UNSIGNED_SHORT, 0);
  else if(this._vertex.id)
    gl.drawArrays(gl.TRIANGLES, 0, this._vertex.data.length / 3);
};
<commit_msg>Updated Mesh.js<commit_after>/**
 * @class Mesh
 * @extends Entity
 */

EZ3.Mesh = function(geometry, material) {
  EZ3.Entity.call(this);

  this._uv = new EZ3.Buffer();
  this._color = new EZ3.Buffer();
  this._index = new EZ3.Buffer();
  this._normal = new EZ3.Buffer();
  this._vertex = new EZ3.Buffer();
  this._tangent = new EZ3.Buffer();
  this._bitangent = new EZ3.Buffer();

  this._dynamic = false;
  this._material = (material instanceof EZ3.Material) ? material : null;
  this._geometry = (geometry instanceof EZ3.Geometry) ? geometry : null;
};

EZ3.Mesh.prototype = Object.create(EZ3.Entity.prototype);
EZ3.Mesh.prototype.constructor = EZ3.Mesh;

EZ3.Mesh.prototype._setupBuffer = function(gl) {
  if (this._geometry) {

    if (this._geometry.uvs.dirty && this._geometry.uvs.length) {
      this._geometry.uvs.dirty = false;
      this._uv.update(gl, gl.ARRAY_BUFFER, gl.FLOAT, this._geometry.uvs, gl.STATIC_DRAW);
    }

    if(this._geometry.colors.dirty && this._geometry.colors.length) {
      this._geometry.colors.dirty = false;
      this._color.update(gl, gl.ARRAY_BUFFER, gl.FLOAT, this._geometry.colors, gl.STATIC_DRAW);
    }

    if(this._geometry.normals.dirty && this._geometry.normals.length) {
      this._geometry.normals.dirty = false;
      this._normal.update(gl, gl.ARRAY_BUFFER, gl.FLOAT, this._geometry.normals, gl.STATIC_DRAW);
    }

    if(this._geometry.vertices.dirty && this._geometry.vertices.length) {
      this._geometry.vertices.dirty = false;
      this._vertex.update(gl, gl.ARRAY_BUFFER, gl.FLOAT, this._geometry.vertices, gl.STATIC_DRAW);
    }

    if(this._geometry.tangents.dirty && this._geometry.tangents.length) {
      this._geometry.tangents.dirty = false;
      this._tangent.update(gl, gl.ARRAY_BUFFER, gl.FLOAT, this._geometry.tangents, gl.STATIC_DRAW);
    }

    if(this._geometry.bitangents.dirty && this._geometry.bitangents.length) {
      this._geometry.bitangents.dirty = false;
      this._bitangent.update(gl, gl.ARRAY_BUFFER, gl.FLOAT, this._geometry.bitangents, gl.STATIC_DRAW);
    }

    if(this._geometry.indices.dirty && this.geometry.indices.length) {
      this._geometry.indices.dirty = false;
      this._index.update(gl, gl.ELEMENT_ARRAY_BUFFER, gl.UNSIGNED_SHORT, this._geometry.indices, gl.STATIC_DRAW);
    }
  }
};

EZ3.Mesh.prototype._setupProgram = function(gl) {
  if (this._material.dirty) {
    this._material.dirty = false;

    var programBuilder = new EZ3.GLSLProgramBuilder();
    this._material.program = programBuilder.buildProgram(gl, this._material);
  }
};

Object.defineProperty(EZ3.Mesh.prototype, "material", {
  get: function() {
    return this._material;
  },
  set: function(material) {
    if(material instanceof EZ3.Material){
      this._material = material;
      this._material.dirty = true;
    }
  }
});

Object.defineProperty(EZ3.Mesh.prototype, "geometry", {
  get: function() {
    return this._geometry;
  },
  set: function(geometry) {
    if(geometry instanceof EZ3.Geometry)
      this._geometry = geometry;
  }
});

EZ3.Mesh.prototype.setup = function(gl) {
  this._setupProgram(gl);
  this._setupBuffer(gl);
};

EZ3.Mesh.prototype.render = function(gl) {
  var program = this._material.program;

  if(this._index.id)
    this._index.setup(gl, gl.ELEMENT_ARRAY_BUFFER);

  if (this._uv.id)
    this._uv.setup(gl, gl.ARRAY_BUFFER, program.uvLayout, EZ3.Buffer.UV_LENGTH, gl.FLOAT, false, 0, 0);

  if (this._color.id)
    this._color.setup(gl, gl.ARRAY_BUFFER, program.colorLayout, EZ3.Buffer.COLOR_LENGTH, gl.FLOAT, false, 0, 0);

  if(this._normal.id)
    this._normal.setup(gl, gl.ARRAY_BUFFER, program.normalLayout, EZ3.Buffer.NORMAL_LENGTH, gl.FLOAT, false, 0, 0);

  if(this._vertex.id)
    this._vertex.setup(gl, gl.ARRAY_BUFFER, program.vertexLayout, EZ3.Buffer.VERTEX_LENGTH, gl.FLOAT, false, 0, 0);

  if(this._tangent.id)
    this._tangent.setup(gl, gl.ARRAY_BUFFER, program.tangentLayout, EZ3.Buffer.TANGENT_LENGTH, gl.FLOAT, false, 0, 0);

  if(this._bitangent.id)
    this._bitangent.setup(gl, gl.ARRAY_BUFFER, program.bitangentLayout, EZ3.Buffer.BITANGENT_LENGTH, gl.FLOAT, false, 0, 0);

  if(this._index.id && this._index.data.length)
    gl.drawElements(gl.TRIANGLES, this._index.data.length, gl.UNSIGNED_SHORT, 0);
  else if(this._vertex.id && this._vertex.data.length)
    gl.drawArrays(gl.TRIANGLES, 0, this._vertex.data.length / 3);
};
<|endoftext|>


<commit_before>import { SpriteWidth, SpriteHeight, SpriteRatioX, SpriteRatioY, Bounds } from "../Constants.js";
import { Wall } from "../SpriteConstants";

const MaxX = 1;
const MaxY = 0;

class Room extends Phaser.Group {

  constructor(game, parent, name) {
    super(game, parent, name, false, true, Phaser.Physics.ARCADE);
  }

  createRandomLine(x1, y1, x2, y2, division = 1, varX = 0, varY = 0) {
    const middleX = (x1 + x2) / 2 + (varX * SpriteWidth);
    const middleY = (y1 + y2) / 2 + (varY * SpriteHeight);

    const middleXBefore = middleX - (middleX % SpriteWidth);
    const middleXAfter =  middleX + (middleX % SpriteWidth);
    const middleYBefore = middleY - (middleY % SpriteHeight);
    const middleYAfter = middleY + (middleY % SpriteHeight);
    if(division > 1) {
      this.createRandomLine(x1, y1, middleXBefore, middleYBefore, division - 1, varX, varY);
      this.createRandomLine(middleXAfter, middleYAfter, x2, y2, division - 1, varX, varY);
    } else {
      this.createLine(x1,y1, middleXBefore, middleYBefore);
      this.createLine(middleXAfter, middleYAfter, x2, y2);
    }
  }

  createLineByTile(x1, y1, nbTilesX, nbTilesY, division, varX, varY) {
    if(nbTilesX < 0 ) {
      throw `createLineByTile ${nbTilesX} is negative`;
    }
    if(nbTilesY < 0 ) {
      throw `createLineByTile ${nbTilesY} is negative`;
    }
    this.createRandomLine(x1, y1, (nbTilesX-1) * SpriteWidth + x1 , (nbTilesY-1) * SpriteHeight + y1, division, varX, varY);
  }

  // //Brasenhem algorithm
  createLine(x1,y1, x2, y2) {
    const dx = Math.abs(x2 - x1);
    const sx = x1 < x2 ? SpriteWidth : -SpriteWidth;
    const dy = Math.abs(y2 - y1);
    const sy = y1 < y2 ? SpriteHeight : -SpriteHeight;
    var err = (dx > dy ? dx : -dy) / 2;

    let x = x1;
    let y = y1;
    while (true) {
      this.createSprite(x,y);
      if (x >= x2 && y >= y2) break;
      if(x < 0 || y < 0 || x > Bounds || y > Bounds) break;
      let e2 = err;
      if (e2 > - dx) {
        err -= dy;
        x += sx;
      }
      if (e2 < dy) {
        err += dx;
        y += sy;
      }
    }
  }

  createSprite(x,y) {
    let sprite = this.create(x, y, Wall);
    sprite.scale.setTo(SpriteRatioX, SpriteRatioY);
    sprite.body.immovable = true;
  }

  ////
  // (x,y) ####
  //       #  #
  //       #  #
  //       #  #
  //       ####
  //
  ///
  createSquare(x, y, nbTilesBySide) {
    this.createRandomSquare(x, y, nbTilesBySide, 1, 0, 0);
  }

  // const division = 3;
  // const varX = -1;
  // const varY = 1;
  createRandomSquare(x, y, nbTilesBySide, division = 3, varX = -1, varY = 1) {
    this.createLineByTile(x, y, nbTilesBySide, 1, division, varX, varY);
    this.createLineByTile(x, y + (nbTilesBySide-1) * SpriteHeight, nbTilesBySide, 1, division, varX, varY);

    //nbtiles - 2 because corner  was drawn  by vertical line
    this.createLineByTile(x, y + SpriteHeight, 1, nbTilesBySide - 2, division, varX, varY);
    this.createLineByTile(x + (nbTilesBySide-1) * SpriteWidth, y + SpriteHeight, 1, nbTilesBySide - 2, division, varX, varY);
  }
}

export default Room;<commit_msg>change param order<commit_after>import { SpriteWidth, SpriteHeight, SpriteRatioX, SpriteRatioY, Bounds } from "../Constants.js";
import { Wall } from "../SpriteConstants";

const MaxX = 1;
const MaxY = 0;

class Room extends Phaser.Group {

  constructor(game, parent, name) {
    super(game, parent, name, false, true, Phaser.Physics.ARCADE);
  }

  createRandomLine(x1, y1, x2, y2, division = 1, varX = 0, varY = 0) {
    const middleX = (x1 + x2) / 2 + (varX * SpriteWidth);
    const middleY = (y1 + y2) / 2 + (varY * SpriteHeight);

    const middleXBefore = middleX - (middleX % SpriteWidth);
    const middleXAfter =  middleX + (middleX % SpriteWidth);
    const middleYBefore = middleY - (middleY % SpriteHeight);
    const middleYAfter = middleY + (middleY % SpriteHeight);
    if(division > 1) {
      this.createRandomLine(x1, y1, middleXBefore, middleYBefore, division - 1, varX, varY);
      this.createRandomLine(middleXAfter, middleYAfter, x2, y2, division - 1, varX, varY);
    } else {
      this.createLine(x1,y1, middleXBefore, middleYBefore);
      this.createLine(middleXAfter, middleYAfter, x2, y2);
    }
  }

  createLineByTile(x1, y1, nbTilesX, nbTilesY, division, varX, varY) {
    if(nbTilesX < 0 ) {
      throw `createLineByTile ${nbTilesX} is negative`;
    }
    if(nbTilesY < 0 ) {
      throw `createLineByTile ${nbTilesY} is negative`;
    }
    this.createRandomLine(x1, y1, (nbTilesX-1) * SpriteWidth + x1 , (nbTilesY-1) * SpriteHeight + y1, division, varX, varY);
  }

  // //Brasenhem algorithm
  createLine(x1,y1, x2, y2) {
    const dx = Math.abs(x2 - x1);
    const sx = x1 < x2 ? SpriteWidth : -SpriteWidth;
    const dy = Math.abs(y2 - y1);
    const sy = y1 < y2 ? SpriteHeight : -SpriteHeight;
    var err = (dx > dy ? dx : -dy) / 2;

    let x = x1;
    let y = y1;
    while (true) {
      this.createSprite(x,y);
      if (x >= x2 && y >= y2) break;
      if(x < 0 || y < 0 || x > Bounds || y > Bounds) break;
      let e2 = err;
      if (e2 > - dx) {
        err -= dy;
        x += sx;
      }
      if (e2 < dy) {
        err += dx;
        y += sy;
      }
    }
  }

  createSprite(x,y) {
    let sprite = this.create(x, y, Wall);
    sprite.scale.setTo(SpriteRatioX, SpriteRatioY);
    sprite.body.immovable = true;
  }

  ////
  // (x,y) ####
  //       #  #
  //       #  #
  //       #  #
  //       ####
  //
  ///
  createSquare(x, y, nbTilesBySide) {
    this.createRandomSquare(x, y, nbTilesBySide, 1, false);
  }

  // const division = 3;
  // const varX = -1;
  // const varY = 1;
  createRandomSquare(x, y, nbTilesBySide, division = 3, random = true) {
    let varX = 0;
    let varY = 0;
    if(random) {

    }
    this.createLineByTile(x, y, nbTilesBySide, 1, division, varX, varY);
    this.createLineByTile(x, y + (nbTilesBySide-1) * SpriteHeight, nbTilesBySide, 1, division, varX, varY);

    //nbtiles - 2 because corner  was drawn  by vertical line
    this.createLineByTile(x, y + SpriteHeight, 1, nbTilesBySide - 2, division, varX, varY);
    this.createLineByTile(x + (nbTilesBySide-1) * SpriteWidth, y + SpriteHeight, 1, nbTilesBySide - 2, division, varX, varY);
  }
}

export default Room;<|endoftext|>


<commit_before>import { readFile, writeFile, mkdirs } from '../async/fs';
import { prompt } from '../async/inquirer';
import gitconfig from '../async/git-config';
import path from 'path';
import handlebars from 'handlebars';
import semver from 'semver';
import validateLicense from 'validate-npm-package-license';
import validateName from 'validate-npm-package-name';
import * as style from './style';

const ROOT_DIR = path.resolve(__dirname, '..', '..');
const TEMPLATES_DIR = path.resolve(ROOT_DIR, 'templates');

const NEON_CLI_VERSION = (async function() {
  return JSON.parse(await readFile(path.resolve(ROOT_DIR, 'package.json'), 'utf8')).version;
})();

async function compile(filename) {
  return handlebars.compile(await readFile(path.resolve(TEMPLATES_DIR, filename), 'utf8'), { noEscape: true });
}

const GITIGNORE_TEMPLATE = compile('.gitignore.hbs');
const CARGO_TEMPLATE     = compile('Cargo.toml.hbs');
const NPM_TEMPLATE       = compile('package.json.hbs');
const INDEXJS_TEMPLATE   = compile('index.js.hbs');
const LIBRS_TEMPLATE     = compile('lib.rs.hbs');
const README_TEMPLATE    = compile('README.md.hbs');
const BUILDRS_TEMPLATE   = compile('build.rs.hbs');

async function guessAuthor() {
  let author = {
    name: process.env.USER || process.env.USERNAME,
    email: undefined
  };
  try {
    let config = await gitconfig();
    if (config.user.name) {
      author.name = config.user.name;
    }
    if (config.user.email) {
      author.email = config.user.email;
    }
    return author;
  } catch (e) {
    return author;
  }
}

export default async function wizard(pwd, name, toolchain) {
  let its = validateName(name);
  if (!its.validForNewPackages) {
    let errors = (its.errors || []).concat(its.warnings || []);
    throw new Error("Sorry, " + errors.join(" and ") + ".");
  }

  // check for a scoped name
  let scoped = name.match(/@([^\/]+)\/(.*)/);
  let [, scope, local] = scoped || [, null, name];

  console.log("This utility will walk you through creating the " + style.project(name) + " Neon project.");
  console.log("It only covers the most common items, and tries to guess sensible defaults.");
  console.log();
  console.log("Press ^C at any time to quit.");

  let root = path.resolve(pwd, local);
  let guess = await guessAuthor();

  let answers = await prompt([
    {
      type: 'input',
      name: 'version',
      message: "version",
      default: "0.1.0",
      validate: function (input) {
        if (semver.valid(input)) {
          return true;
        }
        return "Invalid version: " + input;
      }
    },
    { type: 'input', name: 'description', message: "description"                                              },
    { type: 'input', name: 'node',        message: "node entry point", default: "lib" + path.sep + "index.js" },
    { type: 'input', name: 'git',         message: "git repository"                                           },
    { type: 'input', name: 'author',      message: "author",           default: guess.name                    },
    { type: 'input', name: 'email',       message: "email",            default: guess.email                   },
    {
      type: 'input',
      name: 'license',
      message: "license",
      default: "MIT",
      validate: function (input) {
        let its = validateLicense(input);
        if (its.validForNewPackages) {
          return true;
        }
        let errors = (its.errors || []).concat(its.warnings || []);
        return "Sorry, " + errors.join(" and ") + ".";
      }
    }
  ]);

  answers.name = {
    npm: {
      full: name,
      scope: scope,
      local: local
    },
    cargo: {
      external: local,
      internal: local.replace(/-/g, "_")
    }
  };
  let version = await NEON_CLI_VERSION;
  let ctx = {
    project: answers,
    "neon-cli": {
      major: semver.major(version),
      minor: semver.minor(version),
      patch: semver.patch(version)
    },
    build: {
      cargo: {
        cmd: toolchain === 'default'
           ? []
           : ["multirust", "run", toolchain]
      }
    }
  };

  let lib = path.resolve(root, path.dirname(answers.node));
  let native_ = path.resolve(root, 'native');
  let src = path.resolve(native_, 'src');

  await mkdirs(lib);
  await mkdirs(src);

  await writeFile(path.resolve(root,    '.gitignore'),   (await GITIGNORE_TEMPLATE)(ctx), { flag: 'wx' });
  await writeFile(path.resolve(root,    'package.json'), (await NPM_TEMPLATE)(ctx),       { flag: 'wx' });
  await writeFile(path.resolve(native_, 'Cargo.toml'),   (await CARGO_TEMPLATE)(ctx),     { flag: 'wx' });
  await writeFile(path.resolve(root,    'README.md'),    (await README_TEMPLATE)(ctx),    { flag: 'wx' });
  await writeFile(path.resolve(root,    answers.node),   (await INDEXJS_TEMPLATE)(ctx),   { flag: 'wx' });
  await writeFile(path.resolve(src,     'lib.rs'),       (await LIBRS_TEMPLATE)(ctx),     { flag: 'wx' });
  await writeFile(path.resolve(native_, 'build.rs'),     (await BUILDRS_TEMPLATE)(ctx),   { flag: 'wx' });

  let relativeRoot = path.relative(pwd, root);
  let relativeNode = path.relative(pwd, path.resolve(root, answers.node));
  let relativeRust = path.relative(pwd, path.resolve(src, 'lib.rs'));

  console.log();
  console.log("Woo-hoo! Your Neon project has been created in: " + style.path(relativeRoot));
  console.log();
  console.log("The main Node entry point is at: " + style.path(relativeNode));
  console.log("The main Rust entry point is at: " + style.path(relativeRust));
  console.log();
  console.log("To build your project, just run " + style.command("npm install") + " from within the " + style.path(relativeRoot) + " directory.");
  console.log("Then you can test it out with " + style.command("node -e 'require(\"./\")'") + ".");
  console.log();
  console.log("Happy hacking!");
};
<commit_msg>"lib/index.js" is more portable -- even if you're in windows, you'll typically want to generate a project that will work in both unix and windows.<commit_after>import { readFile, writeFile, mkdirs } from '../async/fs';
import { prompt } from '../async/inquirer';
import gitconfig from '../async/git-config';
import path from 'path';
import handlebars from 'handlebars';
import semver from 'semver';
import validateLicense from 'validate-npm-package-license';
import validateName from 'validate-npm-package-name';
import * as style from './style';

const ROOT_DIR = path.resolve(__dirname, '..', '..');
const TEMPLATES_DIR = path.resolve(ROOT_DIR, 'templates');

const NEON_CLI_VERSION = (async function() {
  return JSON.parse(await readFile(path.resolve(ROOT_DIR, 'package.json'), 'utf8')).version;
})();

async function compile(filename) {
  return handlebars.compile(await readFile(path.resolve(TEMPLATES_DIR, filename), 'utf8'), { noEscape: true });
}

const GITIGNORE_TEMPLATE = compile('.gitignore.hbs');
const CARGO_TEMPLATE     = compile('Cargo.toml.hbs');
const NPM_TEMPLATE       = compile('package.json.hbs');
const INDEXJS_TEMPLATE   = compile('index.js.hbs');
const LIBRS_TEMPLATE     = compile('lib.rs.hbs');
const README_TEMPLATE    = compile('README.md.hbs');
const BUILDRS_TEMPLATE   = compile('build.rs.hbs');

async function guessAuthor() {
  let author = {
    name: process.env.USER || process.env.USERNAME,
    email: undefined
  };
  try {
    let config = await gitconfig();
    if (config.user.name) {
      author.name = config.user.name;
    }
    if (config.user.email) {
      author.email = config.user.email;
    }
    return author;
  } catch (e) {
    return author;
  }
}

export default async function wizard(pwd, name, toolchain) {
  let its = validateName(name);
  if (!its.validForNewPackages) {
    let errors = (its.errors || []).concat(its.warnings || []);
    throw new Error("Sorry, " + errors.join(" and ") + ".");
  }

  // check for a scoped name
  let scoped = name.match(/@([^\/]+)\/(.*)/);
  let [, scope, local] = scoped || [, null, name];

  console.log("This utility will walk you through creating the " + style.project(name) + " Neon project.");
  console.log("It only covers the most common items, and tries to guess sensible defaults.");
  console.log();
  console.log("Press ^C at any time to quit.");

  let root = path.resolve(pwd, local);
  let guess = await guessAuthor();

  let answers = await prompt([
    {
      type: 'input',
      name: 'version',
      message: "version",
      default: "0.1.0",
      validate: function (input) {
        if (semver.valid(input)) {
          return true;
        }
        return "Invalid version: " + input;
      }
    },
    { type: 'input', name: 'description', message: "description"                               },
    { type: 'input', name: 'node',        message: "node entry point", default: "lib/index.js" },
    { type: 'input', name: 'git',         message: "git repository"                            },
    { type: 'input', name: 'author',      message: "author",           default: guess.name     },
    { type: 'input', name: 'email',       message: "email",            default: guess.email    },
    {
      type: 'input',
      name: 'license',
      message: "license",
      default: "MIT",
      validate: function (input) {
        let its = validateLicense(input);
        if (its.validForNewPackages) {
          return true;
        }
        let errors = (its.errors || []).concat(its.warnings || []);
        return "Sorry, " + errors.join(" and ") + ".";
      }
    }
  ]);

  answers.name = {
    npm: {
      full: name,
      scope: scope,
      local: local
    },
    cargo: {
      external: local,
      internal: local.replace(/-/g, "_")
    }
  };
  let version = await NEON_CLI_VERSION;
  let ctx = {
    project: answers,
    "neon-cli": {
      major: semver.major(version),
      minor: semver.minor(version),
      patch: semver.patch(version)
    },
    build: {
      cargo: {
        cmd: toolchain === 'default'
           ? []
           : ["multirust", "run", toolchain]
      }
    }
  };

  let lib = path.resolve(root, path.dirname(answers.node));
  let native_ = path.resolve(root, 'native');
  let src = path.resolve(native_, 'src');

  await mkdirs(lib);
  await mkdirs(src);

  await writeFile(path.resolve(root,    '.gitignore'),   (await GITIGNORE_TEMPLATE)(ctx), { flag: 'wx' });
  await writeFile(path.resolve(root,    'package.json'), (await NPM_TEMPLATE)(ctx),       { flag: 'wx' });
  await writeFile(path.resolve(native_, 'Cargo.toml'),   (await CARGO_TEMPLATE)(ctx),     { flag: 'wx' });
  await writeFile(path.resolve(root,    'README.md'),    (await README_TEMPLATE)(ctx),    { flag: 'wx' });
  await writeFile(path.resolve(root,    answers.node),   (await INDEXJS_TEMPLATE)(ctx),   { flag: 'wx' });
  await writeFile(path.resolve(src,     'lib.rs'),       (await LIBRS_TEMPLATE)(ctx),     { flag: 'wx' });
  await writeFile(path.resolve(native_, 'build.rs'),     (await BUILDRS_TEMPLATE)(ctx),   { flag: 'wx' });

  let relativeRoot = path.relative(pwd, root);
  let relativeNode = path.relative(pwd, path.resolve(root, answers.node));
  let relativeRust = path.relative(pwd, path.resolve(src, 'lib.rs'));

  console.log();
  console.log("Woo-hoo! Your Neon project has been created in: " + style.path(relativeRoot));
  console.log();
  console.log("The main Node entry point is at: " + style.path(relativeNode));
  console.log("The main Rust entry point is at: " + style.path(relativeRust));
  console.log();
  console.log("To build your project, just run " + style.command("npm install") + " from within the " + style.path(relativeRoot) + " directory.");
  console.log("Then you can test it out with " + style.command("node -e 'require(\"./\")'") + ".");
  console.log();
  console.log("Happy hacking!");
};
<|endoftext|>