<commit_before>var React = require('react');
var ReactDOM = require('react-dom');
var {Chart} = require('react-google-charts')
var {Thumbnail, ControlLabel, Button, ButtonGroup, FormControl, Checkbox, Modal, Image, Popover} = require('react-bootstrap');
var GlobalConst = require('./global_const.js')
var intl = require('./translate.js')
var selector = GlobalConst.selector
var supportedChartSortkeys = GlobalConst.supportedChartSortkeys
var supportedSimulationChartSortkeys = GlobalConst.supportedSimulationChartSortkeys
var _ua = GlobalConst._ua;
var {generateHaisuiData, getTotalBuff, getInitialTotals, treatSupportAbility, calcOneCombination, initializeTotals} = require('./global_logic.js')

var HPChart = React.createClass({
    makeChartData: function(props) {
        var storedCombinations = props.storedList.combinations
        var storedArmlist = props.storedList.armlist
        var storedNames = props.storedList.names

        var prof = props.prof; var armlist = props.armlist;
        var summon = props.summon; var chara = props.chara;
        var totalBuff = getTotalBuff(prof)
        var totals = getInitialTotals(prof, chara, summon)
        treatSupportAbility(totals, chara)

        var res = []
        for(var i = 0; i < summon.length; i++){
            res[i] = []
        }

        for(var i = 0; i < storedCombinations.length; i++){
            var oneres = calcOneCombination(storedCombinations[i], summon, prof, armlist, totals, totalBuff)
            for(var j = 0; j < summon.length; j++){
                res[j].push({data: oneres[j], armNumbers: storedCombinations[i]});
            }
            initializeTotals(totals)
        }
        // resに再計算されたデータが入っている状態
        // res[summonind][rank]
        return generateHaisuiData(res, armlist, summon, prof, chara, storedCombinations, storedNames, props.displayRealHP, props.locale);
    },
    componentWillReceiveProps: function(nextProps) {
        // チャートを開きながらStoredListの名前を変更した時などに呼ばれる
        this.setState({chartData: this.makeChartData(nextProps)})
    },
    getInitialState: function() {
        var sortKey = this.props.sortKey
        if(!(sortKey in supportedChartSortkeys)) sortKey = "averageCyclePerTurn"

        return {
            sortKey: sortKey,
            chartData: this.makeChartData(this.props),
        }
    },
    makeChartOption: function(sortKey) {
        var locale = this.props.locale
        var hlabel = (this.props.displayRealHP ? intl.translate("残りHP", locale) : intl.translate("残HP割合", locale));

        options = {}
        for(var key in this.state.chartData) {
            if(key != "minMaxArr") {
                options[key] = {
                    title: key,
                    curveType: 'function',
                    forcelFrame: true,
                    hAxis: {title: hlabel, titleTextStyle: {italic: false}, textStyle: {italic: false}},
                    vAxis: {title: intl.translate(supportedChartSortkeys[sortKey], locale), textStyle: {italic: false}, minValue: this.state.chartData["minMaxArr"][sortKey]["min"], maxValue: this.state.chartData["minMaxArr"][sortKey]["max"]},
                    tooltip: {showColorCode: true, textStyle: {fontSize: 13}, trigger: "selection"},
                    legend: {position: "top", maxLines: 5, textStyle: {fontSize: 13}},
                    crosshair: {orientation: "both", opacity: 0.8, trigger: "both"},
                    chartArea: {left: "10%", top: "10%", width: "85%", height: "80%",},
                    lineWidth: 2,
                    pointSize: 0,
                    selectionMode: 'multiple',
                    aggregationTarget: "category",
                }
            }
        }

        return options
    },
    handleEvent: function(key, e) {
        var locale = this.props.locale
        var newState = this.state
        newState[key] = e.target.value
        this.setState(newState)
    },
    render: function() {
        var locale = this.props.locale
        var sortKey = this.state.sortKey
        var data = this.state.chartData
        var options = this.makeChartOption(sortKey)

        if(_ua.Mobile) {
            return (

                        {Object.keys(data).map(function(key, ind) {
                            if(key != "minMaxArr") {
                                return <Chart chartType="ScatterChart" className="LineChart" data={data[key][sortKey]} key={key} options={options[key]} graph_id={"LineChart" + ind} width={"90%"} height={"50%"} legend_toggle={true} />
                            }
                        })}

            );
        } else {
            if(window.innerWidth > 1000) {
                var width = (98.0 / (Object.keys(data).length - 1))
                if(Object.keys(data).length - 1 > 2) {
                    width = 49.0
                }
            } else {
                var width = 98.0
            }

            return (

                            {intl.translate("表示項目", locale)}
                            <FormControl
                                componentClass="select"
                                value={this.state.sortKey}
                                style={{"width": "400px", "margin": "2px 5px"}}
                                onChange={this.handleEvent.bind(this, "sortKey")}>
                                    {selector[locale].supported_chartsortkeys}
                            </FormControl>

                        {Object.keys(data).map(function(key, ind) {
                            if(key != "minMaxArr") {
                                return <Chart chartType="ScatterChart" className="LineChart" data={data[key][sortKey]} key={key} options={options[key]} graph_id={"LineChart" + ind} width={width + "%"} height={"400px"} legend_toggle={true} />
                            }
                        })}

            );

        }
    },
});

var SimulationChart = React.createClass({
    getInitialState: function() {
        var sortKey = this.props.sortKey
        if(!(sortKey in supportedSimulationChartSortkeys)) sortKey = "summedAverageExpectedDamage"

        return {
            sortKey: sortKey,
        }
    },
    makeChartOption: function(sortKey) {
        var locale = this.props.locale

        options = {}
        for(var key in this.props.data) {
            if(key != "minMaxArr") {
                options[key] = {
                    title: key,
                    forcelFrame: true,
                    hAxis: {title: intl.translate("ターン", locale), titleTextStyle: {italic: false}, textStyle: {italic: false}, gridlines: {count: this.props.maxTurn}},
                    vAxis: {title: intl.translate(supportedSimulationChartSortkeys[sortKey], locale), textStyle: {italic: false}, minValue: this.props.data["minMaxArr"][sortKey]["min"], maxValue: this.props.data["minMaxArr"][sortKey]["max"]},
                    tooltip: {showColorCode: true, textStyle: {fontSize: 13}, trigger: "selection"},
                    legend: {position: "top", maxLines: 5, textStyle: {fontSize: 13}},
                    crosshair: {orientation: "both", opacity: 0.8, trigger: "both"},
                    chartArea: {left: "10%", top: "10%", width: "85%", height: "80%",},
                    lineWidth: 2,
                    pointSize: 8,
                    selectionMode: 'multiple',
                    aggregationTarget: "category",
                }
            }
        }

        return options
    },
    handleEvent: function(key, e) {
        var newState = this.state
        newState[key] = e.target.value
        this.setState(newState)
    },
    render: function() {
        var options = this.state.options
        var data = this.props.data
        var sortKey = this.state.sortKey
        var options = this.makeChartOption(sortKey)

        if(_ua.Mobile) {
            return (

                    {Object.keys(data).map(function(key, ind) {
                        if(key != "minMaxArr") {
                            return <Chart chartType="LineChart" className="LineChart" data={data[key][sortKey]} key={key} options={options[key]} graph_id={"LineChart" + ind} width={"98%"} height={"50%"} legend_toggle={true} />
                        }
                    })}

            );
        } else {
            if(window.innerWidth > 1000) {
                var width = (98.0 / (Object.keys(data).length - 1))
                if(Object.keys(data).length - 1 > 2) {
                    width = 49.0
                }
            } else {
                var width = 98.0
            }

            return (

                            {intl.translate("表示項目", this.props.locale)}
                            <FormControl
                                componentClass="select"
                                value={this.state.sortKey}
                                style={{"width": "400px", "margin": "2px 5px"}}
                                onChange={this.handleEvent.bind(this, "sortKey")}>
                                {selector[this.props.locale].supported_simulationchartsortkeys}
                            </FormControl>

                        {Object.keys(data).map(function(key, ind) {
                            if(key != "minMaxArr") {
                                return <Chart chartType="LineChart" className="LineChart" data={data[key][sortKey]} key={key} options={options[key]} graph_id={"LineChart" + ind} width={width + "%"} height={"400px"} legend_toggle={true} />
                            }
                        })}

            );

        }
    },
});

module.exports.HPChart = HPChart;
module.exports.SimulationChart = SimulationChart;
<commit_msg>chart.jsで怒られたところを修正.<commit_after>var React = require('react');
var ReactDOM = require('react-dom');
var {Chart} = require('react-google-charts')
var {Thumbnail, ControlLabel, Button, ButtonGroup, FormControl, Checkbox, Modal, Image, Popover} = require('react-bootstrap');
var GlobalConst = require('./global_const.js')
var intl = require('./translate.js')
var selector = GlobalConst.selector
var supportedChartSortkeys = GlobalConst.supportedChartSortkeys
var supportedSimulationChartSortkeys = GlobalConst.supportedSimulationChartSortkeys
var _ua = GlobalConst._ua;
var {generateHaisuiData, getTotalBuff, getInitialTotals, treatSupportAbility, calcOneCombination, initializeTotals} = require('./global_logic.js')

var HPChart = React.createClass({
    makeChartData: function(props) {
        var storedCombinations = props.storedList.combinations
        var storedArmlist = props.storedList.armlist
        var storedNames = props.storedList.names

        var prof = props.prof; var armlist = props.armlist;
        var summon = props.summon; var chara = props.chara;
        var totalBuff = getTotalBuff(prof)
        var totals = getInitialTotals(prof, chara, summon)
        treatSupportAbility(totals, chara)

        var res = []
        for(var i = 0; i < summon.length; i++){
            res[i] = []
        }

        for(var i = 0; i < storedCombinations.length; i++){
            var oneres = calcOneCombination(storedCombinations[i], summon, prof, armlist, totals, totalBuff)
            for(var j = 0; j < summon.length; j++){
                res[j].push({data: oneres[j], armNumbers: storedCombinations[i]});
            }
            initializeTotals(totals)
        }
        // resに再計算されたデータが入っている状態
        // res[summonind][rank]
        return generateHaisuiData(res, armlist, summon, prof, chara, storedCombinations, storedNames, props.displayRealHP, props.locale);
    },
    componentWillReceiveProps: function(nextProps) {
        // チャートを開きながらStoredListの名前を変更した時などに呼ばれる
        this.setState({chartData: this.makeChartData(nextProps)})
    },
    getInitialState: function() {
        var sortKey = this.props.sortKey
        if(!(sortKey in supportedChartSortkeys)) sortKey = "averageCyclePerTurn"

        return {
            sortKey: sortKey,
            chartData: this.makeChartData(this.props),
        }
    },
    makeChartOption: function(sortKey) {
        var locale = this.props.locale
        var hlabel = (this.props.displayRealHP ? intl.translate("残りHP", locale) : intl.translate("残HP割合", locale));

        var options = {}
        for(var key in this.state.chartData) {
            if(key != "minMaxArr") {
                options[key] = {
                    title: key,
                    curveType: 'function',
                    forcelFrame: true,
                    hAxis: {title: hlabel, titleTextStyle: {italic: false}, textStyle: {italic: false}},
                    vAxis: {title: intl.translate(supportedChartSortkeys[sortKey], locale), textStyle: {italic: false}, minValue: this.state.chartData["minMaxArr"][sortKey]["min"], maxValue: this.state.chartData["minMaxArr"][sortKey]["max"]},
                    tooltip: {showColorCode: true, textStyle: {fontSize: 13}, trigger: "selection"},
                    legend: {position: "top", maxLines: 5, textStyle: {fontSize: 13}},
                    crosshair: {orientation: "both", opacity: 0.8, trigger: "both"},
                    chartArea: {left: "10%", top: "10%", width: "85%", height: "80%",},
                    lineWidth: 2,
                    pointSize: 0,
                    selectionMode: 'multiple',
                    aggregationTarget: "category",
                }
            }
        }

        return options
    },
    handleEvent: function(key, e) {
        var newState = this.state
        newState[key] = e.target.value
        this.setState(newState)
    },
    render: function() {
        var locale = this.props.locale
        var sortKey = this.state.sortKey
        var data = this.state.chartData
        var options = this.makeChartOption(sortKey)

        if(_ua.Mobile) {
            return (

                        {Object.keys(data).map(function(key, ind) {
                            if(key != "minMaxArr") {
                                return <Chart chartType="ScatterChart" className="LineChart" data={data[key][sortKey]} key={key} options={options[key]} graph_id={"LineChart" + ind} width={"90%"} height={"50%"} legend_toggle={true} />
                            }
                        })}

            );
        } else {
            if(window.innerWidth > 1000) {
                var width = (98.0 / (Object.keys(data).length - 1))
                if(Object.keys(data).length - 1 > 2) {
                    width = 49.0
                }
            } else {
                var width = 98.0
            }

            return (

                            {intl.translate("表示項目", locale)}
                            <FormControl
                                componentClass="select"
                                value={this.state.sortKey}
                                style={{"width": "400px", "margin": "2px 5px"}}
                                onChange={this.handleEvent.bind(this, "sortKey")}>
                                    {selector[locale].supported_chartsortkeys}
                            </FormControl>

                        {Object.keys(data).map(function(key, ind) {
                            if(key != "minMaxArr") {
                                return <Chart chartType="ScatterChart" className="LineChart" data={data[key][sortKey]} key={key} options={options[key]} graph_id={"LineChart" + ind} width={width + "%"} height={"400px"} legend_toggle={true} />
                            }
                        })}

            );

        }
    },
});

var SimulationChart = React.createClass({
    getInitialState: function() {
        var sortKey = this.props.sortKey
        if(!(sortKey in supportedSimulationChartSortkeys)) sortKey = "summedAverageExpectedDamage"

        return {
            sortKey: sortKey,
        }
    },
    makeChartOption: function(sortKey) {
        var locale = this.props.locale

        var options = {}
        for(var key in this.props.data) {
            if(key != "minMaxArr") {
                options[key] = {
                    title: key,
                    forcelFrame: true,
                    hAxis: {title: intl.translate("ターン", locale), titleTextStyle: {italic: false}, textStyle: {italic: false}, gridlines: {count: this.props.maxTurn}},
                    vAxis: {title: intl.translate(supportedSimulationChartSortkeys[sortKey], locale), textStyle: {italic: false}, minValue: this.props.data["minMaxArr"][sortKey]["min"], maxValue: this.props.data["minMaxArr"][sortKey]["max"]},
                    tooltip: {showColorCode: true, textStyle: {fontSize: 13}, trigger: "selection"},
                    legend: {position: "top", maxLines: 5, textStyle: {fontSize: 13}},
                    crosshair: {orientation: "both", opacity: 0.8, trigger: "both"},
                    chartArea: {left: "10%", top: "10%", width: "85%", height: "80%",},
                    lineWidth: 2,
                    pointSize: 8,
                    selectionMode: 'multiple',
                    aggregationTarget: "category",
                }
            }
        }

        return options
    },
    handleEvent: function(key, e) {
        var newState = this.state
        newState[key] = e.target.value
        this.setState(newState)
    },
    render: function() {
        var options = this.state.options
        var data = this.props.data
        var sortKey = this.state.sortKey
        var options = this.makeChartOption(sortKey)

        if(_ua.Mobile) {
            return (

                    {Object.keys(data).map(function(key, ind) {
                        if(key != "minMaxArr") {
                            return <Chart chartType="LineChart" className="LineChart" data={data[key][sortKey]} key={key} options={options[key]} graph_id={"LineChart" + ind} width={"98%"} height={"50%"} legend_toggle={true} />
                        }
                    })}

            );
        } else {
            if(window.innerWidth > 1000) {
                var width = (98.0 / (Object.keys(data).length - 1))
                if(Object.keys(data).length - 1 > 2) {
                    width = 49.0
                }
            } else {
                var width = 98.0
            }

            return (

                            {intl.translate("表示項目", this.props.locale)}
                            <FormControl
                                componentClass="select"
                                value={this.state.sortKey}
                                style={{"width": "400px", "margin": "2px 5px"}}
                                onChange={this.handleEvent.bind(this, "sortKey")}>
                                {selector[this.props.locale].supported_simulationchartsortkeys}
                            </FormControl>

                        {Object.keys(data).map(function(key, ind) {
                            if(key != "minMaxArr") {
                                return <Chart chartType="LineChart" className="LineChart" data={data[key][sortKey]} key={key} options={options[key]} graph_id={"LineChart" + ind} width={width + "%"} height={"400px"} legend_toggle={true} />
                            }
                        })}

            );

        }
    },
});

module.exports.HPChart = HPChart;
module.exports.SimulationChart = SimulationChart;
<|endoftext|>


<commit_before>var _ = require('lodash'),
  references = require('./references'),
  label = require('./label'),
  dom = require('./dom');

/**
 * get placeholder text
 * if placeholder has a text property, use it
 * else call the label service
 * @param  {string} path
 * @param  {{}} schema
 * @return {string}
 */
function getPlaceholderText(path, schema) {
  var placeholder = schema[references.placeholderProperty];

  if (_.isObject(placeholder) && placeholder.text) {
    return placeholder.text;
  } else {
    return label(path, schema);
  }
}

/**
 * get placeholder height based on the behaviors in a field
 * @param  {object} schema
 * @return {string}
 */
function getPlaceholderHeight(schema) {
  var placeholder = schema[references.placeholderProperty];

  return placeholder && placeholder.height || '100px';
}

function isFieldEmpty(data) {
  // note: 0, false, etc are valid bits of data for numbers, booleans, etc so they shouldn't be masked
  var value;

  // only fallback to data if value is undefined (not just falsy)
  if (data.hasOwnProperty('value')) {
    value = data.value;
  } else {
    value = data;
  }

  return !_.isBoolean(value) && !_.isNumber(value) && _.isEmpty(value);
}

/**
 * create dom element for the placeholder, add it to the specified node
 * @param {Element} node
 * @param {{ height: string, text: string }} obj
 * @returns {Element} node
 */
function addPlaceholderDom(node, obj) {
  var placeholder = dom.create(`

      ${obj.text}

  `);

  node.appendChild(placeholder);
  return node;
}

/**
 * @param {Element} el
 * @param {{ref: string, path: string, data: object}} options
 * @returns {boolean}
 */
function hasPlaceholder(el, options) {
  var schema = _.get(options, 'data._schema'),
    isPlaceholder = !!schema[references.placeholderProperty],
    isField = !!schema[references.fieldProperty];

  return isPlaceholder && isField && isFieldEmpty(options.data);
}

/**
 * @param {Element} el
 * @param {{ref: string, path: string, data: object}} options
 * @returns {Element}
 */
function addPlaceholder(el, options) {
  var path = options.path,
    schema = _.get(options, 'data._schema');

  return addPlaceholderDom(el, {
    text: getPlaceholderText(path, schema),
    height: getPlaceholderHeight(schema)
  });
}

module.exports.when = hasPlaceholder;
module.exports.handler = addPlaceholder;

// exported for testing
module.exports.getPlaceholderText = getPlaceholderText;
module.exports.getPlaceholderHeight = getPlaceholderHeight;
module.exports.isFieldEmpty = isFieldEmpty;
<commit_msg>placeholder height should be min-height<commit_after>var _ = require('lodash'),
  references = require('./references'),
  label = require('./label'),
  dom = require('./dom');

/**
 * get placeholder text
 * if placeholder has a text property, use it
 * else call the label service
 * @param  {string} path
 * @param  {{}} schema
 * @return {string}
 */
function getPlaceholderText(path, schema) {
  var placeholder = schema[references.placeholderProperty];

  if (_.isObject(placeholder) && placeholder.text) {
    return placeholder.text;
  } else {
    return label(path, schema);
  }
}

/**
 * get placeholder height based on the behaviors in a field
 * @param  {object} schema
 * @return {string}
 */
function getPlaceholderHeight(schema) {
  var placeholder = schema[references.placeholderProperty];

  return placeholder && placeholder.height || '100px';
}

function isFieldEmpty(data) {
  // note: 0, false, etc are valid bits of data for numbers, booleans, etc so they shouldn't be masked
  var value;

  // only fallback to data if value is undefined (not just falsy)
  if (data.hasOwnProperty('value')) {
    value = data.value;
  } else {
    value = data;
  }

  return !_.isBoolean(value) && !_.isNumber(value) && _.isEmpty(value);
}

/**
 * create dom element for the placeholder, add it to the specified node
 * @param {Element} node
 * @param {{ height: string, text: string }} obj
 * @returns {Element} node
 */
function addPlaceholderDom(node, obj) {
  var placeholder = dom.create(`

      ${obj.text}

  `);

  node.appendChild(placeholder);
  return node;
}

/**
 * @param {Element} el
 * @param {{ref: string, path: string, data: object}} options
 * @returns {boolean}
 */
function hasPlaceholder(el, options) {
  var schema = _.get(options, 'data._schema'),
    isPlaceholder = !!schema[references.placeholderProperty],
    isField = !!schema[references.fieldProperty];

  return isPlaceholder && isField && isFieldEmpty(options.data);
}

/**
 * @param {Element} el
 * @param {{ref: string, path: string, data: object}} options
 * @returns {Element}
 */
function addPlaceholder(el, options) {
  var path = options.path,
    schema = _.get(options, 'data._schema');

  return addPlaceholderDom(el, {
    text: getPlaceholderText(path, schema),
    height: getPlaceholderHeight(schema)
  });
}

module.exports.when = hasPlaceholder;
module.exports.handler = addPlaceholder;

// exported for testing
module.exports.getPlaceholderText = getPlaceholderText;
module.exports.getPlaceholderHeight = getPlaceholderHeight;
module.exports.isFieldEmpty = isFieldEmpty;
<|endoftext|>


<commit_before>import colors from '../settings/colors';
import darken from '../internal/darken';
import fade from '../internal/fade';
import styles from '../settings/styles';

export default {
  iconButton: {
    background: 'none',
    borderRadius: '50%',
    border: 0,
    cursor: 'pointer',
    height: '40px',
    outline: 0,
    padding: '8px',
    transition: 'background-color .3s ease-in-out',
    width: '40px',
    ':hover': {
      background: fade(colors.black, 0.9)
    },
    ':active': {
      background: fade(colors.black, 0.8)
    }
  },
  button: {
    backgroundColor: colors.theme,
    border: 0,
    borderRadius: '3px',
    boxShadow: styles.depthShadows[0],
    color: colors.white,
    cursor: 'pointer',
    fontSize: '16px',
    outline: 0,
    padding: '6.5px 13px',
    transition: 'all .3s ease-in-out',
    ':hover': {
      backgroundColor: darken(colors.theme, 0.15)
    },
    ':active': {
      backgroundColor: darken(colors.theme, 0.25)
    }
  },
  inverted: {
    color: colors.theme,
    backgroundColor: colors.white,
    ':hover': {
      backgroundColor: darken(colors.white, 0.15)
    },
    ':active': {
      backgroundColor: darken(colors.white, 0.25)
    }
  },
  disabled: {
    opacity: '0.38'
  },
  flatButton: {
    backgroundColor: 'transparent',
    boxShadow: 'none',
    textTransform: 'uppercase',
    ':hover': {
      backgroundColor: fade(colors.black, 0.95)
    },
    ':active': {
      backgroundColor: fade(colors.black, 0.85)
    }
  }
};
<commit_msg>:lipstick: Changed active styles<commit_after>import colors from '../settings/colors';
import darken from '../internal/darken';
import fade from '../internal/fade';
import styles from '../settings/styles';

export default {
  iconButton: {
    background: 'none',
    borderRadius: '50%',
    border: 0,
    cursor: 'pointer',
    height: '40px',
    outline: 0,
    padding: '8px',
    transition: 'all .3s ease-in-out',
    width: '40px',
    ':hover': {
      background: fade(colors.black, 0.9)
    },
    ':active': {
      boxShadow: styles.depthShadows[0]
    }
  },
  button: {
    backgroundColor: colors.theme,
    border: 0,
    borderRadius: '3px',
    boxShadow: styles.depthShadows[0],
    color: colors.white,
    cursor: 'pointer',
    fontSize: '16px',
    outline: 0,
    padding: '6.5px 13px',
    transition: 'all .3s ease-in-out',
    ':hover': {
      backgroundColor: darken(colors.theme, 0.15)
    },
    ':active': {
      boxShadow: styles.depthShadows[1]
    }
  },
  inverted: {
    color: colors.theme,
    backgroundColor: colors.white,
    ':hover': {
      backgroundColor: darken(colors.white, 0.15)
    },
    ':active': {
      boxShadow: styles.depthShadows[1]
    }
  },
  disabled: {
    opacity: '0.38'
  },
  flatButton: {
    backgroundColor: 'transparent',
    boxShadow: 'none',
    textTransform: 'uppercase',
    ':hover': {
      backgroundColor: fade(colors.black, 0.95)
    },
    ':active': {
      backgroundColor: fade(colors.black, 0.85)
    }
  }
};
<|endoftext|>


<commit_before>import THREE from './Three';
import React, { PropTypes, Component } from 'react';
import ReactDOM  from 'react-dom';
let OrbitControls = require('three-orbit-controls')(THREE);

class Paint {
  constructor(context) {
    this.component = context;
    this.url = context.props.url;
    this.width = context.props.width;
    this.height = context.props.height;
    this.modelColor = context.props.modelColor;
    this.backgroundColor = context.props.backgroundColor;
    this.orbitControls = context.props.orbitControls;
    this.rotate = context.props.rotate;

    this.camera;
    this.scene;
    this.renderer;
    this.mesh;
    this.distance;
    this.controls;
    this.xDims;
    this.yDims;
    this.zDims;
  }

  init() {
    //Detector.addGetWebGLMessage();
    this.scene = new THREE.Scene();
    this.distance = 10000;
    let directionalLight = new THREE.DirectionalLight( 0xffffff );
    directionalLight.position.x = 0;
    directionalLight.position.y = 0;
    directionalLight.position.z = 1;
    directionalLight.position.normalize();
    this.scene.add( directionalLight );

    let loader = new THREE.STLLoader();
    loader.crossOrigin = '';
    loader.load(this.url, ( geometry ) => {

      // Calculate mesh noramls for MeshLambertMaterial.
      geometry.computeFaceNormals();
      geometry.computeVertexNormals();

      // Center the object
      geometry.center();

      this.mesh = new THREE.Mesh(
        geometry,
        new THREE.MeshLambertMaterial({
          overdraw:true,
          color: this.modelColor,
        }
        ));
      // Set the object's dimensions
      geometry.computeBoundingBox();
      this.xDims = geometry.boundingBox.max.x - geometry.boundingBox.min.x;
      this.yDims = geometry.boundingBox.max.y - geometry.boundingBox.min.y;
      this.zDims = geometry.boundingBox.max.z - geometry.boundingBox.min.z;

      if(this.rotate) {
        this.mesh.rotation.x = 5;
        this.mesh.rotation.z = .25;
      }

      this.scene.add(this.mesh);

      // Add the camera
      this.camera = new THREE.PerspectiveCamera(30, this.width / this.height, 1, this.distance);
      this.camera.position.set(0,0,Math.max(this.xDims * 3, this.yDims * 3, this.zDims * 3));

      this.scene.add(this.camera);

      this.renderer = new THREE.WebGLRenderer(); //new THREE.CanvasRenderer();
      this.renderer.setSize(this.width, this.height);
      this.renderer.setClearColor(this.backgroundColor, 1);

      // Add controls for mouse interaction
      if(this.orbitControls) {
        this.controls = new OrbitControls(this.camera, ReactDOM.findDOMNode(this.component));
        this.controls.enableKeys = false
        this.controls.addEventListener( 'change', this.orbitRender );
      }

      // Add to the React Component
      ReactDOM.findDOMNode(this.component).replaceChild( this.renderer.domElement,
        ReactDOM.findDOMNode(this.component).firstChild);

      // Start the animation
      this.animate();
    });
  }

  /**
   * Animate the scene
   * @returns {void}
   */
  animate() {
    // note: three.js includes requestAnimationFrame shim
    if(this.rotate) {
      requestAnimationFrame(this.animate.bind(this));
    }
    if(this.orbitControls) {
      this.controls.update();
    }
    this.render();
  }

  /**
   * Render the scene after turning off the rotation
   * @returns {void}
   */
  orbitRender() {
    if(this.rotate) {
      this.rotate = false;
    }

    this.render();
  }

  /**
   * Render the scene
   * @returns {void}
   */
  render() {
    if (this.mesh && this.rotate) {
      this.mesh.rotation.z += 0.02;
    }

    this.renderer.render(this.scene, this.camera);
  }
}
/*
let camera, scene, renderer, mesh, distance, controls;
let xDims, yDims, zDims;

const Paint = (params) => {
  //Detector.addGetWebGLMessage();
  scene = new THREE.Scene();
  distance = 10000;
  let directionalLight = new THREE.DirectionalLight( 0xffffff );
  directionalLight.position.x = 0;
  directionalLight.position.y = 0;
  directionalLight.position.z = 1;
  directionalLight.position.normalize();
  scene.add(directionalLight);

  let loader = new THREE.STLLoader();
  loader.crossOrigin = '';
  loader.load(params.url, (geometry) => {

    // Calculate mesh noramls for MeshLambertMaterial.
    geometry.computeFaceNormals();
    geometry.computeVertexNormals();

    // Center the object
    geometry.center();

    mesh = new THREE.Mesh(
      geometry,
      new THREE.MeshLambertMaterial({
        overdraw: true,
        color: params.modelColor,
      })
    );

    // Set the object's dimensions
    geometry.computeBoundingBox();
    xDims = geometry.boundingBox.max.x - geometry.boundingBox.min.x;
    yDims = geometry.boundingBox.max.y - geometry.boundingBox.min.y;
    zDims = geometry.boundingBox.max.z - geometry.boundingBox.min.z;

    if(params.rotate) {
      mesh.rotation.x = 5;
      mesh.rotation.z = .25;
    }

    scene.add(mesh);

    // Add the camera
    camera = new THREE.PerspectiveCamera(30, params.width / params.height, 1, distance);
    camera.position.set(0, 0, Math.max(xDims * 3, yDims * 3, zDims * 3));

    scene.add(camera);

    renderer = new THREE.WebGLRenderer(); //new THREE.CanvasRenderer();
    renderer.setSize(params.width, params.height);
    renderer.setClearColor(params.backgroundColor, 1);

    // Add controls for mouse interaction
    if(params.orbitControls) {
      controls = new OrbitControls(camera, ReactDOM.findDOMNode(params.component));
      controls.enableKeys = false
      controls.addEventListener('change', orbitRender(params));
    }

    // Add to the React Component
    ReactDOM.findDOMNode(params.component).replaceChild( renderer.domElement,
      ReactDOM.findDOMNode(params.component).firstChild);

    // Start the animation
    animate(params);
  });
};

let orbitRender = (params) => {
  if(params.rotate) {
    params.rotate = false;
  }

  render(params);
};

let animate = (params) => {
  // note: three.js includes requestAnimationFrame shim
  debugger;
  if(params.rotate) {
    requestAnimationFrame(animate(params));
  }

  if(params.orbitControls) {
    controls.update();
  }

  render(params);
};

let render = (params) => {
  if (mesh && params.rotate) {
    mesh.rotation.z += 0.02;
  }

  renderer.render(scene, camera);
};
*/

export default Paint;
<commit_msg>Refactor: Break init logic in functions<commit_after>import THREE from './Three';
import React, { PropTypes, Component } from 'react';
import ReactDOM  from 'react-dom';
let OrbitControls = require('three-orbit-controls')(THREE);

class Paint {
  constructor(context) {
    this.component = context;
    this.url = context.props.url;
    this.width = context.props.width;
    this.height = context.props.height;
    this.modelColor = context.props.modelColor;
    this.backgroundColor = context.props.backgroundColor;
    this.orbitControls = context.props.orbitControls;
    this.rotate = context.props.rotate;

    this.camera;
    this.scene;
    this.renderer;
    this.mesh;
    this.distance;
    this.controls;
    this.xDims;
    this.yDims;
    this.zDims;
  }

  init() {
    //Detector.addGetWebGLMessage();
    this.scene = new THREE.Scene();
    this.distance = 10000;
    let directionalLight = new THREE.DirectionalLight( 0xffffff );
    directionalLight.position.x = 0;
    directionalLight.position.y = 0;
    directionalLight.position.z = 1;
    directionalLight.position.normalize();
    this.scene.add(directionalLight);

    this.addSTLToScene();
  }

  addSTLToScene() {
    let loader = new THREE.STLLoader();
    loader.crossOrigin = '';

    loader.load(this.url, (geometry) => {

      // Calculate mesh noramls for MeshLambertMaterial.
      geometry.computeFaceNormals();
      geometry.computeVertexNormals();

      // Center the object
      geometry.center();

      this.mesh = new THREE.Mesh(
        geometry,
        new THREE.MeshLambertMaterial({
          overdraw:true,
          color: this.modelColor,
        }
        ));
      // Set the object's dimensions
      geometry.computeBoundingBox();
      this.xDims = geometry.boundingBox.max.x - geometry.boundingBox.min.x;
      this.yDims = geometry.boundingBox.max.y - geometry.boundingBox.min.y;
      this.zDims = geometry.boundingBox.max.z - geometry.boundingBox.min.z;

      if(this.rotate) {
        this.mesh.rotation.x = 5;
        this.mesh.rotation.z = .25;
      }

      this.scene.add(this.mesh);

      this.addCamera();
      this.addInteractionControls();
      this.addToReactComponent();

      // Start the animation
      this.animate();
    });
  }

  addCamera() {
    // Add the camera
    this.camera = new THREE.PerspectiveCamera(30, this.width / this.height, 1, this.distance);
    this.camera.position.set(0,0,Math.max(this.xDims * 3, this.yDims * 3, this.zDims * 3));

    this.scene.add(this.camera);

    this.renderer = new THREE.WebGLRenderer(); //new THREE.CanvasRenderer();
    this.renderer.setSize(this.width, this.height);
    this.renderer.setClearColor(this.backgroundColor, 1);
  }

  addInteractionControls() {
    // Add controls for mouse interaction
    if(this.orbitControls) {
      this.controls = new OrbitControls(this.camera, ReactDOM.findDOMNode(this.component));
      this.controls.enableKeys = false
      this.controls.addEventListener( 'change', this.orbitRender.bind(this) );
    }
  }

  addToReactComponent() {
    // Add to the React Component
    ReactDOM.findDOMNode(this.component).replaceChild( this.renderer.domElement,
      ReactDOM.findDOMNode(this.component).firstChild);
  }

  /**
   * Animate the scene
   * @returns {void}
   */
  animate() {
    // note: three.js includes requestAnimationFrame shim
    if(this.rotate) {
      requestAnimationFrame(this.animate.bind(this));
    }
    if(this.orbitControls) {
      this.controls.update();
    }
    this.render();
  }

  /**
   * Render the scene after turning off the rotation
   * @returns {void}
   */
  orbitRender() {
    if(this.rotate) {
      this.rotate = false;
    }

    this.render();
  }

  /**
   * Render the scene
   * @returns {void}
   */
  render() {
    if (this.mesh && this.rotate) {
      this.mesh.rotation.z += 0.02;
    }

    this.renderer.render(this.scene, this.camera);
  }
}

export default Paint;
<|endoftext|>


<commit_before>// Copyright 2016-2018, University of Colorado Boulder

/**
 * a Scenery Node that represents the sun, clouds, and a slider to control the level of cloudiness in the view
 *
 * @author John Blanco
 * @author Andrew Adare
 */
define( function( require ) {
  'use strict';

  // modules
  var Cloud = require( 'ENERGY_FORMS_AND_CHANGES/systems/model/Cloud' );
  var Color = require( 'SCENERY/util/Color' );
  var EFACConstants = require( 'ENERGY_FORMS_AND_CHANGES/common/EFACConstants' );
  var EFACQueryParameters = require( 'ENERGY_FORMS_AND_CHANGES/common/EFACQueryParameters' );
  var EnergyChunkLayer = require( 'ENERGY_FORMS_AND_CHANGES/common/view/EnergyChunkLayer' );
  var energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  var HBox = require( 'SCENERY/nodes/HBox' );
  var Image = require( 'SCENERY/nodes/Image' );
  var inherit = require( 'PHET_CORE/inherit' );
  var LightRays = require( 'ENERGY_FORMS_AND_CHANGES/systems/view/LightRays' );
  var Matrix3 = require( 'DOT/Matrix3' );
  var ModelViewTransform2 = require( 'PHETCOMMON/view/ModelViewTransform2' );
  var MoveFadeModelElementNode = require( 'ENERGY_FORMS_AND_CHANGES/systems/view/MoveFadeModelElementNode' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Panel = require( 'SUN/Panel' );
  var Path = require( 'SCENERY/nodes/Path' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  var Property = require( 'AXON/Property' );
  var RadialGradient = require( 'SCENERY/util/RadialGradient' );
  var Range = require( 'DOT/Range' );
  var Shape = require( 'KITE/Shape' );
  var SunEnergySource = require( 'ENERGY_FORMS_AND_CHANGES/systems/model/SunEnergySource' );
  var Text = require( 'SCENERY/nodes/Text' );
  var VBox = require( 'SCENERY/nodes/VBox' );
  var Vector2 = require( 'DOT/Vector2' );
  var VSlider = require( 'SUN/VSlider' );

  // images
  var cloudImage = require( 'image!ENERGY_FORMS_AND_CHANGES/cloud_1.png' );

  // strings
  var cloudsString = require( 'string!ENERGY_FORMS_AND_CHANGES/clouds' );
  var lotsString = require( 'string!ENERGY_FORMS_AND_CHANGES/lots' );
  var noneString = require( 'string!ENERGY_FORMS_AND_CHANGES/none' );

  // constants
  var CONTROL_PANEL_TITLE_FONT = new PhetFont( 16 );
  var CONTROL_PANEL_TEXT_MAX_WIDTH = 50;
  var SLIDER_LABEL_FONT = new PhetFont( 12 );

  /**
   * @param {SunEnergySource} sun Sun model element
   * @param {Property} energyChunksVisibleProperty
   * @param {ModelViewTransform} modelViewTransform
   * @constructor
   */
  function SunNode( sun, energyChunksVisibleProperty, modelViewTransform ) {
    MoveFadeModelElementNode.call( this, sun, modelViewTransform );
    var self = this;

    var sunCenter = modelViewTransform.modelToViewDelta( SunEnergySource.OFFSET_TO_CENTER_OF_SUN );
    var sunRadius = modelViewTransform.modelToViewDeltaX( sun.radius );
    var lightRays = new LightRays( sunCenter, sunRadius, 1000, 40, Color.YELLOW );

    this.addChild( lightRays );

    // turn off light rays when energy chunks are visible
    energyChunksVisibleProperty.link( function( chunksVisible ) {
      lightRays.setVisible( !chunksVisible );
    } );

    // add the sun
    var sunShape = Shape.ellipse( 0, 0, sunRadius, sunRadius );
    var sunPath = new Path( sunShape, {
      fill: new RadialGradient( 0, 0, 0, 0, 0, sunRadius )
        .addColorStop( 0, 'white' )
        .addColorStop( 0.25, 'white' )
        .addColorStop( 1, '#FFD700' ),
      lineWidth: 1,
      stroke: 'yellow'
    } );

    sunPath.setTranslation( sunCenter );

    // create a scale-only MVT since translation of the absorption shapes is done separately
    var scaleOnlyMVT = ModelViewTransform2.createSinglePointScaleInvertedYMapping(
      Vector2.ZERO,
      Vector2.ZERO,
      modelViewTransform.getMatrix().getScaleVector().x
    );

    // add clouds, initially transparent
    sun.clouds.forEach( function( cloud ) {

      // make a light-absorbing shape from the cloud's absorption ellipse
      var cloudAbsorptionShape = cloud.getCloudAbsorptionReflectionShape();
      var translatedCloudAbsorptionShape = cloudAbsorptionShape.transformed( Matrix3.translation(
        -sun.positionProperty.value.x,
        -sun.positionProperty.value.y
      ) );
      var scaledAndTranslatedCloudAbsorptionShape = scaleOnlyMVT.modelToViewShape( translatedCloudAbsorptionShape );
      var lightAbsorbingShape = new LightAbsorbingShape( scaledAndTranslatedCloudAbsorptionShape, 0 );

      cloud.existenceStrengthProperty.link( function( existenceStrength ) {
        lightAbsorbingShape.absorptionCoefficientProperty.set( existenceStrength / 10 );
      } );

      lightRays.addLightAbsorbingShape( lightAbsorbingShape );

      var cloudNode = new CloudNode( cloud, modelViewTransform );
      cloudNode.opacity = 0;
      self.addChild( cloudNode );

      if ( EFACQueryParameters.showHelperShapes ) {
        self.addChild( new Path( scaledAndTranslatedCloudAbsorptionShape, {
          stroke: 'red'
        } ) );
      }
    } );

    // add slider panel to control cloudiness
    var slider = new VSlider(
      sun.cloudinessProperty,
      new Range( 0, 1 ),
      { top: 0, left: 0 }
    );

    function tickLabel( label ) {
      return new Text( label, {
        font: SLIDER_LABEL_FONT,
        maxWidth: CONTROL_PANEL_TEXT_MAX_WIDTH
      } );
    }

    slider.addMajorTick( 0, tickLabel( noneString ) );
    slider.addMajorTick( 1, tickLabel( lotsString ) );

    var titleText = new Text( cloudsString, {
      font: CONTROL_PANEL_TITLE_FONT,
      maxWidth: CONTROL_PANEL_TEXT_MAX_WIDTH
    } );

    var iconNode = new Image( cloudImage, { scale: 0.25 } );

    var titleBox = new HBox( {
      children: [ titleText, iconNode ],
      spacing: 10
    } );

    var panelContent = new VBox( {
      children: [ titleBox, slider ],
      spacing: 10,
      resize: false
    } );

    this.addChild( new Panel( panelContent, {
      fill: EFACConstants.CONTROL_PANEL_BACKGROUND_COLOR,
      stroke: EFACConstants.CONTROL_PANEL_OUTLINE_STROKE,
      lineWidth: EFACConstants.CONTROL_PANEL_OUTLINE_LINE_WIDTH,
      cornerRadius: EFACConstants.CONTROL_PANEL_CORNER_RADIUS,
      centerX: 0,
      centerY: 0,
      resize: false
    } ) );

    // add the energy chunks, which reside on their own layer
    this.addChild( new EnergyChunkLayer( sun.energyChunkList, modelViewTransform, {
      parentPositionProperty: sun.positionProperty
    } ) );
    this.addChild( sunPath );

    // add/remove the light-absorbing shape for the solar panel
    var currentLightAbsorbingShape = null;

    // visible absorption shape used for debugging
    var helperAbsorptionNode = null;

    Property.multilink(
      [ sun.activeProperty, sun.solarPanel.activeProperty ],
      function( sunActive, solarPanelActive ) {

        if ( sunActive && solarPanelActive ) {
          var absorptionShape = sun.solarPanel.getAbsorptionShape();
          var translatedAbsorptionShape = absorptionShape.transformed( Matrix3.translation(
            -sun.positionProperty.value.x,
            -sun.positionProperty.value.y
          ) );
          var scaledAndTranslatedAbsorptionShape = scaleOnlyMVT.modelToViewShape( translatedAbsorptionShape );
          currentLightAbsorbingShape = new LightAbsorbingShape( scaledAndTranslatedAbsorptionShape, 1 );

          lightRays.addLightAbsorbingShape( currentLightAbsorbingShape );

          // for debug, show absorption shape outline with dotted line visible on top of SolarPanel's helper shape
          if ( EFACQueryParameters.showHelperShapes ) {
            helperAbsorptionNode = new Path( scaledAndTranslatedAbsorptionShape, {
              stroke: 'lime',
              lineDash: [ 4, 8 ]
            } );
            self.addChild( helperAbsorptionNode );
          }
        }
        else if ( currentLightAbsorbingShape !== null ) {
          lightRays.removeLightAbsorbingShape( currentLightAbsorbingShape );
          currentLightAbsorbingShape = null;

          // for debug
          if ( EFACQueryParameters.showHelperShapes && helperAbsorptionNode ) {
            self.removeChild( helperAbsorptionNode );
            helperAbsorptionNode = null;
          }
        }
      }
    );
  }

  /**
   * inner type - a shape with observable light absorption coefficient
   * @param {Shape} shape
   * @param {number} initialAbsorptionCoefficient
   * @constructor
   */
  function LightAbsorbingShape( shape, initialAbsorptionCoefficient ) {
    this.absorptionCoefficientProperty = new Property( initialAbsorptionCoefficient );
    this.shape = shape;
  }

  energyFormsAndChanges.register( 'LightAbsorbingShape', LightAbsorbingShape );

  inherit( Object, LightAbsorbingShape, {
    reset: function() {
      this.absorptionCoefficientProperty.reset();
    }
  } );

  /**
   * inner type - a cloud
   * @param cloud
   * @param modelViewTransform
   * @constructor
   */
  function CloudNode( cloud, modelViewTransform ) {
    Node.call( this );
    var self = this;

    var cloudNode = new Image( cloudImage );
    cloudNode.scale(
      modelViewTransform.modelToViewDeltaX( Cloud.WIDTH ) / cloudNode.width,
      -modelViewTransform.modelToViewDeltaY( Cloud.HEIGHT ) / cloudNode.height
    );
    this.addChild( cloudNode );

    this.center = modelViewTransform.modelToViewDelta( cloud.offsetFromParent );

    cloud.existenceStrengthProperty.link( function( opacity ) {
      self.opacity = opacity;
    } );
  }

  inherit( Node, CloudNode );

  energyFormsAndChanges.register( 'SunNode', SunNode );

  return inherit( MoveFadeModelElementNode, SunNode );
} );

<commit_msg>Move cloud slider panel in front of sun energy chunks, see https://github.com/phetsims/energy-forms-and-changes/issues/148<commit_after>// Copyright 2016-2018, University of Colorado Boulder

/**
 * a Scenery Node that represents the sun, clouds, and a slider to control the level of cloudiness in the view
 *
 * @author John Blanco
 * @author Andrew Adare
 */
define( function( require ) {
  'use strict';

  // modules
  var Cloud = require( 'ENERGY_FORMS_AND_CHANGES/systems/model/Cloud' );
  var Color = require( 'SCENERY/util/Color' );
  var EFACConstants = require( 'ENERGY_FORMS_AND_CHANGES/common/EFACConstants' );
  var EFACQueryParameters = require( 'ENERGY_FORMS_AND_CHANGES/common/EFACQueryParameters' );
  var EnergyChunkLayer = require( 'ENERGY_FORMS_AND_CHANGES/common/view/EnergyChunkLayer' );
  var energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  var HBox = require( 'SCENERY/nodes/HBox' );
  var Image = require( 'SCENERY/nodes/Image' );
  var inherit = require( 'PHET_CORE/inherit' );
  var LightRays = require( 'ENERGY_FORMS_AND_CHANGES/systems/view/LightRays' );
  var Matrix3 = require( 'DOT/Matrix3' );
  var ModelViewTransform2 = require( 'PHETCOMMON/view/ModelViewTransform2' );
  var MoveFadeModelElementNode = require( 'ENERGY_FORMS_AND_CHANGES/systems/view/MoveFadeModelElementNode' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Panel = require( 'SUN/Panel' );
  var Path = require( 'SCENERY/nodes/Path' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  var Property = require( 'AXON/Property' );
  var RadialGradient = require( 'SCENERY/util/RadialGradient' );
  var Range = require( 'DOT/Range' );
  var Shape = require( 'KITE/Shape' );
  var SunEnergySource = require( 'ENERGY_FORMS_AND_CHANGES/systems/model/SunEnergySource' );
  var Text = require( 'SCENERY/nodes/Text' );
  var VBox = require( 'SCENERY/nodes/VBox' );
  var Vector2 = require( 'DOT/Vector2' );
  var VSlider = require( 'SUN/VSlider' );

  // images
  var cloudImage = require( 'image!ENERGY_FORMS_AND_CHANGES/cloud_1.png' );

  // strings
  var cloudsString = require( 'string!ENERGY_FORMS_AND_CHANGES/clouds' );
  var lotsString = require( 'string!ENERGY_FORMS_AND_CHANGES/lots' );
  var noneString = require( 'string!ENERGY_FORMS_AND_CHANGES/none' );

  // constants
  var CONTROL_PANEL_TITLE_FONT = new PhetFont( 16 );
  var CONTROL_PANEL_TEXT_MAX_WIDTH = 50;
  var SLIDER_LABEL_FONT = new PhetFont( 12 );

  /**
   * @param {SunEnergySource} sun Sun model element
   * @param {Property} energyChunksVisibleProperty
   * @param {ModelViewTransform} modelViewTransform
   * @constructor
   */
  function SunNode( sun, energyChunksVisibleProperty, modelViewTransform ) {
    MoveFadeModelElementNode.call( this, sun, modelViewTransform );
    var self = this;

    var sunCenter = modelViewTransform.modelToViewDelta( SunEnergySource.OFFSET_TO_CENTER_OF_SUN );
    var sunRadius = modelViewTransform.modelToViewDeltaX( sun.radius );
    var lightRays = new LightRays( sunCenter, sunRadius, 1000, 40, Color.YELLOW );

    this.addChild( lightRays );

    // turn off light rays when energy chunks are visible
    energyChunksVisibleProperty.link( function( chunksVisible ) {
      lightRays.setVisible( !chunksVisible );
    } );

    // add the sun
    var sunShape = Shape.ellipse( 0, 0, sunRadius, sunRadius );
    var sunPath = new Path( sunShape, {
      fill: new RadialGradient( 0, 0, 0, 0, 0, sunRadius )
        .addColorStop( 0, 'white' )
        .addColorStop( 0.25, 'white' )
        .addColorStop( 1, '#FFD700' ),
      lineWidth: 1,
      stroke: 'yellow'
    } );

    sunPath.setTranslation( sunCenter );

    // create a scale-only MVT since translation of the absorption shapes is done separately
    var scaleOnlyMVT = ModelViewTransform2.createSinglePointScaleInvertedYMapping(
      Vector2.ZERO,
      Vector2.ZERO,
      modelViewTransform.getMatrix().getScaleVector().x
    );

    // add clouds, initially transparent
    sun.clouds.forEach( function( cloud ) {

      // make a light-absorbing shape from the cloud's absorption ellipse
      var cloudAbsorptionShape = cloud.getCloudAbsorptionReflectionShape();
      var translatedCloudAbsorptionShape = cloudAbsorptionShape.transformed( Matrix3.translation(
        -sun.positionProperty.value.x,
        -sun.positionProperty.value.y
      ) );
      var scaledAndTranslatedCloudAbsorptionShape = scaleOnlyMVT.modelToViewShape( translatedCloudAbsorptionShape );
      var lightAbsorbingShape = new LightAbsorbingShape( scaledAndTranslatedCloudAbsorptionShape, 0 );

      cloud.existenceStrengthProperty.link( function( existenceStrength ) {
        lightAbsorbingShape.absorptionCoefficientProperty.set( existenceStrength / 10 );
      } );

      lightRays.addLightAbsorbingShape( lightAbsorbingShape );

      var cloudNode = new CloudNode( cloud, modelViewTransform );
      cloudNode.opacity = 0;
      self.addChild( cloudNode );

      if ( EFACQueryParameters.showHelperShapes ) {
        self.addChild( new Path( scaledAndTranslatedCloudAbsorptionShape, {
          stroke: 'red'
        } ) );
      }
    } );

    // add the energy chunks, which reside on their own layer
    this.addChild( new EnergyChunkLayer( sun.energyChunkList, modelViewTransform, {
      parentPositionProperty: sun.positionProperty
    } ) );
    this.addChild( sunPath );

    // add slider panel to control cloudiness
    var slider = new VSlider(
      sun.cloudinessProperty,
      new Range( 0, 1 ),
      { top: 0, left: 0 }
    );

    function tickLabel( label ) {
      return new Text( label, {
        font: SLIDER_LABEL_FONT,
        maxWidth: CONTROL_PANEL_TEXT_MAX_WIDTH
      } );
    }

    slider.addMajorTick( 0, tickLabel( noneString ) );
    slider.addMajorTick( 1, tickLabel( lotsString ) );

    var titleText = new Text( cloudsString, {
      font: CONTROL_PANEL_TITLE_FONT,
      maxWidth: CONTROL_PANEL_TEXT_MAX_WIDTH
    } );

    var iconNode = new Image( cloudImage, { scale: 0.25 } );

    var titleBox = new HBox( {
      children: [ titleText, iconNode ],
      spacing: 10
    } );

    var panelContent = new VBox( {
      children: [ titleBox, slider ],
      spacing: 10,
      resize: false
    } );

    this.addChild( new Panel( panelContent, {
      fill: EFACConstants.CONTROL_PANEL_BACKGROUND_COLOR,
      stroke: EFACConstants.CONTROL_PANEL_OUTLINE_STROKE,
      lineWidth: EFACConstants.CONTROL_PANEL_OUTLINE_LINE_WIDTH,
      cornerRadius: EFACConstants.CONTROL_PANEL_CORNER_RADIUS,
      centerX: 0,
      centerY: 0,
      resize: false
    } ) );

    // add/remove the light-absorbing shape for the solar panel
    var currentLightAbsorbingShape = null;

    // visible absorption shape used for debugging
    var helperAbsorptionNode = null;

    Property.multilink(
      [ sun.activeProperty, sun.solarPanel.activeProperty ],
      function( sunActive, solarPanelActive ) {

        if ( sunActive && solarPanelActive ) {
          var absorptionShape = sun.solarPanel.getAbsorptionShape();
          var translatedAbsorptionShape = absorptionShape.transformed( Matrix3.translation(
            -sun.positionProperty.value.x,
            -sun.positionProperty.value.y
          ) );
          var scaledAndTranslatedAbsorptionShape = scaleOnlyMVT.modelToViewShape( translatedAbsorptionShape );
          currentLightAbsorbingShape = new LightAbsorbingShape( scaledAndTranslatedAbsorptionShape, 1 );

          lightRays.addLightAbsorbingShape( currentLightAbsorbingShape );

          // for debug, show absorption shape outline with dotted line visible on top of SolarPanel's helper shape
          if ( EFACQueryParameters.showHelperShapes ) {
            helperAbsorptionNode = new Path( scaledAndTranslatedAbsorptionShape, {
              stroke: 'lime',
              lineDash: [ 4, 8 ]
            } );
            self.addChild( helperAbsorptionNode );
          }
        }
        else if ( currentLightAbsorbingShape !== null ) {
          lightRays.removeLightAbsorbingShape( currentLightAbsorbingShape );
          currentLightAbsorbingShape = null;

          // for debug
          if ( EFACQueryParameters.showHelperShapes && helperAbsorptionNode ) {
            self.removeChild( helperAbsorptionNode );
            helperAbsorptionNode = null;
          }
        }
      }
    );
  }

  /**
   * inner type - a shape with observable light absorption coefficient
   * @param {Shape} shape
   * @param {number} initialAbsorptionCoefficient
   * @constructor
   */
  function LightAbsorbingShape( shape, initialAbsorptionCoefficient ) {
    this.absorptionCoefficientProperty = new Property( initialAbsorptionCoefficient );
    this.shape = shape;
  }

  energyFormsAndChanges.register( 'LightAbsorbingShape', LightAbsorbingShape );

  inherit( Object, LightAbsorbingShape, {
    reset: function() {
      this.absorptionCoefficientProperty.reset();
    }
  } );

  /**
   * inner type - a cloud
   * @param cloud
   * @param modelViewTransform
   * @constructor
   */
  function CloudNode( cloud, modelViewTransform ) {
    Node.call( this );
    var self = this;

    var cloudNode = new Image( cloudImage );
    cloudNode.scale(
      modelViewTransform.modelToViewDeltaX( Cloud.WIDTH ) / cloudNode.width,
      -modelViewTransform.modelToViewDeltaY( Cloud.HEIGHT ) / cloudNode.height
    );
    this.addChild( cloudNode );

    this.center = modelViewTransform.modelToViewDelta( cloud.offsetFromParent );

    cloud.existenceStrengthProperty.link( function( opacity ) {
      self.opacity = opacity;
    } );
  }

  inherit( Node, CloudNode );

  energyFormsAndChanges.register( 'SunNode', SunNode );

  return inherit( MoveFadeModelElementNode, SunNode );
} );

<|endoftext|>


<commit_before>'use strict';

const Types = require('../constants/types.js');
const Charsets = require('../constants/charsets.js');
const helpers = require('../helpers');
const genFunc = require('generate-function');
const parserCache = require('./parser_cache.js');

const typeNames = [];
for (const t in Types) {
  typeNames[Types[t]] = t;
}

function readCodeFor(type, charset, encodingExpr, config, options) {
  const supportBigNumbers =
    options.supportBigNumbers || config.supportBigNumbers;
  const bigNumberStrings = options.bigNumberStrings || config.bigNumberStrings;
  const timezone = options.timezone || config.timezone;
  const dateStrings = options.dateStrings || config.dateStrings;

  switch (type) {
    case Types.TINY:
    case Types.SHORT:
    case Types.LONG:
    case Types.INT24:
    case Types.YEAR:
      return 'packet.parseLengthCodedIntNoBigCheck()';
    case Types.LONGLONG:
      if (supportBigNumbers && bigNumberStrings) {
        return 'packet.parseLengthCodedIntString()';
      }
      return `packet.parseLengthCodedInt(${supportBigNumbers})`;
    case Types.FLOAT:
    case Types.DOUBLE:
      return 'packet.parseLengthCodedFloat()';
    case Types.NULL:
      return 'packet.readLengthCodedNumber()';
    case Types.DECIMAL:
    case Types.NEWDECIMAL:
      if (config.decimalNumbers) {
        return 'packet.parseLengthCodedFloat()';
      }
      return 'packet.readLengthCodedString("ascii")';
    case Types.DATE:
      if (helpers.typeMatch(type, dateStrings, Types)) {
        return 'packet.readLengthCodedString("ascii")';
      }
      return `packet.parseDate('${timezone}')`;
    case Types.DATETIME:
    case Types.TIMESTAMP:
      if (helpers.typeMatch(type, dateStrings, Types)) {
        return 'packet.readLengthCodedString("ascii")';
      }
      return `packet.parseDateTime('${timezone}')`;
    case Types.TIME:
      return 'packet.readLengthCodedString("ascii")';
    case Types.GEOMETRY:
      return 'packet.parseGeometryValue()';
    case Types.JSON:
      // Since for JSON columns mysql always returns charset 63 (BINARY),
      // we have to handle it according to JSON specs and use "utf8",
      // see https://github.com/sidorares/node-mysql2/issues/409
      return 'JSON.parse(packet.readLengthCodedString("utf8"))';
    default:
      if (charset === Charsets.BINARY) {
        return 'packet.readLengthCodedBuffer()';
      }
      return `packet.readLengthCodedString(${encodingExpr})`;
  }
}

function compile(fields, options, config) {
  // use global typeCast if current query doesn't specify one
  if (
    typeof config.typeCast === 'function' &&
    typeof options.typeCast !== 'function'
  ) {
    options.typeCast = config.typeCast;
  }

  function wrap(field, _this) {
    return {
      type: typeNames[field.columnType],
      length: field.columnLength,
      db: field.schema,
      table: field.table,
      name: field.name,
      string: function() {
        return _this.packet.readLengthCodedString(field.encoding);
      },
      buffer: function() {
        return _this.packet.readLengthCodedBuffer();
      },
      geometry: function() {
        return _this.packet.parseGeometryValue();
      }
    };
  }

  const parserFn = genFunc();

  /* eslint-disable no-trailing-spaces */
  /* eslint-disable no-spaced-func */
  /* eslint-disable no-unexpected-multiline */
  parserFn('(function () {')(
    'return class TextRow {'
  );

  // constructor method
  parserFn('constructor(fields) {');
  // node-mysql typeCast compatibility wrapper
  // see https://github.com/mysqljs/mysql/blob/96fdd0566b654436624e2375c7b6604b1f50f825/lib/protocol/packets/Field.js
  if (typeof options.typeCast === 'function') {
    parserFn('const _this = this;');
    parserFn('for(let i=0; i<fields.length; ++i) {');
    parserFn('this[`wrap${i}`] = wrap(fields[i], _this);');
    parserFn('}');
  }
  parserFn('}');

  // next method
  parserFn('next(packet, fields, options) {');
  parserFn("this.packet = packet;");
  if (options.rowsAsArray) {
    parserFn(`const result = new Array(${fields.length});`);
  } else {
    parserFn("const result = {};");
  }

  const resultTables = {};
  let resultTablesArray = [];

  if (options.nestTables === true) {
    for (let i=0; i < fields.length; i++) {
      resultTables[fields[i].table] = 1;
    }
    resultTablesArray = Object.keys(resultTables);
    for (let i=0; i < resultTablesArray.length; i++) {
      parserFn(`result[${helpers.srcEscape(resultTablesArray[i])}] = {};`);
    }
  }

  let lvalue = '';
  let fieldName = '';
  for (let i = 0; i < fields.length; i++) {
    fieldName = helpers.srcEscape(fields[i].name);
    parserFn(`// ${fieldName}: ${typeNames[fields[i].columnType]}`);
    if (typeof options.nestTables === 'string') {
      lvalue = `result[${helpers.srcEscape(
        fields[i].table + options.nestTables + fields[i].name
      )}]`;
    } else if (options.nestTables === true) {
      lvalue = `result[${helpers.srcEscape(fields[i].table)}][${fieldName}]`;
    } else if (options.rowsAsArray) {
      lvalue = `result[${i.toString(10)}]`;
    } else {
      lvalue = `result[${fieldName}]`;
    }
    if (options.typeCast === false) {
      parserFn(`${lvalue} = packet.readLengthCodedBuffer();`);
    } else {
      const encodingExpr = `fields[${i}].encoding`;
      const readCode = readCodeFor(
        fields[i].columnType,
        fields[i].characterSet,
        encodingExpr,
        config,
        options
      );
      if (typeof options.typeCast === 'function') {
        parserFn(`${lvalue} = options.typeCast(this.wrap${i}, function() { return ${readCode} });`);
      }  else {
        parserFn(`${lvalue} = ${readCode};`);
      }
    }
  }

  parserFn('return result;');
  parserFn('}');
  parserFn('};')('})()');

  /* eslint-enable no-trailing-spaces */
  /* eslint-enable no-spaced-func */
  /* eslint-enable no-unexpected-multiline */

  if (config.debug) {
    helpers.printDebugWithCode(
      'Compiled text protocol row parser',
      parserFn.toString()
    );
  }
  if (typeof options.typeCast === 'function') {
    return parserFn.toFunction({wrap});
  }
  return parserFn.toFunction();
}

function getTextParser(fields, options, config) {
  return parserCache.getParser('text', fields, options, config, compile);
}

module.exports = getTextParser;
<commit_msg>Add option to override encoding<commit_after>'use strict';

const Types = require('../constants/types.js');
const Charsets = require('../constants/charsets.js');
const helpers = require('../helpers');
const genFunc = require('generate-function');
const parserCache = require('./parser_cache.js');

const typeNames = [];
for (const t in Types) {
  typeNames[Types[t]] = t;
}

function readCodeFor(type, charset, encodingExpr, config, options) {
  const supportBigNumbers =
    options.supportBigNumbers || config.supportBigNumbers;
  const bigNumberStrings = options.bigNumberStrings || config.bigNumberStrings;
  const timezone = options.timezone || config.timezone;
  const dateStrings = options.dateStrings || config.dateStrings;

  switch (type) {
    case Types.TINY:
    case Types.SHORT:
    case Types.LONG:
    case Types.INT24:
    case Types.YEAR:
      return 'packet.parseLengthCodedIntNoBigCheck()';
    case Types.LONGLONG:
      if (supportBigNumbers && bigNumberStrings) {
        return 'packet.parseLengthCodedIntString()';
      }
      return `packet.parseLengthCodedInt(${supportBigNumbers})`;
    case Types.FLOAT:
    case Types.DOUBLE:
      return 'packet.parseLengthCodedFloat()';
    case Types.NULL:
      return 'packet.readLengthCodedNumber()';
    case Types.DECIMAL:
    case Types.NEWDECIMAL:
      if (config.decimalNumbers) {
        return 'packet.parseLengthCodedFloat()';
      }
      return 'packet.readLengthCodedString("ascii")';
    case Types.DATE:
      if (helpers.typeMatch(type, dateStrings, Types)) {
        return 'packet.readLengthCodedString("ascii")';
      }
      return `packet.parseDate('${timezone}')`;
    case Types.DATETIME:
    case Types.TIMESTAMP:
      if (helpers.typeMatch(type, dateStrings, Types)) {
        return 'packet.readLengthCodedString("ascii")';
      }
      return `packet.parseDateTime('${timezone}')`;
    case Types.TIME:
      return 'packet.readLengthCodedString("ascii")';
    case Types.GEOMETRY:
      return 'packet.parseGeometryValue()';
    case Types.JSON:
      // Since for JSON columns mysql always returns charset 63 (BINARY),
      // we have to handle it according to JSON specs and use "utf8",
      // see https://github.com/sidorares/node-mysql2/issues/409
      return 'JSON.parse(packet.readLengthCodedString("utf8"))';
    default:
      if (charset === Charsets.BINARY) {
        return 'packet.readLengthCodedBuffer()';
      }
      return `packet.readLengthCodedString(${encodingExpr})`;
  }
}

function compile(fields, options, config) {
  // use global typeCast if current query doesn't specify one
  if (
    typeof config.typeCast === 'function' &&
    typeof options.typeCast !== 'function'
  ) {
    options.typeCast = config.typeCast;
  }

  function wrap(field, _this) {
    return {
      type: typeNames[field.columnType],
      length: field.columnLength,
      db: field.schema,
      table: field.table,
      name: field.name,
      string: function(encoding = field.encoding) {
        return _this.packet.readLengthCodedString(encoding);
      },
      buffer: function() {
        return _this.packet.readLengthCodedBuffer();
      },
      geometry: function() {
        return _this.packet.parseGeometryValue();
      }
    };
  }

  const parserFn = genFunc();

  /* eslint-disable no-trailing-spaces */
  /* eslint-disable no-spaced-func */
  /* eslint-disable no-unexpected-multiline */
  parserFn('(function () {')(
    'return class TextRow {'
  );

  // constructor method
  parserFn('constructor(fields) {');
  // node-mysql typeCast compatibility wrapper
  // see https://github.com/mysqljs/mysql/blob/96fdd0566b654436624e2375c7b6604b1f50f825/lib/protocol/packets/Field.js
  if (typeof options.typeCast === 'function') {
    parserFn('const _this = this;');
    parserFn('for(let i=0; i<fields.length; ++i) {');
    parserFn('this[`wrap${i}`] = wrap(fields[i], _this);');
    parserFn('}');
  }
  parserFn('}');

  // next method
  parserFn('next(packet, fields, options) {');
  parserFn("this.packet = packet;");
  if (options.rowsAsArray) {
    parserFn(`const result = new Array(${fields.length});`);
  } else {
    parserFn("const result = {};");
  }

  const resultTables = {};
  let resultTablesArray = [];

  if (options.nestTables === true) {
    for (let i=0; i < fields.length; i++) {
      resultTables[fields[i].table] = 1;
    }
    resultTablesArray = Object.keys(resultTables);
    for (let i=0; i < resultTablesArray.length; i++) {
      parserFn(`result[${helpers.srcEscape(resultTablesArray[i])}] = {};`);
    }
  }

  let lvalue = '';
  let fieldName = '';
  for (let i = 0; i < fields.length; i++) {
    fieldName = helpers.srcEscape(fields[i].name);
    parserFn(`// ${fieldName}: ${typeNames[fields[i].columnType]}`);
    if (typeof options.nestTables === 'string') {
      lvalue = `result[${helpers.srcEscape(
        fields[i].table + options.nestTables + fields[i].name
      )}]`;
    } else if (options.nestTables === true) {
      lvalue = `result[${helpers.srcEscape(fields[i].table)}][${fieldName}]`;
    } else if (options.rowsAsArray) {
      lvalue = `result[${i.toString(10)}]`;
    } else {
      lvalue = `result[${fieldName}]`;
    }
    if (options.typeCast === false) {
      parserFn(`${lvalue} = packet.readLengthCodedBuffer();`);
    } else {
      const encodingExpr = `fields[${i}].encoding`;
      const readCode = readCodeFor(
        fields[i].columnType,
        fields[i].characterSet,
        encodingExpr,
        config,
        options
      );
      if (typeof options.typeCast === 'function') {
        parserFn(`${lvalue} = options.typeCast(this.wrap${i}, function() { return ${readCode} });`);
      }  else {
        parserFn(`${lvalue} = ${readCode};`);
      }
    }
  }

  parserFn('return result;');
  parserFn('}');
  parserFn('};')('})()');

  /* eslint-enable no-trailing-spaces */
  /* eslint-enable no-spaced-func */
  /* eslint-enable no-unexpected-multiline */

  if (config.debug) {
    helpers.printDebugWithCode(
      'Compiled text protocol row parser',
      parserFn.toString()
    );
  }
  if (typeof options.typeCast === 'function') {
    return parserFn.toFunction({wrap});
  }
  return parserFn.toFunction();
}

function getTextParser(fields, options, config) {
  return parserCache.getParser('text', fields, options, config, compile);
}

module.exports = getTextParser;
<|endoftext|>


<commit_before>'use strict';

// Use Applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('rubrics');

<commit_msg>Deleting this file, which is a duplicate <commit_after><|endoftext|>


<commit_before>(function () {
    'use strict';

    var Player = function () {
        //SpriteSheet Player
        this.imageName = 'player_image';
        this.imageUrl = 'assets/spritesheets/walk-idle-transform-BAT.png';

        //BatShot
        this.imageNameBatShot = 'batShot_image';
        this.imageUrlBatShot = 'assets/spritesheets/Sprites-morcego-bala-16x16.png';

        //Lives Blood
        this.imageNameLives = 'lives_image';
        this.imageUrlLives = 'assets/img/blood.png';

        //Bat Hud
        this.imageBatHud = 'bat_hud_image';
        this.imageUrlBatHud = 'assets/spritesheets/bat_hud.png';

        //Bat Hud
        this.imageCapHud = 'capa_hud_image';
        this.imageUrlCapHud = 'assets/spritesheets/capa_hud.png';

        //Select Item Hud
        this.imageSelectHud = 'select_hud_image';
        this.imageUrlSelectHud = 'assets/spritesheets/select-item.png';

        gameManager.globals.score = 0;
        gameManager.globals.scoreText = '';

        this.normalGravity = 750;
        this.fallingGravity = 50;
        this.jumpVelocity = -450;
        this.isJumping = false;
        this.isDoubleJumping = false;
        this.initialPositionX = 50;
        this.initialPositionY = this.game.height - 500;

        this.bullets;
        this.bulletTime = 0;
        this.bullet;

        //Sound Dead
        this.soundNameDead = 'deadSound';
        this.soundUrlDead = 'assets/sounds/player/die1.ogg';
        this.soundDead = null;

        // Sound ShotBats
        this.soundNameShot = 'shotSound';
        this.soundUrlShot = 'assets/sounds/player/longRangeHitBat2.ogg';
        this.soundShot = null;

        // Sound Jump
        this.soundNameJump = 'jumpSound';
        this.soundUrlJump = 'assets/sounds/player/jump1.ogg';
        this.soundJump = null;

        // Sound Pickup
        this.soundNamePickupBlood = 'pickupSound';
        this.soundUrlPickupBlood = 'assets/sounds/player/sipBlood.ogg';
        this.soundPickup = null;

        this.stateContext = null;

    }

    Player.prototype.preload = function () {
        //Load Imagens
        // Player
        this.game.load.spritesheet(this.imageName, this.imageUrl, 48, 64);

        // Bullet Bat
        this.game.load.spritesheet(this.imageNameBatShot, this.imageUrlBatShot, 16, 16);

        // Lives
        this.game.load.image(this.imageNameLives, this.imageUrlLives);

         // hud
        this.game.load.image(this.imageBatHud, this.imageUrlBatHud);
        this.game.load.image(this.imageCapHud, this.imageUrlCapHud);
        this.game.load.image(this.imageSelectHud, this.imageUrlSelectHud);

        //Load Sounds
        this.game.load.audio(this.soundNameDead, this.soundUrlDead);
        this.game.load.audio(this.soundNameShot, this.soundUrlShot);
        this.game.load.audio(this.soundNameJump, this.soundUrlJump);
        this.game.load.audio(this.soundNamePickupBlood, this.soundUrlPickupBlood);
    }

    Player.prototype.setup = function (stateContext) {
        var self = this;

        //Criando balas
        this.bullets = this.game.add.group();
        this.bullets.enableBody = true;
        this.bullets.physicsBodyType = Phaser.Physics.ARCADE;
        for (var i = 0; i < 40; i++){
            var b = this.bullets.create(0, 0, this.imageNameBatShot);
            b.name = 'imageNameBatShot' + i;
            b.animations.add('shotBat', [0, 1, 2, 3, 4, 5, 6, 7], 100, true);
            b.exists = false;
            b.visible = false;
            b.checkWorldBounds = true;
            b.events.onOutOfBounds.add(this.resetBullet, this);
        }

        //SpriteSheet and Animations Player
        this.sprite = this.game.add.sprite(this.initialPositionX, this.initialPositionY, this.imageName);
        this.sprite.frame = 0;
        this.sprite.animations.add('walk', [0, 1, 2, 3], 22, true);
        this.sprite.animations.add('idle', [4,5,6], 4, true);
        this.sprite.animations.add('transform', [7,8,9], 22, true);
        this.sprite.animations.add('batTransformation', [10,11,12,13,14,15,16,17,18,19], 22, true);
        this.sprite.animations.add('wolfRun', [10,11,12,13,14,15,16,17,18,19], 22, true);
        this.sprite.anchor.set(0.5);
        this.game.physics.arcade.enable(this.sprite);
        this.sprite.body.gravity.y = this.normalGravity;
        this.stateContext = stateContext;

        //Img Blood Lives
        this.imageBloodLives1 = this.game.add.sprite(40, 25, this.imageNameLives);
        this.imageBloodLives1.anchor.set(0.5);
        this.imageBloodLives1.fixedToCamera = true;

        this.imageBloodLives2 = this.game.add.sprite(90, 25, this.imageNameLives);
        this.imageBloodLives2.anchor.set(0.5);
        this.imageBloodLives2.fixedToCamera = true;

        this.imageBloodLives3 = this.game.add.sprite(140, 25, this.imageNameLives);
        this.imageBloodLives3.anchor.set(0.5);
        this.imageBloodLives3.fixedToCamera = true;

        //Hud
        this.imageBatHudView = this.game.add.sprite(200, 25, this.imageBatHud);
        this.imageBatHudView.anchor.set(0.5);
        this.imageBatHudView.fixedToCamera = true;

        this.imageCapHudView = this.game.add.sprite(280, 25, this.imageCapHud);
        this.imageCapHudView.anchor.set(0.5);
        this.imageCapHudView.fixedToCamera = true;

        // Text Scores
        gameManager.globals.scoreText = this.game.add.text(670, 10, gameManager.globals.score, { fill: '#ffffff', align: 'center', fontSize: 32 });
        gameManager.globals.scoreText.anchor.set(0,0);
        gameManager.globals.scoreText.fixedToCamera = true;

        //Sounds
        this.soundDead = this.game.add.audio(this.soundNameDead);
        this.soundShot = this.game.add.audio(this.soundNameShot);
        this.soundJump = this.game.add.audio(this.soundNameJump);
        this.soundPickup = this.game.add.audio(this.soundNamePickupBlood);

        //Controles
        //this.keys = this.game.input.keyboard.createCursorKeys();
        // Movement Player
        this.leftButton = this.game.input.keyboard.addKey(Phaser.Keyboard.A);
        this.rightButton = this.game.input.keyboard.addKey(Phaser.Keyboard.D);
        // Jump
        this.jumpButton = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
        this.jumpButton.onDown.add(this.jump, this);
        // Shot
        this.shotButton = this.game.input.keyboard.addKey(Phaser.Keyboard.ENTER);
        // Run
        this.runButton = this.game.input.keyboard.addKey(Phaser.Keyboard.SHIFT);
        this.runButton.onDown.add(this.run,this)

    }

    Player.prototype.decreaseLives = function () {
        gameManager.globals.lives--;
        this.soundDead.play();

        if(gameManager.globals.lives === 2) {
            this.imageBloodLives3.destroy();
        }

        if(gameManager.globals.lives === 1) {
            this.imageBloodLives2.destroy();
        }

        if(gameManager.globals.lives === 0) {
            this.imageBloodLives1.destroy();
            this.gameover();
        }
    }

    Player.prototype.addLives = function () {
        this.soundPickup.play();

        if(gameManager.globals.lives === 2) { // jogador com 2 corações e adicionando mais uma vida
            this.imageBloodLives2 = this.game.add.sprite(140, 25, this.imageNameLives);
            this.imageBloodLives2.anchor.set(0.5);
            this.imageBloodLives2.fixedToCamera = true;
            gameManager.globals.lives++;
        }

        if(gameManager.globals.lives === 1) { // jogador com 1 coração e adicionando mais uma vida
            this.imageBloodLives1 = this.game.add.sprite(90, 25, this.imageNameLives);
            this.imageBloodLives1.anchor.set(0.5);
            this.imageBloodLives1.fixedToCamera = true;
            gameManager.globals.lives++;
        }
    }

    Player.prototype.checkIsJumping = function () {
        if((this.isJumping) && (this.sprite.body.touching.down || this.sprite.body.onFloor())) {
            this.isJumping = false;
            this.isDoubleJumping = false;
            this.sprite.animations.play('walk');
            this.sprite.body.gravity.y = this.normalGravity;
        }
    }

    Player.prototype.gameover = function () {
        this.checkIsJumping();
        this.game.state.start('lose');
    }

    Player.prototype.jump = function () {
        if(this.sprite.body.touching.down || this.sprite.body.onFloor()) {
            this.isJumping = true;
            return doJump.apply(this);
        }
        else if(!this.isDoubleJumping) {
            this.isDoubleJumping = true;
            this.sprite.animations.play('batTransformation');
            return doJump.apply(this);
        }

        function doJump() {
            this.sprite.body.velocity.y = this.jumpVelocity || -450;
            this.soundJump.play();
        }
    }

    Player.prototype.run = function () {
        if(this.sprite.body.velocity.x != 0 && this.isJumping == false) {
            this.sprite.animations.play('transform');
            this.sprite.scale.x = 1 * Math.sign(this.sprite.body.velocity.x);
            this.sprite.body.velocity.x = (this.sprite.body.velocity.x * 15);
            console.log("correndo: ",this.sprite.body.velocity.x);
        }
    }

    Player.prototype.groundCollision = function (playerSprite) {
        this.checkIsJumping();
    }

    Player.prototype.handleInputs = function () {
        if(this.leftButton.isDown){
            this.sprite.body.velocity.x = -150; // Ajustar velocidade
            // Se o jogador estiver virado para a direita, inverter a escala para que ele vire para o outro lado
            if(this.sprite.scale.x == 1) this.sprite.scale.x = -1;
            // Iniciando a animação 'walk'
            if(!this.isJumping) {
                this.sprite.animations.play('walk');
            }
        }

        // mover o sprite para a direita
        else if(this.rightButton.isDown){
            // se a tecla direita estiver pressionada
            this.sprite.body.velocity.x = 150;  // Ajustar velocidade
            // Se o jogador estiver virado para a direita, inverter a escala para que ele vire para o outro lado
            if(this.sprite.scale.x == -1) this.sprite.scale.x = 1;

            if(!this.isDoubleJumping) {
                this.sprite.animations.play('walk');
            }
        }
        else {
            // Ajustar velocidade para zero
            this.sprite.body.velocity.x = 0;

            if(!this.isJumping && !this.isDoubleJumping) {
                this.sprite.animations.play('idle');
            }

            if(!this.isDoubleJumping) {
                this.sprite.animations.play('');
            }
        }

        if (this.shotButton.isDown){
            this.fire();
        }
    }

    Player.prototype.checkGravity = function () {
        if(this.sprite.body.velocity.y >= 0 && this.isDoubleJumping) {
            this.sprite.body.gravity.y = this.fallingGravity;
        }
    }

    // Score
    Player.prototype.increaseScoreRatos = function () {
        gameManager.globals.score = gameManager.globals.score + 50;
        gameManager.globals.scoreText.setText(gameManager.globals.score);
    }

    Player.prototype.increaseScoreEnemies = function () {
        gameManager.globals.score = gameManager.globals.score + 100;
        gameManager.globals.scoreText.setText(gameManager.globals.score);
    }

    //Shot Bats
    Player.prototype.fire = function () {
        if (this.game.time.now > this.bulletTime) {
            this.bullet = this.bullets.getFirstExists(false);
            if (this.bullet) {
                this.bullet.reset(this.sprite.x, this.sprite.y);
                if (this.sprite.scale.x == 1) {
                    this.bullet.body.velocity.x = 300;
                    this.soundShot.play();
                    this.bullet.animations.play('shotBat');
                    this.bulletTime = this.game.time.now + 150;
                } else {
                    this.bullet.body.velocity.x = -300;
                    this.bullet.scale.x = -1;
                    this.soundShot.play()
                    this.bullet.animations.play('shotBat');
                    this.bulletTime = this.game.time.now + 150;
                }
            }
        }
    }

    Player.prototype.resetBullet = function(bullet) {
        bullet.kill();
    }
    gameManager.addSprite('player', Player);

})();
<commit_msg>updates<commit_after>(function () {
    'use strict';

    var Player = function () {
        //SpriteSheet Player
        this.imageName = 'player_image';
        this.imageUrl = 'assets/spritesheets/walk-idle-transform-BAT.png';

        //BatShot
        this.imageNameBatShot = 'batShot_image';
        this.imageUrlBatShot = 'assets/spritesheets/Sprites-morcego-bala-16x16.png';

        //Lives Blood
        this.imageNameLives = 'lives_image';
        this.imageUrlLives = 'assets/img/blood.png';

        //Bat Hud
        this.imageBatHud = 'bat_hud_image';
        this.imageUrlBatHud = 'assets/spritesheets/bat_hud.png';

        //Bat Hud
        this.imageCapHud = 'capa_hud_image';
        this.imageUrlCapHud = 'assets/spritesheets/capa_hud.png';

        //Select Item Hud
        this.imageSelectHud = 'select_hud_image';
        this.imageUrlSelectHud = 'assets/spritesheets/select-item.png';

        gameManager.globals.score = 0;
        gameManager.globals.scoreText = '';

        this.normalGravity = 750;
        this.fallingGravity = 50;
        this.jumpVelocity = -450;
        this.isJumping = false;
        this.isDoubleJumping = false;
        this.initialPositionX = 50;
        this.initialPositionY = this.game.height - 500;

        this.bullets;
        this.bulletTime = 0;
        this.bullet;

        //Sound Dead
        this.soundNameDead = 'deadSound';
        this.soundUrlDead = 'assets/sounds/player/die1.ogg';
        this.soundDead = null;

        // Sound ShotBats
        this.soundNameShot = 'shotSound';
        this.soundUrlShot = 'assets/sounds/player/longRangeHitBat2.ogg';
        this.soundShot = null;

        // Sound Jump
        this.soundNameJump = 'jumpSound';
        this.soundUrlJump = 'assets/sounds/player/jump1.ogg';
        this.soundJump = null;

        // Sound Pickup
        this.soundNamePickupBlood = 'pickupSound';
        this.soundUrlPickupBlood = 'assets/sounds/player/sipBlood.ogg';
        this.soundPickup = null;

        this.stateContext = null;

    }

    Player.prototype.preload = function () {
        //Load Imagens
        // Player
        this.game.load.spritesheet(this.imageName, this.imageUrl, 48, 64);

        // Bullet Bat
        this.game.load.spritesheet(this.imageNameBatShot, this.imageUrlBatShot, 16, 16);

        // Lives
        this.game.load.image(this.imageNameLives, this.imageUrlLives);

         // hud
        this.game.load.image(this.imageBatHud, this.imageUrlBatHud);
        this.game.load.image(this.imageCapHud, this.imageUrlCapHud);
        this.game.load.image(this.imageSelectHud, this.imageUrlSelectHud);

        //Load Sounds
        this.game.load.audio(this.soundNameDead, this.soundUrlDead);
        this.game.load.audio(this.soundNameShot, this.soundUrlShot);
        this.game.load.audio(this.soundNameJump, this.soundUrlJump);
        this.game.load.audio(this.soundNamePickupBlood, this.soundUrlPickupBlood);
    }

    Player.prototype.setup = function (stateContext) {
        var self = this;

        //Criando balas
        this.bullets = this.game.add.group();
        this.bullets.enableBody = true;
        this.bullets.physicsBodyType = Phaser.Physics.ARCADE;
        for (var i = 0; i < 40; i++){
            var b = this.bullets.create(0, 0, this.imageNameBatShot);
            b.name = 'imageNameBatShot' + i;
            b.animations.add('shotBat', [0, 1, 2, 3, 4, 5, 6, 7], 100, true);
            b.exists = false;
            b.visible = false;
            b.checkWorldBounds = true;
            b.events.onOutOfBounds.add(this.resetBullet, this);
        }

        //SpriteSheet and Animations Player
        this.sprite = this.game.add.sprite(this.initialPositionX, this.initialPositionY, this.imageName);
        this.sprite.frame = 0;
        this.sprite.animations.add('walk', [0, 1, 2, 3], 22, true);
        this.sprite.animations.add('idle', [4,5,6], 4, true);
        this.sprite.animations.add('transform', [7,8,9], 22, true);
        this.sprite.animations.add('batTransformation', [10,11,12,13,14,15,16,17,18,19], 22, true);
        this.sprite.animations.add('wolfRun', [10,11,12,13,14,15,16,17,18,19], 22, true);
        this.sprite.anchor.set(0.5);
        this.game.physics.arcade.enable(this.sprite);
        this.sprite.body.gravity.y = this.normalGravity;
        this.stateContext = stateContext;

        //Img Blood Lives
        this.imageBloodLives1 = this.game.add.sprite(40, 25, this.imageNameLives);
        this.imageBloodLives1.anchor.set(0.5);
        this.imageBloodLives1.fixedToCamera = true;

        this.imageBloodLives2 = this.game.add.sprite(90, 25, this.imageNameLives);
        this.imageBloodLives2.anchor.set(0.5);
        this.imageBloodLives2.fixedToCamera = true;

        this.imageBloodLives3 = this.game.add.sprite(140, 25, this.imageNameLives);
        this.imageBloodLives3.anchor.set(0.5);
        this.imageBloodLives3.fixedToCamera = true;

        //Hud
        this.imageBatHudView = this.game.add.sprite(200, 25, this.imageBatHud);
        this.imageBatHudView.anchor.set(0.5);
        this.imageBatHudView.fixedToCamera = true;

        this.imageCapHudView = this.game.add.sprite(280, 25, this.imageCapHud);
        this.imageCapHudView.anchor.set(0.5);
        this.imageCapHudView.fixedToCamera = true;

        // Text Scores
        gameManager.globals.scoreText = this.game.add.text(670, 10, gameManager.globals.score, { fill: '#ffffff', align: 'center', fontSize: 32 });
        gameManager.globals.scoreText.anchor.set(0,0);
        gameManager.globals.scoreText.fixedToCamera = true;

        //Sounds
        this.soundDead = this.game.add.audio(this.soundNameDead);
        this.soundShot = this.game.add.audio(this.soundNameShot);
        this.soundJump = this.game.add.audio(this.soundNameJump);
        this.soundPickup = this.game.add.audio(this.soundNamePickupBlood);

        //Controles
        //this.keys = this.game.input.keyboard.createCursorKeys();
        // Movement Player
        this.leftButton = this.game.input.keyboard.addKey(Phaser.Keyboard.A);
        this.rightButton = this.game.input.keyboard.addKey(Phaser.Keyboard.D);
        // Jump
        this.jumpButton = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
        this.jumpButton.onDown.add(this.jump, this);
        // Shot
        this.shotButton = this.game.input.keyboard.addKey(Phaser.Keyboard.ENTER);
        // Run
        this.runButton = this.game.input.keyboard.addKey(Phaser.Keyboard.SHIFT);
        this.runButton.onDown.add(this.run,this)

    }

    Player.prototype.decreaseLives = function () {
        gameManager.globals.lives--;
        this.soundDead.play();

        if(gameManager.globals.lives === 2) {
            this.imageBloodLives3.destroy();
        }

        if(gameManager.globals.lives === 1) {
            this.imageBloodLives2.destroy();
        }

        if(gameManager.globals.lives === 0) {
            this.imageBloodLives1.destroy();
            this.gameover();
        }
    }

    Player.prototype.addLives = function () {
        this.soundPickup.play();

        if(gameManager.globals.lives === 2) { // jogador com 2 corações e adicionando mais uma vida
            this.imageBloodLives2 = this.game.add.sprite(140, 25, this.imageNameLives);
            this.imageBloodLives2.anchor.set(0.5);
            this.imageBloodLives2.fixedToCamera = true;
            gameManager.globals.lives++;
        }

        if(gameManager.globals.lives === 1) { // jogador com 1 coração e adicionando mais uma vida
            this.imageBloodLives1 = this.game.add.sprite(90, 25, this.imageNameLives);
            this.imageBloodLives1.anchor.set(0.5);
            this.imageBloodLives1.fixedToCamera = true;
            gameManager.globals.lives++;
        }
    }

    Player.prototype.checkIsJumping = function () {
        if((this.isJumping) && (this.sprite.body.touching.down || this.sprite.body.onFloor())) {
            this.isJumping = false;
            this.isDoubleJumping = false;
            this.sprite.animations.play('walk');
            this.sprite.body.gravity.y = this.normalGravity;
        }
    }

    Player.prototype.gameover = function () {
        this.checkIsJumping();
        this.game.state.start('lose');
    }

    Player.prototype.jump = function () {
        if(this.sprite.body.touching.down || this.sprite.body.onFloor()) {
            this.isJumping = true;
            return doJump.apply(this);
        }
        else if(!this.isDoubleJumping) {
            this.isDoubleJumping = true;
            this.sprite.animations.play('batTransformation');
            return doJump.apply(this);
        }

        function doJump() {
            this.sprite.body.velocity.y = this.jumpVelocity || -450;
            this.soundJump.play();
        }
    }

    Player.prototype.run = function () {
        if(this.sprite.body.velocity.x != 0 && this.isJumping == false) {
            this.sprite.animations.play('transform');
            this.sprite.scale.x = 1 * Math.sign(this.sprite.body.velocity.x);
            this.sprite.body.velocity.x = (this.sprite.body.velocity.x * 15);
            console.log("correndo: ",this.sprite.body.velocity.x);
        }
    }

    Player.prototype.groundCollision = function (playerSprite) {
        this.checkIsJumping();
    }

    Player.prototype.handleInputs = function () {
        if(this.leftButton.isDown){
            this.sprite.body.velocity.x = -150; // Ajustar velocidade
            // Se o jogador estiver virado para a direita, inverter a escala para que ele vire para o outro lado
            if(this.sprite.scale.x == 1) this.sprite.scale.x = -1;
            // Iniciando a animação 'walk'
            if(!this.isJumping) {
                this.sprite.animations.play('walk');
            }
        }

        // mover o sprite para a direita
        else if(this.rightButton.isDown){
            // se a tecla direita estiver pressionada
            this.sprite.body.velocity.x = 150;  // Ajustar velocidade
            // Se o jogador estiver virado para a direita, inverter a escala para que ele vire para o outro lado
            if(this.sprite.scale.x == -1) this.sprite.scale.x = 1;

            if(!this.isDoubleJumping) {
                this.sprite.animations.play('walk');
            }
        }
        else {
            // Ajustar velocidade para zero
            this.sprite.body.velocity.x = 0;

            if(!this.isJumping && !this.isDoubleJumping) {
                this.sprite.animations.play('idle');
            }

            if(!this.isDoubleJumping) {
                this.sprite.animations.play('');
            }
        }

        if (this.shotButton.isDown){
            this.fire();
        }
    }

    Player.prototype.checkGravity = function () {
        if(this.sprite.body.velocity.y >= 0 && this.isDoubleJumping) {
            this.sprite.body.gravity.y = this.fallingGravity;
        }
    }

    // Score
    Player.prototype.increaseScoreRatos = function () {
        //this.soundShot.stop();
        gameManager.globals.score = gameManager.globals.score + 50;
        gameManager.globals.scoreText.setText(gameManager.globals.score);
    }

    Player.prototype.increaseScoreEnemies = function () {
        //this.soundShot.stop();
        gameManager.globals.score = gameManager.globals.score + 100;
        gameManager.globals.scoreText.setText(gameManager.globals.score);
    }

    //Shot Bats
    Player.prototype.fire = function () {
        if (this.game.time.now > this.bulletTime) {
            this.bullet = this.bullets.getFirstExists(false);
            if (this.bullet) {
                this.bullet.reset(this.sprite.x, this.sprite.y);
                if (this.sprite.scale.x == 1) {
                    this.bullet.body.velocity.x = 300;
                    this.soundShot.play();
                    this.bullet.animations.play('shotBat');
                    this.bulletTime = this.game.time.now + 150;
                } else {
                    this.bullet.body.velocity.x = -300;
                    this.bullet.scale.x = -1;
                    this.soundShot.play()
                    this.bullet.animations.play('shotBat');
                    this.bulletTime = this.game.time.now + 150;
                }
            }
        }
    }

    Player.prototype.resetBullet = function(bullet) {
        this.soundShot.stop();
        bullet.kill();
    }
    gameManager.addSprite('player', Player);

})();
<|endoftext|>