<commit_before>// @flow

import React, { Component } from 'react';
import { View } from 'react-native';
import type { Dispatch } from 'redux';

import { ColorSchemeRegistry } from '../../../base/color-scheme';
import { openDialog } from '../../../base/dialog';
import { MEDIA_TYPE, VIDEO_TYPE, Audio } from '../../../base/media';
import {
    PARTICIPANT_ROLE,
    ParticipantView,
    getParticipantCount,
    isEveryoneModerator,
    pinParticipant
} from '../../../base/participants';
import { Container } from '../../../base/react';
import { connect } from '../../../base/redux';
import { StyleType } from '../../../base/styles';
import { getTrackByMediaTypeAndParticipant } from '../../../base/tracks';
import { ConnectionIndicator } from '../../../connection-indicator';
import { DisplayNameLabel } from '../../../display-name';
import { RemoteVideoMenu } from '../../../remote-video-menu';
import { toggleToolboxVisible } from '../../../toolbox';

import AudioMutedIndicator from './AudioMutedIndicator';
import DominantSpeakerIndicator from './DominantSpeakerIndicator';
import ModeratorIndicator from './ModeratorIndicator';
import RaisedHandIndicator from './RaisedHandIndicator';
import styles, { AVATAR_SIZE } from './styles';
import VideoMutedIndicator from './VideoMutedIndicator';

/**
 * Thumbnail component's property types.
 */
type Props = {

    /**
     * The Redux representation of the participant's audio track.
     */
    _audioTrack: Object,

    /**
     * The Redux representation of the state "features/large-video".
     */
    _largeVideo: Object,

    /**
     * Handles click/tap event on the thumbnail.
     */
    _onClick: ?Function,

    /**
     * Handles long press on the thumbnail.
     */
    _onShowRemoteVideoMenu: ?Function,

    /**
     * Whether to show the dominant speaker indicator or not.
     */
    _renderDominantSpeakerIndicator: boolean,

    /**
     * Whether to show the moderator indicator or not.
     */
    _renderModeratorIndicator: boolean,

    /**
     * The color-schemed stylesheet of the feature.
     */
    _styles: StyleType,

    /**
     * The Redux representation of the participant's video track.
     */
    _videoTrack: Object,

    /**
     * If true, there will be no color overlay (tint) on the thumbnail
     * indicating the participant associated with the thumbnail is displayed on
     * large video. By default there will be a tint.
     */
    disableTint?: boolean,

    /**
     * Invoked to trigger state changes in Redux.
     */
    dispatch: Dispatch<any>,

    /**
     * The Redux representation of the participant to display.
     */
    participant: Object,

    /**
     * Whether to display or hide the display name of the participant in the thumbnail.
     */
    renderDisplayName: ?boolean,

    /**
     * Optional styling to add or override on the Thumbnail component root.
     */
    styleOverrides?: Object,

    /**
     * If true, it tells the thumbnail that it needs to behave differently. E.g. react differently to a single tap.
     */
    tileView?: boolean
};

/**
 * React component for video thumbnail.
 *
 * @extends Component
 */
class Thumbnail extends Component<Props> {
    /**
     * Implements React's {@link Component#render()}.
     *
     * @inheritdoc
     * @returns {ReactElement}
     */
    render() {
        const {
            _audioTrack: audioTrack,
            _largeVideo: largeVideo,
            _onClick,
            _onShowRemoteVideoMenu,
            _renderDominantSpeakerIndicator: renderDominantSpeakerIndicator,
            _renderModeratorIndicator: renderModeratorIndicator,
            _styles,
            _videoTrack: videoTrack,
            disableTint,
            participant,
            renderDisplayName,
            tileView
        } = this.props;

        // We don't render audio in any of the following:
        // 1. The audio (source) is muted. There's no practical reason (that we
        //    know of, anyway) why we'd want to render it given that it's
        //    silence (& not even comfort noise).
        // 2. The audio is local. If we were to render local audio, the local
        //    participants would be hearing themselves.
        const audioMuted = !audioTrack || audioTrack.muted;
        const renderAudio = !audioMuted && !audioTrack.local;
        const participantId = participant.id;
        const participantInLargeVideo
            = participantId === largeVideo.participantId;
        const videoMuted = !videoTrack || videoTrack.muted;
        const isScreenShare = videoTrack && videoTrack.videoType === VIDEO_TYPE.DESKTOP;

        return (
            <Container
                onClick = { _onClick }
                onLongPress = { participant.local ? undefined : _onShowRemoteVideoMenu }
                style = { [
                    styles.thumbnail,
                    participant.pinned && !tileView
                        ? _styles.thumbnailPinned : null,
                    this.props.styleOverrides || null
                ] }
                touchFeedback = { false }>

                { renderAudio
                    && <Audio
                        stream
                            = { audioTrack.jitsiTrack.getOriginalStream() } /> }

                <ParticipantView
                    avatarSize = { AVATAR_SIZE }
                    disableVideo = { isScreenShare }
                    participantId = { participantId }
                    style = { _styles.participantViewStyle }
                    tintEnabled = { participantInLargeVideo && !disableTint }
                    tintStyle = { _styles.activeThumbnailTint }
                    zOrder = { 1 } />

                { renderDisplayName && <DisplayNameLabel participantId = { participantId } /> }

                { renderModeratorIndicator
                    && <View style = { styles.moderatorIndicatorContainer }>
                        <ModeratorIndicator />
                    </View> }

                <View
                    style = { [
                        styles.thumbnailTopIndicatorContainer,
                        styles.thumbnailTopLeftIndicatorContainer
                    ] }>
                    <RaisedHandIndicator participantId = { participant.id } />
                    { renderDominantSpeakerIndicator && <DominantSpeakerIndicator /> }
                </View>

                <View
                    style = { [
                        styles.thumbnailTopIndicatorContainer,
                        styles.thumbnailTopRightIndicatorContainer
                    ] }>
                    <ConnectionIndicator participantId = { participant.id } />
                </View>

                <Container style = { styles.thumbnailIndicatorContainer }>
                    { audioMuted
                        && <AudioMutedIndicator /> }

                    { videoMuted
                        && <VideoMutedIndicator /> }
                </Container>

            </Container>
        );
    }
}

/**
 * Maps part of redux actions to component's props.
 *
 * @param {Function} dispatch - Redux's {@code dispatch} function.
 * @param {Props} ownProps - The own props of the component.
 * @returns {{
 *     _onClick: Function,
 *     _onShowRemoteVideoMenu: Function
 * }}
 */
function _mapDispatchToProps(dispatch: Function, ownProps): Object {
    return {
        /**
         * Handles click/tap event on the thumbnail.
         *
         * @protected
         * @returns {void}
         */
        _onClick() {
            const { participant, tileView } = ownProps;

            if (tileView) {
                dispatch(toggleToolboxVisible());
            } else {
                dispatch(pinParticipant(participant.pinned ? null : participant.id));
            }
        },

        /**
         * Handles long press on the thumbnail.
         *
         * @returns {void}
         */
        _onShowRemoteVideoMenu() {
            const { participant } = ownProps;

            dispatch(openDialog(RemoteVideoMenu, {
                participant
            }));
        }
    };
}

/**
 * Function that maps parts of Redux state tree into component props.
 *
 * @param {Object} state - Redux state.
 * @param {Props} ownProps - Properties of component.
 * @returns {Object}
 */
function _mapStateToProps(state, ownProps) {
    // We need read-only access to the state of features/large-video so that the
    // filmstrip doesn't render the video of the participant who is rendered on
    // the stage i.e. as a large video.
    const largeVideo = state['features/large-video'];
    const tracks = state['features/base/tracks'];
    const { participant } = ownProps;
    const id = participant.id;
    const audioTrack
        = getTrackByMediaTypeAndParticipant(tracks, MEDIA_TYPE.AUDIO, id);
    const videoTrack
        = getTrackByMediaTypeAndParticipant(tracks, MEDIA_TYPE.VIDEO, id);
    const participantCount = getParticipantCount(state);
    const renderDominantSpeakerIndicator = participant.dominantSpeaker && participantCount > 2;
    const _isEveryoneModerator = isEveryoneModerator(state);
    const renderModeratorIndicator = !_isEveryoneModerator && participant.role === PARTICIPANT_ROLE.MODERATOR;

    return {
        _audioTrack: audioTrack,
        _largeVideo: largeVideo,
        _renderDominantSpeakerIndicator: renderDominantSpeakerIndicator,
        _renderModeratorIndicator: renderModeratorIndicator,
        _styles: ColorSchemeRegistry.get(state, 'Thumbnail'),
        _videoTrack: videoTrack
    };
}

export default connect(_mapStateToProps, _mapDispatchToProps)(Thumbnail);
<commit_msg>thumbnail: remove dead code<commit_after>// @flow

import React, { Component } from 'react';
import { View } from 'react-native';
import type { Dispatch } from 'redux';

import { ColorSchemeRegistry } from '../../../base/color-scheme';
import { openDialog } from '../../../base/dialog';
import { MEDIA_TYPE, VIDEO_TYPE } from '../../../base/media';
import {
    PARTICIPANT_ROLE,
    ParticipantView,
    getParticipantCount,
    isEveryoneModerator,
    pinParticipant
} from '../../../base/participants';
import { Container } from '../../../base/react';
import { connect } from '../../../base/redux';
import { StyleType } from '../../../base/styles';
import { getTrackByMediaTypeAndParticipant } from '../../../base/tracks';
import { ConnectionIndicator } from '../../../connection-indicator';
import { DisplayNameLabel } from '../../../display-name';
import { RemoteVideoMenu } from '../../../remote-video-menu';
import { toggleToolboxVisible } from '../../../toolbox';

import AudioMutedIndicator from './AudioMutedIndicator';
import DominantSpeakerIndicator from './DominantSpeakerIndicator';
import ModeratorIndicator from './ModeratorIndicator';
import RaisedHandIndicator from './RaisedHandIndicator';
import styles, { AVATAR_SIZE } from './styles';
import VideoMutedIndicator from './VideoMutedIndicator';

/**
 * Thumbnail component's property types.
 */
type Props = {

    /**
     * Whether local audio (microphone) is muted or not.
     */
    _audioMuted: boolean,

    /**
     * The Redux representation of the state "features/large-video".
     */
    _largeVideo: Object,

    /**
     * Handles click/tap event on the thumbnail.
     */
    _onClick: ?Function,

    /**
     * Handles long press on the thumbnail.
     */
    _onShowRemoteVideoMenu: ?Function,

    /**
     * Whether to show the dominant speaker indicator or not.
     */
    _renderDominantSpeakerIndicator: boolean,

    /**
     * Whether to show the moderator indicator or not.
     */
    _renderModeratorIndicator: boolean,

    /**
     * The color-schemed stylesheet of the feature.
     */
    _styles: StyleType,

    /**
     * The Redux representation of the participant's video track.
     */
    _videoTrack: Object,

    /**
     * If true, there will be no color overlay (tint) on the thumbnail
     * indicating the participant associated with the thumbnail is displayed on
     * large video. By default there will be a tint.
     */
    disableTint?: boolean,

    /**
     * Invoked to trigger state changes in Redux.
     */
    dispatch: Dispatch<any>,

    /**
     * The Redux representation of the participant to display.
     */
    participant: Object,

    /**
     * Whether to display or hide the display name of the participant in the thumbnail.
     */
    renderDisplayName: ?boolean,

    /**
     * Optional styling to add or override on the Thumbnail component root.
     */
    styleOverrides?: Object,

    /**
     * If true, it tells the thumbnail that it needs to behave differently. E.g. react differently to a single tap.
     */
    tileView?: boolean
};

/**
 * React component for video thumbnail.
 *
 * @extends Component
 */
class Thumbnail extends Component<Props> {
    /**
     * Implements React's {@link Component#render()}.
     *
     * @inheritdoc
     * @returns {ReactElement}
     */
    render() {
        const {
            _audioMuted: audioMuted,
            _largeVideo: largeVideo,
            _onClick,
            _onShowRemoteVideoMenu,
            _renderDominantSpeakerIndicator: renderDominantSpeakerIndicator,
            _renderModeratorIndicator: renderModeratorIndicator,
            _styles,
            _videoTrack: videoTrack,
            disableTint,
            participant,
            renderDisplayName,
            tileView
        } = this.props;

        const participantId = participant.id;
        const participantInLargeVideo
            = participantId === largeVideo.participantId;
        const videoMuted = !videoTrack || videoTrack.muted;
        const isScreenShare = videoTrack && videoTrack.videoType === VIDEO_TYPE.DESKTOP;

        return (
            <Container
                onClick = { _onClick }
                onLongPress = { participant.local ? undefined : _onShowRemoteVideoMenu }
                style = { [
                    styles.thumbnail,
                    participant.pinned && !tileView
                        ? _styles.thumbnailPinned : null,
                    this.props.styleOverrides || null
                ] }
                touchFeedback = { false }>

                <ParticipantView
                    avatarSize = { AVATAR_SIZE }
                    disableVideo = { isScreenShare }
                    participantId = { participantId }
                    style = { _styles.participantViewStyle }
                    tintEnabled = { participantInLargeVideo && !disableTint }
                    tintStyle = { _styles.activeThumbnailTint }
                    zOrder = { 1 } />

                { renderDisplayName && <DisplayNameLabel participantId = { participantId } /> }

                { renderModeratorIndicator
                    && <View style = { styles.moderatorIndicatorContainer }>
                        <ModeratorIndicator />
                    </View> }

                <View
                    style = { [
                        styles.thumbnailTopIndicatorContainer,
                        styles.thumbnailTopLeftIndicatorContainer
                    ] }>
                    <RaisedHandIndicator participantId = { participant.id } />
                    { renderDominantSpeakerIndicator && <DominantSpeakerIndicator /> }
                </View>

                <View
                    style = { [
                        styles.thumbnailTopIndicatorContainer,
                        styles.thumbnailTopRightIndicatorContainer
                    ] }>
                    <ConnectionIndicator participantId = { participant.id } />
                </View>

                <Container style = { styles.thumbnailIndicatorContainer }>
                    { audioMuted
                        && <AudioMutedIndicator /> }

                    { videoMuted
                        && <VideoMutedIndicator /> }
                </Container>

            </Container>
        );
    }
}

/**
 * Maps part of redux actions to component's props.
 *
 * @param {Function} dispatch - Redux's {@code dispatch} function.
 * @param {Props} ownProps - The own props of the component.
 * @returns {{
 *     _onClick: Function,
 *     _onShowRemoteVideoMenu: Function
 * }}
 */
function _mapDispatchToProps(dispatch: Function, ownProps): Object {
    return {
        /**
         * Handles click/tap event on the thumbnail.
         *
         * @protected
         * @returns {void}
         */
        _onClick() {
            const { participant, tileView } = ownProps;

            if (tileView) {
                dispatch(toggleToolboxVisible());
            } else {
                dispatch(pinParticipant(participant.pinned ? null : participant.id));
            }
        },

        /**
         * Handles long press on the thumbnail.
         *
         * @returns {void}
         */
        _onShowRemoteVideoMenu() {
            const { participant } = ownProps;

            dispatch(openDialog(RemoteVideoMenu, {
                participant
            }));
        }
    };
}

/**
 * Function that maps parts of Redux state tree into component props.
 *
 * @param {Object} state - Redux state.
 * @param {Props} ownProps - Properties of component.
 * @returns {Object}
 */
function _mapStateToProps(state, ownProps) {
    // We need read-only access to the state of features/large-video so that the
    // filmstrip doesn't render the video of the participant who is rendered on
    // the stage i.e. as a large video.
    const largeVideo = state['features/large-video'];
    const tracks = state['features/base/tracks'];
    const { participant } = ownProps;
    const id = participant.id;
    const audioTrack
        = getTrackByMediaTypeAndParticipant(tracks, MEDIA_TYPE.AUDIO, id);
    const videoTrack
        = getTrackByMediaTypeAndParticipant(tracks, MEDIA_TYPE.VIDEO, id);
    const participantCount = getParticipantCount(state);
    const renderDominantSpeakerIndicator = participant.dominantSpeaker && participantCount > 2;
    const _isEveryoneModerator = isEveryoneModerator(state);
    const renderModeratorIndicator = !_isEveryoneModerator && participant.role === PARTICIPANT_ROLE.MODERATOR;

    return {
        _audioMuted: audioTrack?.muted ?? true,
        _largeVideo: largeVideo,
        _renderDominantSpeakerIndicator: renderDominantSpeakerIndicator,
        _renderModeratorIndicator: renderModeratorIndicator,
        _styles: ColorSchemeRegistry.get(state, 'Thumbnail'),
        _videoTrack: videoTrack
    };
}

export default connect(_mapStateToProps, _mapDispatchToProps)(Thumbnail);
<|endoftext|>


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

  // event trigger for search filters
  angular.module('cla.directives')
    .directive('searchFilter', ['postal', function (postal) {
      return {
        restrict: 'A',
        link: function(scope, elem) {
          elem.on('blur', function () {
            if (elem.val() !== '') {
              var lbl = elem.attr('name');
              postal.publish({channel: 'SearchFilter', topic: 'search', data: {label: lbl}});
            }
          });
        }
      };
    }]);
})();
<commit_msg>Prevent text search filters submitting forms on enter<commit_after>(function(){
  'use strict';

  // event trigger for search filters
  angular.module('cla.directives')
    .directive('searchFilter', ['postal', function (postal) {
      return {
        restrict: 'A',
        link: function(scope, elem) {
          elem
            .on('blur', function () {
              if (elem.val() !== '') {
                var lbl = elem.attr('name');
                postal.publish({channel: 'SearchFilter', topic: 'search', data: {label: lbl}});
              }
            })
            .on('keydown keypress', function (event) {
              if (event.which === 13) {
                event.preventDefault();
              }
            });
        }
      };
    }]);
})();
<|endoftext|>


<commit_before>/*
 * XDSMjs
 * Copyright 2016 Rémi Lafage
 */
"use strict";

var d3 = require('d3');
var Graph = require('./src/graph');
var Xdsm = require('./src/xdsm');
var Animation = require('./src/animation');
var Controls = require('./src/controls');

d3.json("xdsm.json", function(error, mdo) {
  if (error) {
    throw error;
  }

  // Tooltip for variable connexions
  var tooltip = d3.select("body").selectAll(".tooltip").data(['tooltip'])
                  .enter().append("div")
                .attr("class", "tooltip")
                .style("opacity", 0);

  var scenarioKeys = Object.keys(mdo).sort();

  // Optimization problem display setup
  /* eslint-disable brace-style */
  d3.select("body").selectAll("optpb")
                .data(scenarioKeys)
              .enter()
                .append("div")
                .filter(function(d) { return mdo[d].optpb; })
                  .attr("class", function(d) { return "optpb " + d; })
                  .style("opacity", 0)
                  .on("click", function() {
                    d3.select(this).transition().duration(500)
                      .style("opacity", 0)
                      .style("pointer-events", "none");
                  }).append("pre").text(function(d) { return mdo[d].optpb; });
  /* eslint-enable brace-style */

  var xdsms = {};

  if (scenarioKeys.indexOf('root') === -1) {
    // old format: mono xdsm
    var graph = new Graph(mdo);
    xdsms.root = new Xdsm(graph, 'root', tooltip);
    xdsms.root.draw();
  } else {
    // new format managing several XDSM
    scenarioKeys.forEach(function(k) {
      if (mdo.hasOwnProperty(k)) {
        var graph = new Graph(mdo[k], k);
        xdsms[k] = new Xdsm(graph, k, tooltip);
        xdsms[k].draw();
        xdsms[k].svg.select(".optimization").on("click", function() {
          var info = d3.select(".optpb." + k);
          info.style("opacity", 0.9);
          info.style("left", (d3.event.pageX) + "px")
            .style("top", (d3.event.pageY - 28) + "px");
          info.style("pointer-events", "auto");
        });
      }
    }, this);
  }

  var ctrls = new Controls(new Animation(xdsms)); // eslint-disable-line no-unused-vars

  var addButton = d3.select('button#add');
  addButton.on('click', function() {
    xdsms.root.addNode("Discipline");
  });
  var delButton = d3.select('button#del');
  delButton.on('click', function() {
    xdsms.root.removeNode();
  });
});

<commit_msg>check for workflow presence<commit_after>/*
 * XDSMjs
 * Copyright 2016 Rémi Lafage
 */
"use strict";

var d3 = require('d3');
var Graph = require('./src/graph');
var Xdsm = require('./src/xdsm');
var Animation = require('./src/animation');
var Controls = require('./src/controls');

d3.json("xdsm.json", function(error, mdo) {
  if (error) {
    throw error;
  }

  // Tooltip for variable connexions
  var tooltip = d3.select("body").selectAll(".tooltip").data(['tooltip'])
                  .enter().append("div")
                .attr("class", "tooltip")
                .style("opacity", 0);

  var scenarioKeys = Object.keys(mdo).sort();

  // Optimization problem display setup
  d3.select("body").selectAll("optpb")
                .data(scenarioKeys)
              .enter()
                .append("div")
                .filter(function(d) { return mdo[d].optpb; })
                  .attr("class", function(d) { return "optpb " + d; })
                  .style("opacity", 0)
                  .on("click", function() {
                    d3.select(this).transition().duration(500)
                      .style("opacity", 0)
                      .style("pointer-events", "none");
                  }).append("pre").text(function(d) { return mdo[d].optpb; });

  var xdsms = {};

  if (scenarioKeys.indexOf('root') === -1) {
    // old format: mono xdsm
    var graph = new Graph(mdo);
    xdsms.root = new Xdsm(graph, 'root', tooltip);
    xdsms.root.draw();
  } else {
    // new format managing several XDSM
    scenarioKeys.forEach(function(k) {
      if (mdo.hasOwnProperty(k)) {
        var graph = new Graph(mdo[k], k);
        xdsms[k] = new Xdsm(graph, k, tooltip);
        xdsms[k].draw();
        xdsms[k].svg.select(".optimization").on("click", function() {
          var info = d3.select(".optpb." + k);
          info.style("opacity", 0.9);
          info.style("left", (d3.event.pageX) + "px")
            .style("top", (d3.event.pageY - 28) + "px");
          info.style("pointer-events", "auto");
        });
      }
    }, this);
  }

  if (mdo.workflow && mdo.workflow.length !== 0) {  // workflow is optional
    var ctrls = new Controls(new Animation(xdsms)); // eslint-disable-line no-unused-vars
  }

  var addButton = d3.select('button#add');
  addButton.on('click', function() {
    xdsms.root.addNode("Discipline");
  });
  var delButton = d3.select('button#del');
  delButton.on('click', function() {
    xdsms.root.removeNode();
  });
});

<|endoftext|>


<commit_before>FOAModel({
  name: 'CViewView',
  extendsModel: 'View',

  properties: [
    {
      name: 'cview',
      postSet: function(_, cview) {
        cview.view = this;
        cview.x$.addListener(this.resize);
        cview.y$.addListener(this.resizeP);
        cview.width$.addListener(this.resize);
        cview.height$.addListener(this.resize);
        this.resize();
      }
    },
    {
      name:  'width',
      type:  'int',
      defaultValue: 100,
      postSet: function(_, width) {
        if ( this.$ ) this.$.width = width;
      }
    },
    {
      name:  'height',
      type:  'int',
      defaultValue: 100,
      postSet: function(_, height) {
        if ( this.$ ) this.$.height = height;
      }
    },
    {
      name: 'canvas',
      getter: function() { return this.$ && this.$.getContext('2d'); }
    }
  ],

  listeners: [
    {
      name: 'resize',
      isAnimated: true,
      code: function() {
        this.width  = this.cview.x + this.cview.width;
        this.height = this.cview.y + this.cview.height;
      }
    },
    {
      name: 'paint',
      isAnimated: true,
      code: function() {
        if ( ! this.$ ) throw EventService.UNSUBSCRIBE_EXCEPTION;
        this.canvas.save();
        this.cview.paint();
        this.canvas.restore();
      }
    }
  ],

  methods: {
    toHTML: function() {
      return '<canvas id="' + this.id + '" width="' + this.width + '" height="' + this.height + '"> </canvas>';
    },

    initHTML: function() {
      if ( ! this.$ ) return;
      this.canvas = this.$.getContext('2d');
    }
  }
});

// Should CViews' have a cparent?
FOAModel({
  name:  'CView2',
  label: 'CView2',

  properties: [
    {
      name:  'view',
      type:  'Canvas2',
      hidden: true
    },
    {
      name:  'canvas',
      getter: function() { return this.view && this.view.canvas; },
      hidden: true
    },
    {
      name:  '$',
      getter: function() { return this.view && this.view.$; },
      hidden: true
    },
    {
      name:  'x',
      type:  'int',
      view:  'IntFieldView',
      defaultValue: 10
    },
    {
      name:  'y',
      type:  'int',
      view:  'IntFieldView',
      defaultValue: 10
    },
    {
      name:  'width',
      type:  'int',
      view:  'IntFieldView',
      defaultValue: 10
    },
    {
      name:  'height',
      type:  'int',
      view:  'IntFieldView',
      defaultValue: 10
    },
    {
      name:  'children',
      type:  'CView[]',
      factory: function() { return []; },
      hidden: true
    },
    {
      name:  'alpha',
      type:  'int',
      defaultValue: 1
    },
    {
      name:  'color',
      label: 'Foreground Color',
      type:  'String',
      defaultValue: 'black'
    },
    {
      name:  'background',
      label: 'Background Color',
      type:  'String',
      defaultValue: 'white'
    },
    {
      name: 'font'
    }
  ],

  methods: {
    toView: function() { return this.X.CViewView.create({cview: this}); },

    write: function(document) {
      var v = this.toView();
      document.writeln(v.toHTML());
      v.initHTML();
    },

    addChild: function(child) {
      this.children.push(child);
      child.view = this.view;
      child.addListener(this.view.paint);
      // child.parent = this;
      return this;
    },

    removeChild: function(child) {
      this.children.deleteI(child);
      child.view = undefined;
      child.removeListener(this.view.paint);
      // child.parent = undefined;
      return this;
    },

    erase: function() {
      this.canvas.fillStyle = this.background;
      this.canvas.fillRect(0, 0, this.width, this.height);
    },

    paintChildren: function() {
      for ( var i = 0 ; i < this.children.length ; i++ ) {
        var child = this.children[i];
        this.canvas.save();
        child.paint();
        this.canvas.restore();
      }
    },

    paintSelf: function() {},

    paint: function() {
      if ( ! this.$ ) return;
      this.erase();
      this.paintSelf();
      this.paintChildren();
    }
  }
});

FOAModel({
  name:  'Circle2',

  extendsModel: 'CView2',

  properties: [
    {
      name:  'border',
      label: 'Border Color',
      type:  'String',
      defaultValue: undefined
    },
    {
      name:  'borderWidth',
      type:  'int',
      defaultValue: 1
    },
    {
      name: 'r',
      label: 'Radius',
      type: 'int',
      defaultValue: 20
    }
  ],

  methods: {

    paint: function() {
      var c = this.canvas;

      c.globalAlpha = this.alpha;

      if ( this.border && this.r ) {
        c.lineWidth = this.borderWidth;
        c.strokeStyle = this.border;
        c.beginPath();
        c.arc(this.x, this.y, this.r, 0, Math.PI*2, true);
        c.closePath();
        c.stroke();
      }

      if ( this.color ) {
        c.fillStyle = this.color;

        c.beginPath();
        c.arc(this.x, this.y, this.r, 0, Math.PI*2, true);
        c.closePath();
        c.fill();
      }
    }
  }
});
<commit_msg>Initial check-in of ActionButtonCView.<commit_after>FOAModel({
  name: 'CViewView',
  extendsModel: 'View',

  properties: [
    {
      name: 'cview',
      postSet: function(_, cview) {
        cview.view = this;
        cview.x$.addListener(this.resize);
        cview.y$.addListener(this.resizeP);
        cview.width$.addListener(this.resize);
        cview.height$.addListener(this.resize);
        this.resize();
      }
    },
    {
      name:  'width',
      type:  'int',
      defaultValue: 100,
      postSet: function(_, width) {
        if ( this.$ ) this.$.width = width;
      }
    },
    {
      name:  'height',
      type:  'int',
      defaultValue: 100,
      postSet: function(_, height) {
        if ( this.$ ) this.$.height = height;
      }
    },
    {
      name: 'canvas',
      getter: function() { return this.$ && this.$.getContext('2d'); }
    }
  ],

  listeners: [
    {
      name: 'resize',
      isAnimated: true,
      code: function() {
        this.width  = this.cview.x + this.cview.width;
        this.height = this.cview.y + this.cview.height;
      }
    },
    {
      name: 'paint',
      isAnimated: true,
      code: function() {
        if ( ! this.$ ) throw EventService.UNSUBSCRIBE_EXCEPTION;
        this.canvas.save();
        this.cview.paint();
        this.canvas.restore();
      }
    }
  ],

  methods: {
    toHTML: function() {
      return '<canvas id="' + this.id + '" width="' + this.width + '" height="' + this.height + '"> </canvas>';
    },

    initHTML: function() {
      if ( ! this.$ ) return;
      this.canvas = this.$.getContext('2d');
      this.paint();
    }
  }
});

// Should CViews' have a cparent?
FOAModel({
  name:  'CView2',
  label: 'CView2',

  properties: [
    {
      name:  'view',
      type:  'Canvas2',
      hidden: true
    },
    {
      name:  'canvas',
      getter: function() { return this.view && this.view.canvas; },
      hidden: true
    },
    {
      name:  '$',
      getter: function() { return this.view && this.view.$; },
      hidden: true
    },
    {
      name:  'x',
      type:  'int',
      view:  'IntFieldView',
      defaultValue: 10
    },
    {
      name:  'y',
      type:  'int',
      view:  'IntFieldView',
      defaultValue: 10
    },
    {
      name:  'width',
      type:  'int',
      view:  'IntFieldView',
      defaultValue: 10
    },
    {
      name:  'height',
      type:  'int',
      view:  'IntFieldView',
      defaultValue: 10
    },
    {
      name:  'children',
      type:  'CView[]',
      factory: function() { return []; },
      hidden: true
    },
    {
      name:  'alpha',
      type:  'int',
      defaultValue: 1
    },
    {
      name:  'color',
      label: 'Foreground Color',
      type:  'String',
      defaultValue: 'black'
    },
    {
      name:  'background',
      label: 'Background Color',
      type:  'String',
      defaultValue: 'white'
    },
    {
      name: 'font'
    }
  ],

  methods: {
    toView: function() { return this.view || this.X.CViewView.create({cview: this}); },

    write: function(document) {
      var v = this.toView();
      document.writeln(v.toHTML());
      v.initHTML();
    },

    addChild: function(child) {
      this.children.push(child);
      child.view = this.view;
      child.addListener(this.view.paint);
      // child.parent = this;
      return this;
    },

    removeChild: function(child) {
      this.children.deleteI(child);
      child.view = undefined;
      child.removeListener(this.view.paint);
      // child.parent = undefined;
      return this;
    },

    erase: function() {
      this.canvas.fillStyle = this.background;
      this.canvas.fillRect(0, 0, this.width, this.height);
    },

    paintChildren: function() {
      for ( var i = 0 ; i < this.children.length ; i++ ) {
        var child = this.children[i];
        this.canvas.save();
        child.paint();
        this.canvas.restore();
      }
    },

    paintSelf: function() {},

    paint: function() {
      if ( ! this.$ ) return;
      this.erase();
      this.paintSelf();
      this.paintChildren();
    }
  }
});

FOAModel({
  name:  'Circle2',

  extendsModel: 'CView2',

  properties: [
    {
      name:  'border',
      label: 'Border Color',
      type:  'String',
      defaultValue: undefined
    },
    {
      name:  'borderWidth',
      type:  'int',
      defaultValue: 1
    },
    {
      name: 'r',
      label: 'Radius',
      type: 'int',
      defaultValue: 20
    }
  ],

  methods: {

    paint: function() {
      var c = this.canvas;

      c.globalAlpha = this.alpha;

      if ( this.border && this.r ) {
        c.lineWidth = this.borderWidth;
        c.strokeStyle = this.border;
        c.beginPath();
        c.arc(this.x, this.y, this.r, 0, Math.PI*2, true);
        c.closePath();
        c.stroke();
      }

      if ( this.color ) {
        c.fillStyle = this.color;

        c.beginPath();
        c.arc(this.x, this.y, this.r, 0, Math.PI*2, true);
        c.closePath();
        c.fill();
      }
    }
  }
});

FOAModel({
  name: 'ActionButtonCView',

  extendsModel: 'CView2',

  properties: [
    {
      name: 'action',
      postSet: function(oldValue, action) {
        //  oldValue && oldValue.removeListener(this.render)
        // action.addListener(this.render);
      }
    },
    {
      name: 'data',
      setter: function(_, d) { this.value = SimpleValue.create(d); }
    },
    {
      name:  'font',
      type:  'String',
      defaultValue: ''
    },
    {
      name: 'value',
      type: 'Value',
      factory: function() { return SimpleValue.create(); }
    },
    {
      name: 'showLabel',
      defaultValueFn: function() { return this.action.showLabel; }
    },
    {
      name: 'iconUrl',
      defaultValueFn: function() { return this.action.iconUrl; }
    }
  ],

  listeners: [
    {
      name: 'fooBar',
      isAnimated: true,
      code: function() {  }
    }
  ],

  methods: {
    paintSelf: function() {
      var self = this;
      var canvas = this.canvas;

      var oldFont = canvas.font;
      var oldAlign = canvas.textAlign;

      if ( this.font ) canvas.font = this.font;

      canvas.textAlign = 'center';
      canvas.textBaseline = 'middle';
      canvas.fillStyle = this.color;
      canvas.fillText(this.action.labelFn.call(this.value, this.action), this.x+this.width/2, this.y+this.height/2);

      canvas.font = oldFont;
      canvas.textAlign = oldAlign;

      /*
      this.on('click', function() {
        self.action.callIfEnabled(self.value.get());
      }, this.id);

      this.setAttribute('data-tip', function() {
        return self.action.help || undefined;
      }, this.id);

      this.setAttribute('disabled', function() {
        var value = self.value.get();
        return self.action.isEnabled.call(value, self.action) ? undefined : 'disabled';
      }, this.id);

      this.X.dynamic(function() { self.action.labelFn.call(value, self.action); self.updateHTML(); });
      */
    },

    foo: function() {
      var out = '';

      if ( this.iconUrl ) {
        out += '<img src="' + XMLUtil.escapeAttr(this.action.iconUrl) + '">';
      }

      if ( this.showLabel ) {
        var value = this.value.get();
        out += value ? this.action.labelFn.call(value, this.action) : this.action.label;
      }

      return out;
    }
  }
});
<|endoftext|>


<commit_before>"use strict";

const test     = require('tape');

const lapi     = require("../src/lapi.js");
const lauxlib  = require("../src/lauxlib.js");
const lua      = require('../src/lua.js');
const linit    = require('../src/linit.js');

test('constructs.lua', function (t) {
    let luaCode = `
        return dofile("tests/lua-tests/constructs.lua")
    `, L;

    t.plan(1);

    t.doesNotThrow(function () {

        L = lauxlib.luaL_newstate();

        linit.luaL_openlibs(L);

        lauxlib.luaL_loadstring(L, lua.to_luastring(luaCode));

    }, "Lua program loaded without error");

    // t.doesNotThrow(function () {

        lapi.lua_call(L, 0, -1);

    // }, "Lua program ran without error");

});

test('strings.lua', function (t) {
    let luaCode = `
        return dofile("tests/lua-tests/strings.lua")
    `, L;

    t.plan(2);

    t.doesNotThrow(function () {

        L = lauxlib.luaL_newstate();

        linit.luaL_openlibs(L);

        lauxlib.luaL_loadstring(L, lua.to_luastring(luaCode));

    }, "Lua program loaded without error");

    t.doesNotThrow(function () {

        lapi.lua_call(L, 0, -1);

    }, "Lua program ran without error");

});
<commit_msg>Temp require to run constructs.lua<commit_after>"use strict";

const test     = require('tape');

const lapi     = require("../src/lapi.js");
const lauxlib  = require("../src/lauxlib.js");
const lua      = require('../src/lua.js');
const linit    = require('../src/linit.js');

test('constructs.lua', function (t) {
    let luaCode = `
        _soft = true
        require = function(lib) return _G[lib] end  -- NYI
        return dofile("tests/lua-tests/constructs.lua")
    `, L;

    t.plan(1);

    t.doesNotThrow(function () {

        L = lauxlib.luaL_newstate();

        linit.luaL_openlibs(L);

        lauxlib.luaL_loadstring(L, lua.to_luastring(luaCode));

    }, "Lua program loaded without error");

    // t.doesNotThrow(function () {

        lapi.lua_call(L, 0, -1);

    // }, "Lua program ran without error");

});

test('strings.lua', function (t) {
    let luaCode = `
        return dofile("tests/lua-tests/strings.lua")
    `, L;

    t.plan(2);

    t.doesNotThrow(function () {

        L = lauxlib.luaL_newstate();

        linit.luaL_openlibs(L);

        lauxlib.luaL_loadstring(L, lua.to_luastring(luaCode));

    }, "Lua program loaded without error");

    t.doesNotThrow(function () {

        lapi.lua_call(L, 0, -1);

    }, "Lua program ran without error");

});
<|endoftext|>


<commit_before>countInversions.js
<commit_msg>add desc<commit_after>// Count Inversions in an array.

// Inversion Count for an array indicates – how far (or close) the array is from being sorted.
// If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum.
// Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j

// Example:
// The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3).
<|endoftext|>


<commit_before>const postcss = require('postcss');
const bemLinter = require('postcss-bem-linter');
const reporter = require('postcss-reporter');

module.exports = {
  use: [
    "postcss-import",
    "postcss-calc",
    "postcss-custom-media",
    "autoprefixer",
    "postcss-reporter"
  ],
  "postcss-import": {
    transform(css) {
      return postcss([bemLinter, reporter]).process(css).css;
    }
  },
  "postcss-reporter": {
    clearMessages: true
  }
};
<commit_msg>Remove unused build file<commit_after><|endoftext|>


<commit_before>"use strict";
/*jslint vars: true, plusplus: true, devel: true, nomen: true*/
/*global define */

var game_state = {};
var USER_INPUT_ALLOWED = true;

function a_execute() {
    if (game_state.options.a === "Play again.") {
        request_initial_world();
    } else {
        request_outcome_of_action(game_state.options.a);
    }
}

function a_or_an(next_letter) {
    if (next_letter === "a" ||
        next_letter === "e" ||
        next_letter === "i" ||
        next_letter === "o" ||
        next_letter === "u") {
        return "an";
    }
    return "a";
}

function set_alt_option_name(letter, option, alternate) {
    if (game_state.action === option) {
        $("#" + letter).text(letter + ". " + alternate);
    } else {
        $("#" + letter).text(letter + ". " + option);
    }
}

function b_execute() {
    if (game_state.options.b === "Don't play again.") {
        window.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
    } else {
        request_outcome_of_action(game_state.options.b);
    }
}

function bind_keys() {
    document.onkeypress = function(event) {
        var ascii = event.which;
        if ((ascii == 49 || ascii == 65 || ascii == 97) &&
            USER_INPUT_ALLOWED) {
            a_execute();
        } else if ((ascii == 50 || ascii == 66 || ascii == 98) &&
                   USER_INPUT_ALLOWED) {
            b_execute();
        } else if ((ascii == 51 || ascii == 67 || ascii == 99) &&
                   USER_INPUT_ALLOWED &&
                   game_state.options.c !== "") {
            execute("c");
        } else if ((ascii == 52 || ascii == 68 || ascii == 100) &&
                   USER_INPUT_ALLOWED &&
                   game_state.options.d !== "") {
            execute("d");
        } else if ((ascii == 53 || ascii == 69 || ascii == 101) &&
                   USER_INPUT_ALLOWED &&
                   game_state.options.e !== "") {
            execute("e");
        }
    };
}

function execute(letter) {
    request_outcome_of_action(game_state.options[letter]);
}

function get_ground(game_state) {
    switch (game_state.character.place) {
        case "pirate_ship":
            return "deck";
        case "docks":
            return "docks";
    }
    if (game_state.places[game_state.character.place].outside === false) {
        return "floor";
    } else {
        return "ground";
    }
}

function get_person_name(game_state) {
    return game_state.persons[game_state.character.person].name;
}

function get_place_name(game_state) {
    return game_state.places[game_state.character.place].name;
}

function handle_new_world(resp) {
    if (resp.message === "error") {
        handle_world_error(game_state);
    } else {
        game_state = resp;

        if (game_state.character.is_dead) {
            game_state.message += " You are dead.";
        }

        set_message(game_state);
        set_a(game_state);
        set_b(game_state);
        set_c(game_state);
        set_d(game_state);
        set_e(game_state);
        $("#score").text("Score: " + game_state.score);

        if (parseInt(game_state.score) === 0) {
        // we only need to bind the keys if this is the first frame of the game
        // and the player has a score of 0 at the first frame of the game

        // I am binding the keys at the end of the handle_new_world function
        // to prevent the client from being able to make a bad server request
        // before the server has given the client the initial game state
            bind_keys();
        }
    }
    USER_INPUT_ALLOWED = true; // re-allow user inputs now that we have a new
                               // game state
}

function handle_world_error(game_state) {
    $("#message").text("The universe rips apart, because an error occured on the server. Please email sberg@uoregon.edu about what you were doing in the game when the error ocurred or raise an issue at https://github.com/SageBerg/St.GeorgeGame/issues/. I'll try to fix the issue ASAP.");
    $("#a").text("Play again.");
    $("#b").text("Don't play again.");
    $("#c").text("");
    $("#d").text("");
    $("#e").text("");
    game_state.options.a = "Play again.";
    game_state.options.b = "Don't play again.";
    game_state.options.c = "";
    game_state.options.d = "";
    game_state.options.e = "";
}

function random_choice(array) {
    return array[random_int(array.length)];
}

function random_int(n) {
    return Math.floor(Math.random() * n);
}

function request_initial_world() {
    $.get("request_initial_world.json", {}, handle_new_world);
}

function request_outcome_of_action(action) {
    game_state.action = action;
    USER_INPUT_ALLOWED = false;
    $.get("request_outcome_of_action.json",
           game_state,
           handle_new_world);
}

// CREDITS: function based on top answer by community wiki at:
// http://stackoverflow.com/questions/2450954/
//        how-to-randomize-shuffle-a-javascript-array
function scramble(text) {
    text = text.replace(/\./g, "");
    text = text.replace(/,/g, "");
    text = text.replace(/\?/g, "");
    text = text.replace(/!/g, "");
    text = text.replace(/"/g, "");

    text = text.toLowerCase();
    var array = text.split(" ");
    var current_index = array.length, temporary_value, random_index ;

    while (0 !== current_index) {
        random_index = Math.floor(Math.random() * current_index);
        current_index -= 1;
        temporary_value = array[current_index];
        array[current_index] = array[random_index];
        array[random_index] = temporary_value;
    }

    var return_text = "";
    for (var i = 0; i < array.length; i++) {
        return_text += array[i] + " ";
    }

    return return_text;
}

function set_a(game_state) {
    switch (game_state.options.a) {
        case "ATTACK":
            $("#a").text("a. Attack " + get_person_name(game_state) + ".");
            break;

        case "GIVE_HER_CAT":
            var cat = "your cat";
            if (game_state.character.items.cat > 1) {
                cat = "one of your cats";
            }
            $("#a").text("a. Give " + get_person_name(game_state) + cat + ".");
            break;

        case "Go flower picking.":
            set_alt_option_name("a", "Go flower picking.",
                                "Go flower picking again.");
            break;

        case "LICK_THE_GROUND":
            $("#a").text("a. Lick the " + get_ground(game_state) + ".");
            break;

        case "MARRY":
            $("#a").text("a. Marry " + get_person_name(game_state) + ".");
            break;

        case "Think.":
            set_alt_option_name("a", "Think.", "Think some more.");
            break;

        case "YELL_A_PIRATE_PHRASE":
            $("#a").text("a. Yell, \"" +
                random_choice([
                    "Ahoy",
                    "All hands on deck",
                    "Arr Matey",
                    "Avast",
                    "Aye Aye",
                    "Dead men tell no tales",
                    "Hoist the Jolly Roger",
                    "Land ho",
                    "Send 'em to Davy Jones' locker",
                    "Shiver me timbers",
                    "Thare she blows",
                    "Walk the plank",
                    "X marks the spot",
                    "Yo, ho, ho, and a bottle of rum",
                ]) + "!\"");
            break;

        default:
            $("#a").text("a. " + game_state.options.a);
    }
}

function set_b(game_state) {
    switch (game_state.options.b) {
        case "BURN":
            $("#b").text("b. Burn " +  get_place_name(game_state) +
                " to the ground.");
            break;

        case "Buy a drink.":
            set_alt_option_name("b", "Buy a drink.", "Buy another drink.");
            break;

        case "BUY_ITEM":
            var item = game_state.for_sell;
            $("#b").text("b. Buy " +
                a_or_an(item[0]) + " " + item + ".");
            break;

        case "GIVE_FLOWERS":
            if (game_state.character.place === "prison") {
                if (game_state.persons.felicity.name === "the fat lady") {
                    $("#b").text("b. Give the fat lady who feeds you a " +
                        "bouquet of flowers.");
                } else {
                    $("#b").text("b. Give Felicity your bouquet of flowers.");
                }
            } else {
                $("#b").text("b. Give her your bouquet of flowers.");
            }
            break;

        case "LOVE_POTION":
            $("#b").text("b. Use your love potion on " +
                get_person_name(game_state) + ".");
            break;

        case "Pray to a higher power.":
            set_alt_option_name("b", "Pray to a higher power.",
                                "Continue praying.");
            break;

        case "SHOW_COIN":
            $("#b").text("b. Show " + get_person_name(game_state) +
                " your shiny foreign coin.");
            break;

        case "SUCK_UP":
            $("#b").text("b. Suck up to " + get_person_name(game_state) + ".");
            break;

        default:
            $("#b").text("b. " + game_state.options.b);
    }
}

function set_c(game_state) {
    if (game_state.options.c !== "") {
        switch (game_state.options.c) {

            case "Go to sleep.":
                set_alt_option_name("c", "Go to sleep.", "Go back to sleep.");
                break;

            case "GO_TO":
                var dest = game_state.destination;
                if (game_state.character.items.donkey > 0) {
                    $("#c").text("c. Ride your donkey to " +
                        game_state.places[dest].name + ".");
                } else {
                    $("#c").text("c. Go to " + game_state.places[dest].name +
                        ".");
                }
                break;

            default:
                $("#c").text("c. " + game_state.options.c);
        }
    } else {
        $("#c").text("");
    }
}

function set_d(game_state) {
    if (game_state.options.d !== "") {
        switch (game_state.options.d) {
            case "BUY_WEAPON":
                var weapon = game_state.for_sell;
                $("#d").text("d. Buy " +
                    a_or_an(weapons_map[weapon][0]) + " " +
                    weapons_map[weapon] + ".");
                break;

            case "Dance a jig.":
                set_alt_option_name("d", "Dance a jig.", "Dance some more.");
                break;

            case "FLIRT_WITH":
                $("#d").text("d. Flirt with " +
                    get_person_name(game_state) + ".");
                break;

            case "Go swimming in a pool of lava.":
                if (game_state.outcome === "lava_swim") {
                    $("#d").text("d. Go swimming in another pool of lava.");
                } else {
                    $("#d").text("d. Go swimming in a pool of lava.");
                }
                break;

            case "TELL_GUARDS":
                $("#d").text("d. Tell the guards you're not a lunatic, " +
                    "you're just " + game_state.character.excuse + ".");
                break;

            default:
                $("#d").text("d. " + game_state.options.d);
        }
    } else {
        $("#d").text("");
    }
}

function set_e(game_state) {
    if (game_state.options.e !== "") {
        $("#e").text("e. " + game_state.options.e);
    } else {
        $("#e").text("");
    }
}

function set_message(game_state) {
    if (game_state.character.is_tripping) {
        $("#message").text(scramble(game_state.message));
    } else {
        $("#message").text(game_state.message);
    }
}

var weapons_map = {
    "cutlass": "cutlass",
    "dagger": "dagger",
    "hammer": "hammer",
    "iron_hammer": "iron hammer",
    "jeweled_cutlass": "jeweled cutlass",
    "pitchfork": "pitchfork",
    "long_pitchfork": "long pitchfork",
    "poison_dagger": "poison dagger",
};

$(document).ready(request_initial_world);
<commit_msg>fixed typo<commit_after>"use strict";
/*jslint vars: true, plusplus: true, devel: true, nomen: true*/
/*global define */

var game_state = {};
var USER_INPUT_ALLOWED = true;

function a_execute() {
    if (game_state.options.a === "Play again.") {
        request_initial_world();
    } else {
        request_outcome_of_action(game_state.options.a);
    }
}

function a_or_an(next_letter) {
    if (next_letter === "a" ||
        next_letter === "e" ||
        next_letter === "i" ||
        next_letter === "o" ||
        next_letter === "u") {
        return "an";
    }
    return "a";
}

function set_alt_option_name(letter, option, alternate) {
    if (game_state.action === option) {
        $("#" + letter).text(letter + ". " + alternate);
    } else {
        $("#" + letter).text(letter + ". " + option);
    }
}

function b_execute() {
    if (game_state.options.b === "Don't play again.") {
        window.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
    } else {
        request_outcome_of_action(game_state.options.b);
    }
}

function bind_keys() {
    document.onkeypress = function(event) {
        var ascii = event.which;
        if ((ascii == 49 || ascii == 65 || ascii == 97) &&
            USER_INPUT_ALLOWED) {
            a_execute();
        } else if ((ascii == 50 || ascii == 66 || ascii == 98) &&
                   USER_INPUT_ALLOWED) {
            b_execute();
        } else if ((ascii == 51 || ascii == 67 || ascii == 99) &&
                   USER_INPUT_ALLOWED &&
                   game_state.options.c !== "") {
            execute("c");
        } else if ((ascii == 52 || ascii == 68 || ascii == 100) &&
                   USER_INPUT_ALLOWED &&
                   game_state.options.d !== "") {
            execute("d");
        } else if ((ascii == 53 || ascii == 69 || ascii == 101) &&
                   USER_INPUT_ALLOWED &&
                   game_state.options.e !== "") {
            execute("e");
        }
    };
}

function execute(letter) {
    request_outcome_of_action(game_state.options[letter]);
}

function get_ground(game_state) {
    switch (game_state.character.place) {
        case "pirate_ship":
            return "deck";
        case "docks":
            return "docks";
    }
    if (game_state.places[game_state.character.place].outside === false) {
        return "floor";
    } else {
        return "ground";
    }
}

function get_person_name(game_state) {
    return game_state.persons[game_state.character.person].name;
}

function get_place_name(game_state) {
    return game_state.places[game_state.character.place].name;
}

function handle_new_world(resp) {
    if (resp.message === "error") {
        handle_world_error(game_state);
    } else {
        game_state = resp;

        if (game_state.character.is_dead) {
            game_state.message += " You are dead.";
        }

        set_message(game_state);
        set_a(game_state);
        set_b(game_state);
        set_c(game_state);
        set_d(game_state);
        set_e(game_state);
        $("#score").text("Score: " + game_state.score);

        if (parseInt(game_state.score) === 0) {
        // we only need to bind the keys if this is the first frame of the game
        // and the player has a score of 0 at the first frame of the game

        // I am binding the keys at the end of the handle_new_world function
        // to prevent the client from being able to make a bad server request
        // before the server has given the client the initial game state
            bind_keys();
        }
    }
    USER_INPUT_ALLOWED = true; // re-allow user inputs now that we have a new
                               // game state
}

function handle_world_error(game_state) {
    $("#message").text("The universe rips apart because an error occured on the server. Please email sberg@uoregon.edu about what you were doing in the game when the error ocurred or raise an issue at https://github.com/SageBerg/St.GeorgeGame/issues/. I'll try to fix the issue ASAP.");
    $("#a").text("Play again.");
    $("#b").text("Don't play again.");
    $("#c").text("");
    $("#d").text("");
    $("#e").text("");
    game_state.options.a = "Play again.";
    game_state.options.b = "Don't play again.";
    game_state.options.c = "";
    game_state.options.d = "";
    game_state.options.e = "";
}

function random_choice(array) {
    return array[random_int(array.length)];
}

function random_int(n) {
    return Math.floor(Math.random() * n);
}

function request_initial_world() {
    $.get("request_initial_world.json", {}, handle_new_world);
}

function request_outcome_of_action(action) {
    game_state.action = action;
    USER_INPUT_ALLOWED = false;
    $.get("request_outcome_of_action.json",
           game_state,
           handle_new_world);
}

// CREDITS: function based on top answer by community wiki at:
// http://stackoverflow.com/questions/2450954/
//        how-to-randomize-shuffle-a-javascript-array
function scramble(text) {
    text = text.replace(/\./g, "");
    text = text.replace(/,/g, "");
    text = text.replace(/\?/g, "");
    text = text.replace(/!/g, "");
    text = text.replace(/"/g, "");

    text = text.toLowerCase();
    var array = text.split(" ");
    var current_index = array.length, temporary_value, random_index ;

    while (0 !== current_index) {
        random_index = Math.floor(Math.random() * current_index);
        current_index -= 1;
        temporary_value = array[current_index];
        array[current_index] = array[random_index];
        array[random_index] = temporary_value;
    }

    var return_text = "";
    for (var i = 0; i < array.length; i++) {
        return_text += array[i] + " ";
    }

    return return_text;
}

function set_a(game_state) {
    switch (game_state.options.a) {
        case "ATTACK":
            $("#a").text("a. Attack " + get_person_name(game_state) + ".");
            break;

        case "GIVE_HER_CAT":
            var cat = "your cat";
            if (game_state.character.items.cat > 1) {
                cat = "one of your cats";
            }
            $("#a").text("a. Give " + get_person_name(game_state) + cat + ".");
            break;

        case "Go flower picking.":
            set_alt_option_name("a", "Go flower picking.",
                                "Go flower picking again.");
            break;

        case "LICK_THE_GROUND":
            $("#a").text("a. Lick the " + get_ground(game_state) + ".");
            break;

        case "MARRY":
            $("#a").text("a. Marry " + get_person_name(game_state) + ".");
            break;

        case "Think.":
            set_alt_option_name("a", "Think.", "Think some more.");
            break;

        case "YELL_A_PIRATE_PHRASE":
            $("#a").text("a. Yell, \"" +
                random_choice([
                    "Ahoy",
                    "All hands on deck",
                    "Arr Matey",
                    "Avast",
                    "Aye Aye",
                    "Dead men tell no tales",
                    "Hoist the Jolly Roger",
                    "Land ho",
                    "Send 'em to Davy Jones' locker",
                    "Shiver me timbers",
                    "Thare she blows",
                    "Walk the plank",
                    "X marks the spot",
                    "Yo, ho, ho, and a bottle of rum",
                ]) + "!\"");
            break;

        default:
            $("#a").text("a. " + game_state.options.a);
    }
}

function set_b(game_state) {
    switch (game_state.options.b) {
        case "BURN":
            $("#b").text("b. Burn " +  get_place_name(game_state) +
                " to the ground.");
            break;

        case "Buy a drink.":
            set_alt_option_name("b", "Buy a drink.", "Buy another drink.");
            break;

        case "BUY_ITEM":
            var item = game_state.for_sell;
            $("#b").text("b. Buy " +
                a_or_an(item[0]) + " " + item + ".");
            break;

        case "GIVE_FLOWERS":
            if (game_state.character.place === "prison") {
                if (game_state.persons.felicity.name === "the fat lady") {
                    $("#b").text("b. Give the fat lady who feeds you a " +
                        "bouquet of flowers.");
                } else {
                    $("#b").text("b. Give Felicity your bouquet of flowers.");
                }
            } else {
                $("#b").text("b. Give her your bouquet of flowers.");
            }
            break;

        case "LOVE_POTION":
            $("#b").text("b. Use your love potion on " +
                get_person_name(game_state) + ".");
            break;

        case "Pray to a higher power.":
            set_alt_option_name("b", "Pray to a higher power.",
                                "Continue praying.");
            break;

        case "SHOW_COIN":
            $("#b").text("b. Show " + get_person_name(game_state) +
                " your shiny foreign coin.");
            break;

        case "SUCK_UP":
            $("#b").text("b. Suck up to " + get_person_name(game_state) + ".");
            break;

        default:
            $("#b").text("b. " + game_state.options.b);
    }
}

function set_c(game_state) {
    if (game_state.options.c !== "") {
        switch (game_state.options.c) {

            case "Go to sleep.":
                set_alt_option_name("c", "Go to sleep.", "Go back to sleep.");
                break;

            case "GO_TO":
                var dest = game_state.destination;
                if (game_state.character.items.donkey > 0) {
                    $("#c").text("c. Ride your donkey to " +
                        game_state.places[dest].name + ".");
                } else {
                    $("#c").text("c. Go to " + game_state.places[dest].name +
                        ".");
                }
                break;

            default:
                $("#c").text("c. " + game_state.options.c);
        }
    } else {
        $("#c").text("");
    }
}

function set_d(game_state) {
    if (game_state.options.d !== "") {
        switch (game_state.options.d) {
            case "BUY_WEAPON":
                var weapon = game_state.for_sell;
                $("#d").text("d. Buy " +
                    a_or_an(weapons_map[weapon][0]) + " " +
                    weapons_map[weapon] + ".");
                break;

            case "Dance a jig.":
                set_alt_option_name("d", "Dance a jig.", "Dance some more.");
                break;

            case "FLIRT_WITH":
                $("#d").text("d. Flirt with " +
                    get_person_name(game_state) + ".");
                break;

            case "Go swimming in a pool of lava.":
                if (game_state.outcome === "lava_swim") {
                    $("#d").text("d. Go swimming in another pool of lava.");
                } else {
                    $("#d").text("d. Go swimming in a pool of lava.");
                }
                break;

            case "TELL_GUARDS":
                $("#d").text("d. Tell the guards you're not a lunatic, " +
                    "you're just " + game_state.character.excuse + ".");
                break;

            default:
                $("#d").text("d. " + game_state.options.d);
        }
    } else {
        $("#d").text("");
    }
}

function set_e(game_state) {
    if (game_state.options.e !== "") {
        $("#e").text("e. " + game_state.options.e);
    } else {
        $("#e").text("");
    }
}

function set_message(game_state) {
    if (game_state.character.is_tripping) {
        $("#message").text(scramble(game_state.message));
    } else {
        $("#message").text(game_state.message);
    }
}

var weapons_map = {
    "cutlass": "cutlass",
    "dagger": "dagger",
    "hammer": "hammer",
    "iron_hammer": "iron hammer",
    "jeweled_cutlass": "jeweled cutlass",
    "pitchfork": "pitchfork",
    "long_pitchfork": "long pitchfork",
    "poison_dagger": "poison dagger",
};

$(document).ready(request_initial_world);
<|endoftext|>


<commit_before>var camera;
var scene;
var renderer;
var collectibleItemCube;
var collectibleItemSphere;
var center;

var maze = {width: 15, large: 9, cellSize: 500};

var angleX = 0;
var windowHalfX = window.innerWidth / 2;
var incrementoX = Math.PI / windowHalfX;

var mouseX = windowHalfX;

var person = {
    startPosition: {
        x: 1,
        z: 8
    }
};

wallGeometries = [];

init();

function init() {
    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
    camera.position.x = (person.startPosition.x - maze.width / 2) * maze.cellSize;
    camera.position.z = (person.startPosition.z - maze.large / 2) * maze.cellSize - maze.cellSize / 2;

    center = new THREE.Vector3(camera.position.x + 250, 0, 0);

    var geometryPlane = new THREE.PlaneBufferGeometry(maze.width * maze.cellSize, maze.large * maze.cellSize);
    var geometryPlaneBasic = new THREE.PlaneBufferGeometry(maze.cellSize, maze.cellSize, 1, 1);

    // ceiling
    var ceiling = new THREE.Mesh(geometryPlane, new THREE.MeshBasicMaterial({
        map: THREE.ImageUtils.loadTexture('textures/ceiling.jpg')
    }));
    ceiling.rotation.x = Math.PI / 2;
    ceiling.position.y = maze.cellSize / 2;
    scene.add(ceiling);

    // floor
    var floorTexture = THREE.ImageUtils.loadTexture('textures/floor.png');
    floorTexture.wrapS = THREE.RepeatWrapping;
    floorTexture.wrapT = THREE.RepeatWrapping;
    floorTexture.repeat.set(maze.width, maze.large);

    var floor = new THREE.Mesh(geometryPlane, new THREE.MeshBasicMaterial({
        map: floorTexture
    }));
    floor.rotation.x = -Math.PI / 2;
    floor.position.y = -maze.cellSize / 2;
    scene.add(floor);

    var wallMaterial = new THREE.MeshBasicMaterial({
        map: THREE.ImageUtils.loadTexture('textures/wall.png'),
        side: THREE.DoubleSide
    });
    // South and North walls
    for (var actualMazeWidth = 0; actualMazeWidth < maze.width; actualMazeWidth++) {
        var borderWallSN = new THREE.Mesh(geometryPlaneBasic, wallMaterial);
        borderWallSN.position.z = maze.large / 2 * maze.cellSize;
        borderWallSN.position.y = 0;
        borderWallSN.position.x = (actualMazeWidth - maze.width / 2) * maze.cellSize + maze.cellSize / 2;
        scene.add(borderWallSN);
        wallGeometries.push(borderWallSN);

        borderWallSN = new THREE.Mesh(geometryPlaneBasic, wallMaterial);
        borderWallSN.position.z = -maze.large / 2 * maze.cellSize;
        borderWallSN.position.y = 0;
        borderWallSN.position.x = (actualMazeWidth - maze.width / 2) * maze.cellSize + maze.cellSize / 2;
        scene.add(borderWallSN);
        wallGeometries.push(borderWallSN);
    }

    // East and West walls
    for (var actualMazeLarge = 0; actualMazeLarge < maze.large; actualMazeLarge++) {
        var borderWallEW = new THREE.Mesh(geometryPlaneBasic, wallMaterial);
        borderWallEW.rotation.y = Math.PI / 2;
        borderWallEW.position.x = maze.width / 2 * maze.cellSize;
        borderWallEW.position.y = 0;
        borderWallEW.position.z = (actualMazeLarge - maze.large / 2) * maze.cellSize + maze.cellSize / 2;
        scene.add(borderWallEW);
        wallGeometries.push(borderWallEW);

        borderWallEW = new THREE.Mesh(geometryPlaneBasic, wallMaterial);
        borderWallEW.rotation.y = Math.PI / 2;
        borderWallEW.position.x = -maze.width / 2 * maze.cellSize;
        borderWallEW.position.y = 0;
        borderWallEW.position.z = (actualMazeLarge - maze.large / 2) * maze.cellSize + maze.cellSize / 2;
        scene.add(borderWallEW);
        wallGeometries.push(borderWallEW);
    }

    // walls inside the maze
    var offsizeX = 0;
    var offsizeZ = 0;
    for (var i = 0; i < walls.length; i++) {
        var wallData = walls[i];
        var insideWalls = new THREE.Mesh(geometryPlaneBasic, wallMaterial);
        if (wallData.orientation === 'front') {
            offsizeX = -250;
            offsizeZ = -maze.cellSize;
        } else if (wallData.orientation === 'back') {
            offsizeX = -250;
            offsizeZ = 0;
        } else if (wallData.orientation === 'left') {
            offsizeX = -maze.cellSize;
            offsizeZ = -250;
        } else if (wallData.orientation === 'right') {
            offsizeX = 0;
            offsizeZ = -250;
        }
        insideWalls.rotation.y = wallData.orientation === 'left' || wallData.orientation === 'right' ? Math.PI / 2 : 0;
        insideWalls.position.x = (wallData.x - maze.width / 2) * maze.cellSize + offsizeX;
        insideWalls.position.y = 0;
        insideWalls.position.z = (wallData.z - maze.large / 2) * maze.cellSize + offsizeZ;
        scene.add(insideWalls);
        wallGeometries.push(insideWalls);
    }

    // cube
    collectibleItemCube = new THREE.Mesh(new THREE.BoxGeometry(200, 200, 200), new THREE.MeshBasicMaterial({
        color: 'green'
    }));
    collectibleItemCube.position.z = -1500;
    scene.add(collectibleItemCube);

    // sphere
    collectibleItemSphere = new THREE.Mesh(new THREE.SphereGeometry(75, 16, 16), new THREE.MeshBasicMaterial({
        color: 'yellow'
    }));
    collectibleItemSphere.position.z = 2000;
    collectibleItemSphere.position.x = 1000;
    scene.add(collectibleItemSphere);

    //adding some light to the scene
    var pointLight = new THREE.DirectionalLight(0xffffff);
    pointLight.position.set(0, 0, 1).normalize();
    scene.add(pointLight);

    renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight * .75);
    document.body.insertBefore(renderer.domElement, document.getElementById('footer'));

    // listeners
    document.addEventListener('mousemove', onMouseMove, false);
    document.addEventListener('keydown', onKeyDown, false);

    animate();
}

function onMouseMove(e) {
    var difference = mouseX - e.clientX;
    angleX -= incrementoX * difference;

    mouseX = e.clientX;
    if (mouseX <= windowHalfX - 100 && difference > 0) {
        angleX -= incrementoX * 5;
    }
    if (mouseX >= windowHalfX + 100 && difference < 0) {
        angleX += incrementoX * 5;
    }
    //x movement ok
    e.preventDefault();
}

function onKeyDown(e) {
    var ray = new THREE.Raycaster(camera.position, center.clone().normalize(), 0, 100);

    // This makes it impossible to walk through walls
    if (ray.intersectObjects(wallGeometries).length !== 1) {
        var keyCode = e.which || e.keyCode;
        // w
        if (keyCode === 87) {
            camera.translateZ(-30);
        }
        // d
        if (keyCode === 68) {
            camera.translateX(30);
        }
        //s
        if (keyCode === 83) {
            camera.translateZ(30);
        }
        // a
        if (keyCode === 65) {
            camera.translateX(-30);
        }
    }

    if (ray.intersectObject(collectibleItemCube).length === 1) {
        scene.remove(collectibleItemCube);
        document.getElementById('cube').classList.add('found');
    }
    if (ray.intersectObject(collectibleItemSphere).length === 1) {
        scene.remove(collectibleItemSphere);
        document.getElementById('ball').classList.add('found');
    }
}

function animate() {
    if (mouseX <= 100) {
        angleX -= incrementoX * 10;
    }
    if (mouseX >= windowHalfX * 2 - 100) {
        angleX += incrementoX * 10;
    }

    center.x = windowHalfX * 32 * Math.cos(angleX);
    center.z = windowHalfX * 32 * Math.sin(angleX);

    requestAnimationFrame(animate);

    collectibleItemCube.rotation.x += 0.01;
    collectibleItemCube.rotation.y += 0.02;
    collectibleItemSphere.rotation.y -= 0.01;

    camera.lookAt(center);
    renderer.render(scene, camera);
}
<commit_msg>correct intersect detection<commit_after>var camera;
var scene;
var renderer;
var collectibleItemCube;
var collectibleItemSphere;
var center;

var maze = {width: 15, large: 9, cellSize: 500};

var angleX = 0;
var windowHalfX = window.innerWidth / 2;
var incrementoX = Math.PI / windowHalfX;

var mouseX = windowHalfX;

var person = {
    startPosition: {
        x: 1,
        z: 8
    }
};

wallGeometries = [];

init();

function init() {
    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
    camera.position.x = (person.startPosition.x - maze.width / 2) * maze.cellSize;
    camera.position.z = (person.startPosition.z - maze.large / 2) * maze.cellSize - maze.cellSize / 2;

    center = new THREE.Vector3(camera.position.x + 250, 0, 0);

    var geometryPlane = new THREE.PlaneBufferGeometry(maze.width * maze.cellSize, maze.large * maze.cellSize);
    var geometryPlaneBasic = new THREE.PlaneBufferGeometry(maze.cellSize, maze.cellSize, 1, 1);

    // ceiling
    var ceiling = new THREE.Mesh(geometryPlane, new THREE.MeshBasicMaterial({
        map: THREE.ImageUtils.loadTexture('textures/ceiling.jpg')
    }));
    ceiling.rotation.x = Math.PI / 2;
    ceiling.position.y = maze.cellSize / 2;
    scene.add(ceiling);

    // floor
    var floorTexture = THREE.ImageUtils.loadTexture('textures/floor.png');
    floorTexture.wrapS = THREE.RepeatWrapping;
    floorTexture.wrapT = THREE.RepeatWrapping;
    floorTexture.repeat.set(maze.width, maze.large);

    var floor = new THREE.Mesh(geometryPlane, new THREE.MeshBasicMaterial({
        map: floorTexture
    }));
    floor.rotation.x = -Math.PI / 2;
    floor.position.y = -maze.cellSize / 2;
    scene.add(floor);

    var wallMaterial = new THREE.MeshBasicMaterial({
        map: THREE.ImageUtils.loadTexture('textures/wall.png'),
        side: THREE.DoubleSide
    });
    // South and North walls
    for (var actualMazeWidth = 0; actualMazeWidth < maze.width; actualMazeWidth++) {
        var borderWallSN = new THREE.Mesh(geometryPlaneBasic, wallMaterial);
        borderWallSN.position.z = maze.large / 2 * maze.cellSize;
        borderWallSN.position.y = 0;
        borderWallSN.position.x = (actualMazeWidth - maze.width / 2) * maze.cellSize + maze.cellSize / 2;
        scene.add(borderWallSN);
        wallGeometries.push(borderWallSN);

        borderWallSN = new THREE.Mesh(geometryPlaneBasic, wallMaterial);
        borderWallSN.position.z = -maze.large / 2 * maze.cellSize;
        borderWallSN.position.y = 0;
        borderWallSN.position.x = (actualMazeWidth - maze.width / 2) * maze.cellSize + maze.cellSize / 2;
        scene.add(borderWallSN);
        wallGeometries.push(borderWallSN);
    }

    // East and West walls
    for (var actualMazeLarge = 0; actualMazeLarge < maze.large; actualMazeLarge++) {
        var borderWallEW = new THREE.Mesh(geometryPlaneBasic, wallMaterial);
        borderWallEW.rotation.y = Math.PI / 2;
        borderWallEW.position.x = maze.width / 2 * maze.cellSize;
        borderWallEW.position.y = 0;
        borderWallEW.position.z = (actualMazeLarge - maze.large / 2) * maze.cellSize + maze.cellSize / 2;
        scene.add(borderWallEW);
        wallGeometries.push(borderWallEW);

        borderWallEW = new THREE.Mesh(geometryPlaneBasic, wallMaterial);
        borderWallEW.rotation.y = Math.PI / 2;
        borderWallEW.position.x = -maze.width / 2 * maze.cellSize;
        borderWallEW.position.y = 0;
        borderWallEW.position.z = (actualMazeLarge - maze.large / 2) * maze.cellSize + maze.cellSize / 2;
        scene.add(borderWallEW);
        wallGeometries.push(borderWallEW);
    }

    // walls inside the maze
    var offsizeX = 0;
    var offsizeZ = 0;
    for (var i = 0; i < walls.length; i++) {
        var wallData = walls[i];
        var insideWalls = new THREE.Mesh(geometryPlaneBasic, wallMaterial);
        if (wallData.orientation === 'front') {
            offsizeX = -250;
            offsizeZ = -maze.cellSize;
        } else if (wallData.orientation === 'back') {
            offsizeX = -250;
            offsizeZ = 0;
        } else if (wallData.orientation === 'left') {
            offsizeX = -maze.cellSize;
            offsizeZ = -250;
        } else if (wallData.orientation === 'right') {
            offsizeX = 0;
            offsizeZ = -250;
        }
        insideWalls.rotation.y = wallData.orientation === 'left' || wallData.orientation === 'right' ? Math.PI / 2 : 0;
        insideWalls.position.x = (wallData.x - maze.width / 2) * maze.cellSize + offsizeX;
        insideWalls.position.y = 0;
        insideWalls.position.z = (wallData.z - maze.large / 2) * maze.cellSize + offsizeZ;
        scene.add(insideWalls);
        wallGeometries.push(insideWalls);
    }

    // cube
    collectibleItemCube = new THREE.Mesh(new THREE.BoxGeometry(200, 200, 200), new THREE.MeshBasicMaterial({
        color: 'green'
    }));
    collectibleItemCube.position.z = -1500;
    scene.add(collectibleItemCube);

    // sphere
    collectibleItemSphere = new THREE.Mesh(new THREE.SphereGeometry(75, 16, 16), new THREE.MeshBasicMaterial({
        color: 'yellow'
    }));
    collectibleItemSphere.position.z = 2000;
    collectibleItemSphere.position.x = 1000;
    scene.add(collectibleItemSphere);

    //adding some light to the scene
    var pointLight = new THREE.DirectionalLight(0xffffff);
    pointLight.position.set(0, 0, 1).normalize();
    scene.add(pointLight);

    renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight * .75);
    document.body.insertBefore(renderer.domElement, document.getElementById('footer'));

    // listeners
    document.addEventListener('mousemove', onMouseMove, false);
    document.addEventListener('keydown', onKeyDown, false);

    animate();
}

function onMouseMove(e) {
    var difference = mouseX - e.clientX;
    angleX -= incrementoX * difference;

    mouseX = e.clientX;
    if (mouseX <= windowHalfX - 100 && difference > 0) {
        angleX -= incrementoX * 5;
    }
    if (mouseX >= windowHalfX + 100 && difference < 0) {
        angleX += incrementoX * 5;
    }
    //x movement ok
    e.preventDefault();
}

function onKeyDown(e) {
    var ray = new THREE.Raycaster(camera.position, center.clone().normalize(), 0, 100);

    // This makes it impossible to walk through walls
    if (ray.intersectObjects(wallGeometries).length === 0) {
        var keyCode = e.which || e.keyCode;
        // w
        if (keyCode === 87) {
            camera.translateZ(-30);
        }
        // d
        if (keyCode === 68) {
            camera.translateX(30);
        }
        //s
        if (keyCode === 83) {
            camera.translateZ(30);
        }
        // a
        if (keyCode === 65) {
            camera.translateX(-30);
        }
    }

    if (rayCaster.intersectObject(collectibleItemCube).length > 0) {
        scene.remove(collectibleItemCube);
        document.getElementById('cube').classList.add('found');
    }
    if (rayCaster.intersectObject(collectibleItemSphere).length > 0) {
        scene.remove(collectibleItemSphere);
        document.getElementById('ball').classList.add('found');
    }
}

function animate() {
    if (mouseX <= 100) {
        angleX -= incrementoX * 10;
    }
    if (mouseX >= windowHalfX * 2 - 100) {
        angleX += incrementoX * 10;
    }

    center.x = windowHalfX * 32 * Math.cos(angleX);
    center.z = windowHalfX * 32 * Math.sin(angleX);

    requestAnimationFrame(animate);

    collectibleItemCube.rotation.x += 0.01;
    collectibleItemCube.rotation.y += 0.02;
    collectibleItemSphere.rotation.y -= 0.01;

    camera.lookAt(center);
    renderer.render(scene, camera);
}
<|endoftext|>


<commit_before>define([
	"dojo/_base/declare", "dijit/layout/BorderContainer", "dojo/on", "dojo/_base/Deferred",
	"dojo/dom-class", "dijit/layout/ContentPane", "dojo/dom-construct",
	"dojo/_base/xhr", "dojo/_base/lang", "./PageGrid", "./formatter", "../store/SubSystemPieChartMemoryStore", "dojo/request",
	"dojo/aspect", "./GridSelector", "dojo/when", "d3/d3", "dojo/Stateful"
], function(declare, BorderContainer, on, Deferred,
			domClass, ContentPane, domConstruct,
			xhr, lang, Grid, formatter, Store, request,
			aspect, selector, when, d3, Stateful){
	return declare([Stateful], {
		// region: "center",
		// query: (this.query || ""),
		// apiToken: window.App.authorizationToken,
		// apiServer: window.App.dataServiceURL,
		store: null,
		// dataModel: "subsystem",
		// primaryKey: "id",
		// selectionModel: "extended",
		// loadingMessage: "Loading subsystems.  This may take several minutes...",
		// deselectOnRefresh: true,
		// subsystem_data: {},
		// fullSelectAll: true,
		// state: null,

		// _setApiServer: function(server){
		// 	this.apiServer = server;
		// },

		constructor: function(){

			this.watch("state", lang.hitch(this, "onSetState"));
		},

		onSetState: function(attr, oldState, state){

			// var oldState = this.get('state');

			var ov, nv;
			if(oldState){
				ov = oldState.search;
				if(oldState.hashParams.filter){
					ov = ov + oldState.hashParams.filter;
				}
			}

			if(state){
				nv = state.search;
				if(state.hashParams.filter){
					nv = nv + state.hashParams.filter;
				}
			}

			this.state = state;

			if(ov != nv){
				if(!this.store){
					this.set('store', this.createStore(this.apiServer, this.apiToken || window.App.authorizationToken, state));
				}else{
					this.store.set("state", lang.mixin({}, state));
				}
					var that = this;

					Deferred.when(this.store.query(), function(data) {
						console.log(data)
						that.drawGraph(data);
					});
				// }
				// this.refresh()
			}else{
				// this.refresh()
			}
		},

		drawGraph: function(pieChartData) {
			console.log(pieChartData);

			var width = 1000;
			var height = 1000;
			var radius = Math.min(width, height) / 2;

			var color = d3.scaleOrdinal(d3.schemeCategory20);

			var svg = d3.select('#subsystemspiechart')
	          .append('svg')
	          .attr('width', width)
	          .attr('height', height)
	          .append('g')
	          .attr('transform', 'translate(' + (width / 2) +
	            ',' + (height / 2) + ')');

	        var arc = d3.arc()
	          .innerRadius(0)
	          .outerRadius(radius);

	        var pie = d3.pie()
	          .value(function(d) { return d.count; })
	          .sort(null);

	        var path = svg.selectAll('path')
	          .data(pie(pieChartData))
	          .enter()
	          .append('path')
	          .attr('d', arc)
	          .attr('fill', function(d) {
	            return color(d.pieChartData.val);
	        });
	    // }

		},

		// _setVisibleAttr: function(visible){
		// 	this.visible = visible;

		// 	if(this.visible && !this._firstView){
		// 		this.onFirstView();
		// 	}

		// 	if(this.viewer){
		// 		this.viewer.set('visible', true);

		// 		// this.service.get_palette('compare_region', function(palette){
		// 		// 	this.compare_regions.set_palette(palette);
		// 		// }.bind(this));
		// 	}
		// },

		// onFirstView: function(){
		// 	if(this._firstView){
		// 		return;
		// 	}

		// 	this.viewer = new ContentPane({
		// 		region: "center",
		// 		content: "

",
		// 		style: "padding:0"
		// 	})
		// 	this.addChild(this.viewer);

		// 	this.inherited(arguments);
		// 	this._firstView = true;
		// },

		createStore: function(server, token, state){
			if(this.store){
				return this.store
			}

			return new Store({
				token: window.App.authorizationToken,
				apiServer: window.App.dataServiceURL,
				state: this.state,
				type: "subsystems_overview"
			});
		}
	});
});
<commit_msg>graph rendering<commit_after>define([
	"dojo/_base/declare", "dijit/layout/BorderContainer", "dojo/on", "dojo/_base/Deferred",
	"dojo/dom-class", "dijit/layout/ContentPane", "dojo/dom-construct",
	"dojo/_base/xhr", "dojo/_base/lang", "./PageGrid", "./formatter", "../store/SubSystemPieChartMemoryStore", "dojo/request",
	"dojo/aspect", "./GridSelector", "dojo/when", "d3/d3", "dojo/Stateful"
], function(declare, BorderContainer, on, Deferred,
			domClass, ContentPane, domConstruct,
			xhr, lang, Grid, formatter, Store, request,
			aspect, selector, when, d3, Stateful){
	return declare([Stateful], {
		// region: "center",
		// query: (this.query || ""),
		// apiToken: window.App.authorizationToken,
		// apiServer: window.App.dataServiceURL,
		store: null,
		// dataModel: "subsystem",
		// primaryKey: "id",
		// selectionModel: "extended",
		// loadingMessage: "Loading subsystems.  This may take several minutes...",
		// deselectOnRefresh: true,
		// subsystem_data: {},
		// fullSelectAll: true,
		// state: null,

		// _setApiServer: function(server){
		// 	this.apiServer = server;
		// },

		constructor: function(){

			this.watch("state", lang.hitch(this, "onSetState"));
		},

		onSetState: function(attr, oldState, state){

			// var oldState = this.get('state');

			var ov, nv;
			if(oldState){
				ov = oldState.search;
				if(oldState.hashParams.filter){
					ov = ov + oldState.hashParams.filter;
				}
			}

			if(state){
				nv = state.search;
				if(state.hashParams.filter){
					nv = nv + state.hashParams.filter;
				}
			}

			this.state = state;

			if(!this.store){
				this.set('store', this.createStore(this.apiServer, this.apiToken || window.App.authorizationToken, state));
			}else{
				this.store.set("state", lang.mixin({}, state));
			}

			var that = this;

			Deferred.when(this.store.query(), function(data) {
				that.drawGraph(data);
			});

		},

		drawGraph: function(pieChartData) {
			var width = 700;
			var height = 700;
			var radius = Math.min(width, height) / 2;

			var color = d3.scale.category20();

			var svg = d3.select('#subsystemspiechart')
	          .append('svg')
	          .attr('width', width)
	          .attr('height', height)
	          .append('g')
	          .attr('transform', 'translate(' + (width / 2) +
	            ',' + (height / 2) + ')');

	        var arc = d3.svg.arc()
	          .innerRadius(0)
	          .outerRadius(radius);

	        var pie = d3.layout.pie()
	          .value(function(d) { return d.count; })
	          .sort(null);

	        var path = svg.selectAll('path')
	          .data(pie(pieChartData))
	          .enter()
	          .append('path')
	          .attr('d', arc)
	          .attr('fill', function(d) {
	            return color(d.data.val);
	        });
		},

		// _setVisibleAttr: function(visible){
		// 	this.visible = visible;

		// 	if(this.visible && !this._firstView){
		// 		this.onFirstView();
		// 	}

		// 	if(this.viewer){
		// 		this.viewer.set('visible', true);

		// 		// this.service.get_palette('compare_region', function(palette){
		// 		// 	this.compare_regions.set_palette(palette);
		// 		// }.bind(this));
		// 	}
		// },

		// onFirstView: function(){
		// 	if(this._firstView){
		// 		return;
		// 	}

		// 	this.viewer = new ContentPane({
		// 		region: "center",
		// 		content: "

",
		// 		style: "padding:0"
		// 	})
		// 	this.addChild(this.viewer);

		// 	this.inherited(arguments);
		// 	this._firstView = true;
		// },

		createStore: function(server, token, state){
			if(this.store){
				return this.store
			}

			return new Store({
				token: window.App.authorizationToken,
				apiServer: window.App.dataServiceURL,
				state: this.state,
				type: "subsystems_overview"
			});
		}
	});
});
<|endoftext|>