<commit_before>/**
 * Created by Robert Butterworth on 8/9/2014.
 */

SEQUENCE = function() {

    var self = this;
    this.SequenceTime = 0; //Actual time of the Sequence.
    this.SequenceLength = 15*FPS;
    this.Version = 1;
    this.Events = [];
    this.Play = true;
    var mUndoIndex = 0;
    var mMaxUndoIndex = 0;
    var mUndoGrouping = false;

    var previousTime = new Date().getTime();

    this.GetSequenceTime = function()
    {
        return this.SequenceTime;
    };

    this.SetSequenceTime = function(time)
    {
        timer = time;
        this.SequenceTime = time;
    }

    this.ClearSequence = function()
    {
        ClearLights();
        this.Events = [];
        mUndoIndex = 0;
        mMaxUndoIndex = 0;
    }

    this.GetSequenceLength = function()
    {
        return this.SequenceLength;
    };

    this.__defineGetter__("UndoIndex", function(){
        return mUndoIndex;
    });

    this.__defineSetter__("UndoIndex", function(val){

        if(val > mMaxUndoIndex){val = mMaxUndoIndex;}
        if(val < 0){val = 0;}

        mUndoIndex = val;
        UpdateUndoStack(false);
    });

    this.RenderFrame = function(frame, returnFrame)
    {
        var x;

        ClearLights();

        //Render Background
        for(x = 0; x < this.Events.length; x++)
        {
            if((this.Events[x].StartTime <= frame)&&
               (this.Events[x].Brush.Duration + this.Events[x].StartTime > frame))
            {
                if(this.Events[x].IsBackground == true && this.Events[x].Enabled == true)
                {
                        this.Events[x].Render(frame - this.Events[x].StartTime);
                }
            }
        }
        //Render Foreground
        for(x = 0; x < this.Events.length; x++)
        {
            if((this.Events[x].StartTime <= this.SequenceTime)&&
               (this.Events[x].Brush.Duration + this.Events[x].StartTime > frame))
            {
                if(this.Events[x].IsBackground == false && this.Events[x].Enabled == true)
                {
                        this.Events[x].Render(frame - this.Events[x].StartTime);
                }
            }
        }

        //Create Stream
        if(returnFrame == true)
        {
            var binaryFrame = "";

            for (var i = 0; i < 260; i++) {

                var color = new THREE.Color();

                var lightIndex = DomeLightOrder[i];

                color = DomeLightManager.Lights[lightIndex].color;

                binaryFrame += color.getHexString();
                // binaryFrame += String.fromCharCode( color.r );
                // binaryFrame += String.fromCharCode( color.g );
                // binaryFrame += String.fromCharCode( color.b );
            }

            return binaryFrame;
        }
    };

    this.RenderSequence = function(JSONSequenceConstructionFile)
    {
        var BinarySequenceStream = "";

        this.LoadSequence(JSONSequenceConstructionFile);

        if(this.Events.length < 1)
        {
            console.log("--- No Events in Sequence to Render ---");
            return undefined;
        }

        for (var i = 0; i < this.SequenceLength; i++) {
            this.SequenceTime = i;
            BinarySequenceStream += this.RenderFrame(i,true);
        }

        console.log("--- Stream Rendered ---");

        return BinarySequenceStream;
    };

    this.AddEvent = function(event)
    {

        //We need to sort this on addition based on time as we could be adding in an event at any point in time.
        //eg. During playback of other events.
        UpdateUndoStack(true);

        if(mUndoGrouping == false) {
           mUndoIndex++;
        }

        mMaxUndoIndex = mUndoIndex;

        event.ActionID = mUndoIndex;

        this.Events.push(event);

        //Now we've added another event, sort to ensure they are in the correct order
        this.Events.sort(function(a,b){
            return a.StartTime - b.StartTime;
        });
    };

    this.RemoveEvent = function(atIndex)
    {
        this.Events.remove(atIndex);
    };

    this.Update = function()
    {
        if(this.Play == true)
        {
            timer += 0.8; //getFrameDelta();
            if (timer > this.SequenceLength) timer = 0.0;

            this.SequenceTime = Math.floor(timer);
        }
    };

    function getFrameDelta()
    {
        var frameDelta = 0;

        var currentTime = new Date().getTime();
        var delta = currentTime - previousTime;
        previousTime = currentTime;

        //console.log(delta);
        frameDelta = delta / (1000/FPS);

        return frameDelta;
    }

    //Used to load Objects with the right types
    function RebuildBrushData(Data)
    {
      var CleanData = [];

      if( Data ) {
	      for(var x =0; x < Object.keys(Data).length; x++)
	      {
	          if(Data[x].r != undefined && Data[x].g != undefined && Data[x].b != undefined)
	              CleanData[x] = new THREE.Color(Data[x].r,Data[x].g,Data[x].b);
	          else
	              CleanData[x] = Data[x];
	      }
      }
      return CleanData;
    }

    this.SaveSequence = function()
    {
        this.SequenceConstructionFile = {};
        this.SequenceConstructionFile.Events = [];

        //Set Sequence Properties
        this.SequenceConstructionFile.Version = this.Version;
        this.SequenceConstructionFile.SequenceLength = this.SequenceLength;

        //Add all the Events
        for(var index = 0; index < this.Events.length; index++) {

            var SequenceConstructionEvent = {};

            SequenceConstructionEvent.StartTime = this.Events[index].StartTime;
            SequenceConstructionEvent.OriginLight = this.Events[index].OriginLight;
            SequenceConstructionEvent.BrushID = this.Events[index].Brush.Index;
            SequenceConstructionEvent.BrushData = this.Events[index].BrushData;

            this.SequenceConstructionFile.Events.push(SequenceConstructionEvent);
        }
        return JSON.stringify(this.SequenceConstructionFile);
    };

    this.LoadSequence = function(JSONSequenceConstructionFile)
    {
        this.Events = [];

        var SequenceConstructionFile = JSON.parse(JSONSequenceConstructionFile);
        //Set Sequence Properties
        if(this.Version > SequenceConstructionFile.Version){
            console.log("--- Sequence Upgrade Maybe Required ---");
        }

        this.SequenceLength = SequenceConstructionFile.SequenceLength;

        //Add all the Events
        for(var index = 0; index < SequenceConstructionFile.Events.length; index++) {

            var newEvent = new EVENT(SequenceConstructionFile.Events[index].StartTime,
                                      SequenceConstructionFile.Events[index].OriginLight,
                                      Brushes[SequenceConstructionFile.Events[index].BrushID],
                                      RebuildBrushData(SequenceConstructionFile.Events[index].BrushData));
            this.AddEvent(newEvent);
        }

        console.log("--- File Loaded ---");
    };

    this.StartUndoGroup = function()
    {
        mUndoGrouping = true;
        UpdateUndoStack(true);
        mUndoIndex++;
    };
    this.StopUndoGroup = function(){mUndoGrouping = false;};

    this.Undo = function()
    {
        if(mUndoIndex > 0)
        {
            mUndoIndex--;
            UpdateUndoStack(false);
        }
    };

    this.Redo = function()
    {
        if(mUndoIndex < mMaxUndoIndex)
        {
            mUndoIndex++;
            UpdateUndoStack(false);
        }
    };

    var UpdateUndoStack = function(clearPostIndex)
    {
        var mClearPostIndex = clearPostIndex || false;
        var spliceList = [];

        //iterate through all events and remove/disable based on UndoIndex.
        for(var i = 0; i < self.Events.length; i++)
        {
            if(self.Events[i].ActionID > mUndoIndex ){
                if(mClearPostIndex == true)
                {
                    spliceList.push(i);
                    mMaxUndoIndex = mUndoIndex;
                }
                else
                {
                    self.Events[i].Enabled = false;
                }
            }
            else{
                self.Events[i].Enabled = true;
            }
        }

        //Remove all tagged events
        for(var x = 0; x < spliceList.length; x++)
        {
            self.Events.splice(spliceList[x], 1);
        }
    };

};

var EVENT = function(time, originLight, brush, brushData)
{
    this.ActionID = 0;
    this.Enabled = true;
    this.IsBackground = false;
    this.StartTime = time; //Offset from the start of the sequence in frames.
    this.OriginLight = originLight; // The Light that the animation is based from.
    this.Brush = brush; // The brush that should be applied.
    this.BrushData = brushData; //The current brush data

    this.ApplyData = function()
    {
        this.BrushData = Clone(this.BrushData);
    };

    this.PrePaint = function()
    {
      if(this.Brush.PrePaint != null) this.Brush.PrePaint();
    };
    this.PostPaint = function()
    {
        if(this.Brush.PostPaint != null) this.Brush.PostPaint();
    };
    this.Render = function(CurrentFrame) // Applies brush to canvas
    {
        if (this.Brush.Render != null) this.Brush.Render(CurrentFrame, this.OriginLight, this.BrushData);
    };

    //Init
    this.init = function()
    {

    };
    this.init();
};
<commit_msg>Apply Current Data to Event/s<commit_after>/**
 * Created by Robert Butterworth on 8/9/2014.
 */

SEQUENCE = function() {

    var self = this;
    this.SequenceTime = 0; //Actual time of the Sequence.
    this.SequenceLength = 15*FPS;
    this.Version = 1;
    this.Events = [];
    this.Play = true;
    var mUndoIndex = 0;
    var mMaxUndoIndex = 0;
    var mUndoGrouping = false;

    var previousTime = new Date().getTime();

    this.GetSequenceTime = function()
    {
        return this.SequenceTime;
    };

    this.SetSequenceTime = function(time)
    {
        timer = time;
        this.SequenceTime = time;
    }

    this.ClearSequence = function()
    {
        ClearLights();
        this.Events = [];
        mUndoIndex = 0;
        mMaxUndoIndex = 0;
    }

    this.GetSequenceLength = function()
    {
        return this.SequenceLength;
    };

    this.__defineGetter__("UndoIndex", function(){
        return mUndoIndex;
    });

    this.__defineSetter__("UndoIndex", function(val){

        if(val > mMaxUndoIndex){val = mMaxUndoIndex;}
        if(val < 0){val = 0;}

        mUndoIndex = val;
        UpdateUndoStack(false);
    });

    this.RenderFrame = function(frame, returnFrame)
    {
        var x;

        ClearLights();

        //Render Background
        for(x = 0; x < this.Events.length; x++)
        {
            if((this.Events[x].StartTime <= frame)&&
               (this.Events[x].Brush.Duration + this.Events[x].StartTime > frame))
            {
                if(this.Events[x].IsBackground == true && this.Events[x].Enabled == true)
                {
                        this.Events[x].Render(frame - this.Events[x].StartTime);
                }
            }
        }
        //Render Foreground
        for(x = 0; x < this.Events.length; x++)
        {
            if((this.Events[x].StartTime <= this.SequenceTime)&&
               (this.Events[x].Brush.Duration + this.Events[x].StartTime > frame))
            {
                if(this.Events[x].IsBackground == false && this.Events[x].Enabled == true)
                {
                        this.Events[x].Render(frame - this.Events[x].StartTime);
                }
            }
        }

        //Create Stream
        if(returnFrame == true)
        {
            var binaryFrame = "";

            for (var i = 0; i < 260; i++) {

                var color = new THREE.Color();

                var lightIndex = DomeLightOrder[i];

                color = DomeLightManager.Lights[lightIndex].color;

                binaryFrame += color.getHexString();
                // binaryFrame += String.fromCharCode( color.r );
                // binaryFrame += String.fromCharCode( color.g );
                // binaryFrame += String.fromCharCode( color.b );
            }

            return binaryFrame;
        }
    };

    this.RenderSequence = function(JSONSequenceConstructionFile)
    {
        var BinarySequenceStream = "";

        this.LoadSequence(JSONSequenceConstructionFile);

        if(this.Events.length < 1)
        {
            console.log("--- No Events in Sequence to Render ---");
            return undefined;
        }

        for (var i = 0; i < this.SequenceLength; i++) {
            this.SequenceTime = i;
            BinarySequenceStream += this.RenderFrame(i,true);
        }

        console.log("--- Stream Rendered ---");

        return BinarySequenceStream;
    };

    this.AddEvent = function(event)
    {

        //We need to sort this on addition based on time as we could be adding in an event at any point in time.
        //eg. During playback of other events.
        UpdateUndoStack(true);

        if(mUndoGrouping == false) {
           mUndoIndex++;
        }

        mMaxUndoIndex = mUndoIndex;

        event.ActionID = mUndoIndex;

        this.Events.push(event);

        //Now we've added another event, sort to ensure they are in the correct order
        this.Events.sort(function(a,b){
            return a.StartTime - b.StartTime;
        });
    };

    this.RemoveEvent = function(atIndex)
    {
        this.Events.remove(atIndex);
    };

    this.Update = function()
    {
        if(this.Play == true)
        {
            timer += 0.8; //getFrameDelta();
            if (timer > this.SequenceLength) timer = 0.0;

            this.SequenceTime = Math.floor(timer);
        }
    };

    function getFrameDelta()
    {
        var frameDelta = 0;

        var currentTime = new Date().getTime();
        var delta = currentTime - previousTime;
        previousTime = currentTime;

        //console.log(delta);
        frameDelta = delta / (1000/FPS);

        return frameDelta;
    }

    //Used to load Objects with the right types
    function RebuildBrushData(Data)
    {
      var CleanData = [];

      if( Data ) {
	      for(var x =0; x < Object.keys(Data).length; x++)
	      {
	          if(Data[x].r != undefined && Data[x].g != undefined && Data[x].b != undefined)
	              CleanData[x] = new THREE.Color(Data[x].r,Data[x].g,Data[x].b);
	          else
	              CleanData[x] = Data[x];
	      }
      }
      return CleanData;
    }

    this.SaveSequence = function()
    {
        this.SequenceConstructionFile = {};
        this.SequenceConstructionFile.Events = [];

        //Set Sequence Properties
        this.SequenceConstructionFile.Version = this.Version;
        this.SequenceConstructionFile.SequenceLength = this.SequenceLength;

        //Add all the Events
        for(var index = 0; index < this.Events.length; index++) {

            var SequenceConstructionEvent = {};

            SequenceConstructionEvent.StartTime = this.Events[index].StartTime;
            SequenceConstructionEvent.OriginLight = this.Events[index].OriginLight;
            SequenceConstructionEvent.BrushID = this.Events[index].Brush.Index;
            SequenceConstructionEvent.BrushData = this.Events[index].BrushData;

            this.SequenceConstructionFile.Events.push(SequenceConstructionEvent);
        }
        return JSON.stringify(this.SequenceConstructionFile);
    };

    this.LoadSequence = function(JSONSequenceConstructionFile)
    {
        this.Events = [];

        var SequenceConstructionFile = JSON.parse(JSONSequenceConstructionFile);
        //Set Sequence Properties
        if(this.Version > SequenceConstructionFile.Version){
            console.log("--- Sequence Upgrade Maybe Required ---");
        }

        this.SequenceLength = SequenceConstructionFile.SequenceLength;

        //Add all the Events
        for(var index = 0; index < SequenceConstructionFile.Events.length; index++) {

            var newEvent = new EVENT(SequenceConstructionFile.Events[index].StartTime,
                                      SequenceConstructionFile.Events[index].OriginLight,
                                      Brushes[SequenceConstructionFile.Events[index].BrushID],
                                      RebuildBrushData(SequenceConstructionFile.Events[index].BrushData));
            this.AddEvent(newEvent);
        }

        console.log("--- File Loaded ---");
    };

    this.StartUndoGroup = function()
    {
        mUndoGrouping = true;
        UpdateUndoStack(true);
        mUndoIndex++;
    };
    this.StopUndoGroup = function(){mUndoGrouping = false;};

    this.Undo = function()
    {
        if(mUndoIndex > 0)
        {
            mUndoIndex--;
            UpdateUndoStack(false);
        }
    };

    this.Redo = function()
    {
        if(mUndoIndex < mMaxUndoIndex)
        {
            mUndoIndex++;
            UpdateUndoStack(false);
        }
    };

    var UpdateUndoStack = function(clearPostIndex)
    {
        var mClearPostIndex = clearPostIndex || false;
        var spliceList = [];

        //iterate through all events and remove/disable based on UndoIndex.
        for(var i = 0; i < self.Events.length; i++)
        {
            if(self.Events[i].ActionID > mUndoIndex ){
                if(mClearPostIndex == true)
                {
                    spliceList.push(i);
                    mMaxUndoIndex = mUndoIndex;
                }
                else
                {
                    self.Events[i].Enabled = false;
                }
            }
            else{
                self.Events[i].Enabled = true;
            }
        }

        //Remove all tagged events
        for(var x = 0; x < spliceList.length; x++)
        {
            self.Events.splice(spliceList[x], 1);
        }
    };

    this.ApplyCurrentData = function()
    {
        for(var i = 0; i < self.Events.length; i++)
        {
            if(self.Events[i].ActionID == mUndoIndex )
            {
                self.Events[i].ApplyData();
            }
        }
    };

};

var EVENT = function(time, originLight, brush, brushData)
{
    this.ActionID = 0;
    this.Enabled = true;
    this.IsBackground = false;
    this.StartTime = time; //Offset from the start of the sequence in frames.
    this.OriginLight = originLight; // The Light that the animation is based from.
    this.Brush = brush; // The brush that should be applied.
    this.BrushData = brushData; //The current brush data

    this.ApplyData = function()
    {
        this.BrushData = Clone(this.BrushData);
    };

    this.PrePaint = function()
    {
      if(this.Brush.PrePaint != null) this.Brush.PrePaint();
    };
    this.PostPaint = function()
    {
        if(this.Brush.PostPaint != null) this.Brush.PostPaint();
    };
    this.Render = function(CurrentFrame) // Applies brush to canvas
    {
        if (this.Brush.Render != null) this.Brush.Render(CurrentFrame, this.OriginLight, this.BrushData);
    };

    //Init
    this.init = function()
    {

    };
    this.init();
};
<|endoftext|>


<commit_before>/*jslint browser: true, eqeqeq: true, bitwise: true, newcap: true, immed: true, regexp: false */

/**
LazyLoad makes it easy and painless to lazily load one or more external
JavaScript or CSS files on demand either during or after the rendering of a web
page.

Supported browsers include Firefox 2+, IE6+, Safari 3+ (including Mobile
Safari), Google Chrome, and Opera 9+. Other browsers may or may not work and
are not officially supported.

Visit https://github.com/rgrove/lazyload/ for more info.

Copyright (c) 2011 Ryan Grove <ryan@wonko.com>
All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the 'Software'), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@module lazyload
@class LazyLoad
@static
*/

LazyLoad = (function (doc) {
  // -- Private Variables ------------------------------------------------------

  // User agent and feature test information.
  var env,

  // Reference to the  element (populated lazily).
  head,

  // Requests currently in progress, if any.
  pending = {},

  // Number of times we've polled to check whether a pending stylesheet has
  // finished loading. If this gets too high, we're probably stalled.
  pollCount = 0,

  // Queued requests.
  queue = {css: [], js: []},

  // Reference to the browser's list of stylesheets.
  styleSheets = doc.styleSheets;

  // -- Private Methods --------------------------------------------------------

  /**
  Creates and returns an HTML element with the specified name and attributes.

  @method createNode
  @param {String} name element name
  @param {Object} attrs name/value mapping of element attributes
  @return {HTMLElement}
  @private
  */
  function createNode(name, attrs) {
    var node = doc.createElement(name), attr;

    for (attr in attrs) {
      if (attrs.hasOwnProperty(attr)) {
        node.setAttribute(attr, attrs[attr]);
      }
    }

    return node;
  }

  /**
  Called when the current pending resource of the specified type has finished
  loading. Executes the associated callback (if any) and loads the next
  resource in the queue.

  @method finish
  @param {String} type resource type ('css' or 'js')
  @private
  */
  function finish(type) {
    var p = pending[type],
        callback,
        urls;

    if (p) {
      callback = p.callback;
      urls     = p.urls;

      urls.shift();
      pollCount = 0;

      // If this is the last of the pending URLs, execute the callback and
      // start the next request in the queue (if any).
      if (!urls.length) {
        callback && callback.call(p.context, p.obj);
        pending[type] = null;
        queue[type].length && load(type);
      }
    }
  }

  /**
  Populates the env variable with user agent and feature test
  information.

  @method getEnv
  @private
  */
  function getEnv() {
    var ua = navigator.userAgent;

    env = {
      // True if this browser supports disabling async mode on dynamically
      // created script nodes. See
      // http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order
      async: doc.createElement('script').async === true
    };

    (env.webkit = /AppleWebKit\//.test(ua))
      || (env.ie = /MSIE|Trident/.test(ua))
      || (env.opera = /Opera/.test(ua))
      || (env.gecko = /Gecko\//.test(ua))
      || (env.unknown = true);
  }

  /**
  Loads the specified resources, or the next resource of the specified type
  in the queue if no resources are specified. If a resource of the specified
  type is already being loaded, the new request will be queued until the
  first request has been finished.

  When an array of resource URLs is specified, those URLs will be loaded in
  parallel if it is possible to do so while preserving execution order. All
  browsers support parallel loading of CSS, but only Firefox and Opera
  support parallel loading of scripts. In other browsers, scripts will be
  queued and loaded one at a time to ensure correct execution order.

  @method load
  @param {String} type resource type ('css' or 'js')
  @param {String|Array} urls (optional) URL or array of URLs to load
  @param {Function} callback (optional) callback function to execute when the
    resource is loaded
  @param {Object} obj (optional) object to pass to the callback function
  @param {Object} context (optional) if provided, the callback function will
    be executed in this object's context
  @private
  */
  function load(type, urls, callback, obj, context) {
    var _finish = function () { finish(type); },
        isCSS   = type === 'css',
        nodes   = [],
        i, len, node, p, pendingUrls, url;

    env || getEnv();

    if (urls) {
      // If urls is a string, wrap it in an array. Otherwise assume it's an
      // array and create a copy of it so modifications won't be made to the
      // original.
      urls = typeof urls === 'string' ? [urls] : urls.concat();

      // Create a request object for each URL. If multiple URLs are specified,
      // the callback will only be executed after all URLs have been loaded.
      //
      // Sadly, Firefox and Opera are the only browsers capable of loading
      // scripts in parallel while preserving execution order. In all other
      // browsers, scripts must be loaded sequentially.
      //
      // All browsers respect CSS specificity based on the order of the link
      // elements in the DOM, regardless of the order in which the stylesheets
      // are actually downloaded.
      if (isCSS || env.async || env.gecko || env.opera) {
        // Load in parallel.
        queue[type].push({
          urls    : urls,
          callback: callback,
          obj     : obj,
          context : context
        });
      } else {
        // Load sequentially.
        for (i = 0, len = urls.length; i < len; ++i) {
          queue[type].push({
            urls    : [urls[i]],
            callback: i === len - 1 ? callback : null, // callback is only added to the last URL
            obj     : obj,
            context : context
          });
        }
      }
    }

    // If a previous load request of this type is currently in progress, we'll
    // wait our turn. Otherwise, grab the next item in the queue.
    if (pending[type] || !(p = pending[type] = queue[type].shift())) {
      return;
    }

    head || (head = doc.head || doc.getElementsByTagName('head')[0]);
    pendingUrls = p.urls;

    for (i = 0, len = pendingUrls.length; i < len; ++i) {
      url = pendingUrls[i];

      if (isCSS) {
          node = env.gecko ? createNode('style') : createNode('link', {
            href: url,
            rel : 'stylesheet'
          });
      } else {
        node = createNode('script', {src: url});
        node.async = false;
      }

      node.className = 'lazyload';
      node.setAttribute('charset', 'utf-8');

      if (env.ie && !isCSS && 'onreadystatechange' in node && !('draggable' in node)) {
        node.onreadystatechange = function () {
          if (/loaded|complete/.test(node.readyState)) {
            node.onreadystatechange = null;
            _finish();
          }
        };
      } else if (isCSS && (env.gecko || env.webkit)) {
        // Gecko and WebKit don't support the onload event on link nodes.
        if (env.webkit) {
          // In WebKit, we can poll for changes to document.styleSheets to
          // figure out when stylesheets have loaded.
          p.urls[i] = node.href; // resolve relative URLs (or polling won't work)
          pollWebKit();
        } else {
          // In Gecko, we can import the requested URL into a


<commit_before>(function() {
	var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
	var FC = $.fullCalendar;

	DayTableMixinOverride = {
		// override "FC.DayTableMixin.computeColCnt" method to add rows with resource length
		computeColCnt: function() {
			return FC.DayTableMixin.computeColCnt.apply(this) * this.view.resources.length;
		},
		// override "FC.DayTableMixin.getCellDayIndex" method to reverse col index to day index
		getCellDayIndex: function(row, col) {
			return FC.DayTableMixin.getCellDayIndex.apply(this, [row, col]) + row * this.view.resources.length;
		},
		// override "FC.DayTableMixin.getColDayIndex" method to reverse col index to day index
		getColDayIndex: function(col) {
			var dayIndex = parseInt(col / this.view.resources.length);
			if (this.isRTL) {
				dayIndex = this.daysPerRow - 1 - dayIndex;
			}
			return dayIndex;
		},
		// override "FC.DayTableMixin.renderHeadTrHtml" method to inject resource title col into table header
		renderHeadTrHtml: function() {

			return '' +
				FC.DayTableMixin.renderHeadTrHtml.apply(this) +
				'
' +
					(this.isRTL ? '' : this.renderHeadIntroHtml()) +
					this.renderHeadResourceCellsHtml() +
					(this.isRTL ? this.renderHeadIntroHtml() : '') +
				'
';
		},
		// cell renderer for resource title header
		// this method mimics the FC.DayTableMixin.renderHeadDateCellsHtml and FC.DayTableMixin.renderHeadDateCellHtml
		renderHeadResourceCellsHtml: function() {
			var htmls = [];
			var col;

			for (var col = 0; col < this.colCnt; col += this.view.resources.length) {
				date = this.getCellDate(0, col);
				for (r = 0; r < this.view.resources.length; r++) {
					htmls.push(this.renderHeadResourceCellHtml(date, this.view.resources[r]));
				}
			}

			return htmls.join('');
		},
		renderHeadResourceCellHtml: function(date, resource, colspan, otherAttrs) {
			var view = this.view;

			return '' +
				' 1 ?
						' colspan="' + colspan + '"' :
						'') +
					(otherAttrs ?
						' ' + otherAttrs :
						'') +
				'>' +
					FC.htmlEscape(resource.title) +
				'	';
		},
		// override "FC.DayTableMixin.renderHeadDateCellsHtml" method to span date cell
		renderHeadDateCellsHtml: function() {
			var htmls = [];
			var col, date;

			for (var col = 0; col < this.colCnt; col += this.view.resources.length) {
				date = this.getCellDate(0, col);
				htmls.push(this.renderHeadDateCellHtml(date, this.view.resources.length));
			}

			return htmls.join('');
		},
		// override "FC.Grid.eventSpanToSegs" method to shift col of event
		eventSpanToSegs: function(span, event, segSliceFunc) {
			var segs = FC.Grid.prototype.eventSpanToSegs.apply(this, [span, event, segSliceFunc]);

			for (var i = 0; i < segs.length; i++) {
				var resourceCol = 0;
				var seg = segs[i];
				if (seg.event && seg.event.resourceId) {
					resourceCol = this.view.resourcesById[seg.event.resourceId].__index;
				}
				seg.col = seg.col * this.view.resources.length + resourceCol;
			}
			return segs;
		},
	};
	FC.ResourceTimeGrid = FC.TimeGrid.extend({});
	FC.ResourceTimeGrid.mixin(DayTableMixinOverride);
	FC.ResourceDayGrid = FC.DayGrid.extend({});
	FC.ResourceDayGrid.mixin(DayTableMixinOverride);
	FC.ResourceView = FC.AgendaView.extend({
		resources: [],
		resourcesById: {},
		timeGridClass: FC.ResourceTimeGrid,
		dayGridClass: FC.ResourceDayGrid,
		initialize: function() {
			FC.AgendaView.prototype.initialize.apply(this, arguments);

			this.resources = this.options.resources;
			this.resourcesById = {};
			for (var r = 0; r < this.resources.length; r++) {
				if (!this.resources[r].id) {
					this.resources[r].id = r;
				}
				this.resourcesById[this.resources[r].id] = this.resources[r];
				this.resourcesById[this.resources[r].id].__index = r;
			}
		},
	});
	FC.views.resource = {
		'class': FC.ResourceView,
		defaults: {
			allDaySlot: true,
			allDayText: 'all-day',
			slotDuration: '00:30:00',
			minTime: '00:00:00',
			maxTime: '24:00:00',
			slotEventOverlap: true
		}
	};
	FC.views.resourceDay = {
		'type': 'resource',
		duration: { days: 1 }
	};
	FC.views.resourceWeek = {
		'type': 'resource',
		duration: { week: 1 }
	};
})();
<commit_msg>Changed method name<commit_after>(function() {
	var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
	var FC = $.fullCalendar;

	DayTableMixinOverride = {
		// override "FC.DayTableMixin.computeColCnt" method to add rows with resource length
		computeColCnt: function() {
			return FC.DayTableMixin.computeColCnt.apply(this) * this.view.resources.length;
		},
		// override "FC.DayTableMixin.getCellDayIndex" method to reverse col index to day index
		getCellDayIndex: function(row, col) {
			return FC.DayTableMixin.getCellDayIndex.apply(this, [row, col]) + row * this.view.resources.length;
		},
		// override "FC.DayTableMixin.getColDayIndex" method to reverse col index to day index
		getColDayIndex: function(col) {
			var dayIndex = parseInt(col / this.view.resources.length);
			if (this.isRTL) {
				dayIndex = this.daysPerRow - 1 - dayIndex;
			}
			return dayIndex;
		},
		// override "FC.DayTableMixin.renderHeadTrHtml" method to inject resource title col into table header
		renderHeadTrHtml: function() {

			return '' +
				FC.DayTableMixin.renderHeadTrHtml.apply(this) +
				'
' +
					(this.isRTL ? '' : this.renderHeadIntroHtml()) +
					this.renderResourceHeadCellsHtml() +
					(this.isRTL ? this.renderHeadIntroHtml() : '') +
				'
';
		},
		// cell renderer for resource title header
		// this method mimics the FC.DayTableMixin.renderHeadDateCellsHtml, FC.DayTableMixin.renderHeadDateCellHtml
		renderResourceHeadCellsHtml: function() {
			var htmls = [];
			var col;

			for (var col = 0; col < this.colCnt; col += this.view.resources.length) {
				date = this.getCellDate(0, col);
				for (r = 0; r < this.view.resources.length; r++) {
					htmls.push(this.renderResourceHeadCellHtml(date, this.view.resources[r]));
				}
			}

			return htmls.join('');
		},
		renderResourceHeadCellHtml: function(date, resource, colspan, otherAttrs) {
			var view = this.view;

			return '' +
				' 1 ?
						' colspan="' + colspan + '"' :
						'') +
					(otherAttrs ?
						' ' + otherAttrs :
						'') +
				'>' +
					FC.htmlEscape(resource.title) +
				'	';
		},
		// override "FC.DayTableMixin.renderHeadDateCellsHtml" method to span date cell
		renderHeadDateCellsHtml: function() {
			var htmls = [];
			var col, date;

			for (var col = 0; col < this.colCnt; col += this.view.resources.length) {
				date = this.getCellDate(0, col);
				htmls.push(this.renderHeadDateCellHtml(date, this.view.resources.length));
			}

			return htmls.join('');
		},
		// override "FC.Grid.eventSpanToSegs" method to shift col of event
		eventSpanToSegs: function(span, event, segSliceFunc) {
			var segs = FC.Grid.prototype.eventSpanToSegs.apply(this, [span, event, segSliceFunc]);

			for (var i = 0; i < segs.length; i++) {
				var resourceCol = 0;
				var seg = segs[i];
				if (seg.event && seg.event.resourceId) {
					resourceCol = this.view.resourcesById[seg.event.resourceId].__index;
				}
				seg.col = seg.col * this.view.resources.length + resourceCol;
			}
			return segs;
		},
	};
	FC.ResourceTimeGrid = FC.TimeGrid.extend({});
	FC.ResourceTimeGrid.mixin(DayTableMixinOverride);
	FC.ResourceDayGrid = FC.DayGrid.extend({});
	FC.ResourceDayGrid.mixin(DayTableMixinOverride);
	FC.ResourceView = FC.AgendaView.extend({
		resources: [],
		resourcesById: {},
		timeGridClass: FC.ResourceTimeGrid,
		dayGridClass: FC.ResourceDayGrid,
		initialize: function() {
			FC.AgendaView.prototype.initialize.apply(this, arguments);

			this.resources = this.options.resources;
			this.resourcesById = {};
			for (var r = 0; r < this.resources.length; r++) {
				if (!this.resources[r].id) {
					this.resources[r].id = r;
				}
				this.resourcesById[this.resources[r].id] = this.resources[r];
				this.resourcesById[this.resources[r].id].__index = r;
			}
		},
	});
	FC.views.resource = {
		'class': FC.ResourceView,
		defaults: {
			allDaySlot: true,
			allDayText: 'all-day',
			slotDuration: '00:30:00',
			minTime: '00:00:00',
			maxTime: '24:00:00',
			slotEventOverlap: true
		}
	};
	FC.views.resourceDay = {
		'type': 'resource',
		duration: { days: 1 }
	};
	FC.views.resourceWeek = {
		'type': 'resource',
		duration: { week: 1 }
	};
})();
<|endoftext|>


<commit_before>const _ = require('lodash')
const yamlFront = require('yaml-front-matter')
const shortcode = require('shortcode-parser')
const marked = require('marked')
marked.setOptions({
	breaks: true,
})
const hbs = require('handlebars')
const sass = require('node-sass')

const fs = require('fs-extra')
const path = require('path')

class Generator {
	constructor(rootDir) {
		this.rootDir = rootDir
		this.posts = {}
	}

	generate() {
		console.log('compiling scss')
		this.compileSCSS()
		console.log(`compiling contents`)
		this.loadShortcodes()
		this.build(this.rootDir)
		console.log('generating files')
		this.generateFiles(this.rootDir)
	}

	compileSCSS() {
		let result = sass.renderSync({
			file: path.join(this.rootDir, "_layout/style.scss"),
			outputStyle: 'compressed',
		})
		let cssPath = path.join(this.rootDir, "_book/style.css")
		fs.ensureFileSync(cssPath)
		fs.writeFileSync(cssPath, result.css)
	}

	loadShortcodes() {
		let codePath = path.join(this.rootDir, '_layout', 'shortcodes.js')
		if(fs.existsSync(codePath)) {
			let codes = require(codePath)
			Object.keys(codes).forEach(name => {
				shortcode.add(name, codes[name])
			})
		}
	}

	build(dir) {
		fs.readdirSync(dir).forEach(name => {
			let fullPath = path.join(dir, name)
			let stat = fs.statSync(fullPath)
			if(stat.isDirectory()) {
				this.build(fullPath)
			} else {
				if(path.extname(name) == '.md') {
					let post = fs.readFileSync(fullPath)
					this.posts[fullPath] = this.compile(post)
				}
			}
		})
	}

	compile(post) {
		post = yamlFront.parse(post)
		post.content = marked(shortcode.parse(post.__content))
		return post
	}

	generateFiles(dir) {
		if(path.basename(dir)[0] == '_') return

		let toc = this.buildTOC(dir)
		this.setNextPost(toc)
		fs.readdirSync(dir).forEach(name => {
			let fullPath = path.join(dir, name)
			let stat = fs.statSync(fullPath)
			if(stat.isDirectory()) {
				this.generateFiles(fullPath)
			} else {
				if(path.extname(name) == '.md') {
					let post = this.posts[fullPath]
					let layout = fs.readFileSync(post.layout ||
						path.join(this.rootDir, '_layout/page.hbs'))
						.toString()
					let html = hbs.compile(layout)(Object.assign(post, {
						toc: this.tocHTML(toc, fullPath),
					}))
					let resultPath = this.resultPath(fullPath)
					fs.ensureFileSync(resultPath)
					fs.writeFileSync(resultPath, html)
				}
			}
		})
	}

	tocHTML(toc, fullPath) {
		let generator = (toc, level) => {
			let items = toc.map(entry => {
				return [
					`<li>`,
					`<a class="${fullPath == entry.file ? "current":"normal"}" href="${entry.path}">${entry.name}</a>`,
					!_.isEmpty(entry.sub) && generator(entry.sub, level + 1) || '',
					`</li>`
				].join('\n')
			}).join('\n')
			return [
				`<ul class="toc level-${level}">`,
				items,
				`</ul>`,
			].join('\n')
		}
		return generator(toc, 0)
	}

	resultPath(fullPath) {
		let fileName = path.basename(fullPath, '.md') + '.html'
		let relDir = path.relative(this.rootDir, path.dirname(fullPath))
		return path.join(this.rootDir, '_book', relDir, fileName)
	}

	buildTOC(dir) {
		let tocPath = this.findTOCPath(dir)
		let toc = JSON.parse(fs.readFileSync(tocPath).toString())

		let parser = toc => {
			return toc.map(entry => {
				let fullPath = path.join(dir, entry)
				let relPath = path.relative(this.rootDir, fullPath)
				entry = _.isObject(entry) ? entry : {
					file: entry,
					name: this.posts[fullPath].title,
					sub: []
				}

				return {
					file: fullPath,
					path: entry.path || `/${relPath.replace(/\.[^/.]+$/, "")}`,
					name: entry.name,
					sub: parser(entry.sub)
				}
			})
		}

		return parser(toc)
	}

	findTOCPath(dir) {
		while(true) {
			let tocPath = path.join(dir, 'toc.json')
			if(fs.existsSync(tocPath)) {
				return tocPath
			}

			dir = path.join(dir, '..')
		}
	}

	setNextPost(toc) {
		toc.forEach((entry, i) => {
			if(_.isEmpty(entry.sub)) {
				if (i + 1 < toc.length) {
					this.posts[entry.file].next = toc[i+1]
				}
			} else {
				this.posts[entry.file].next = entry.sub[0]
				this.setNextPost(entry.sub)
			}
		})
	}
}

module.exports = Generator<commit_msg>Copy code.js to _book directory.<commit_after>const _ = require('lodash')
const yamlFront = require('yaml-front-matter')
const shortcode = require('shortcode-parser')
const marked = require('marked')
marked.setOptions({
	breaks: true,
})
const hbs = require('handlebars')
const sass = require('node-sass')

const fs = require('fs-extra')
const path = require('path')

class Generator {
	constructor(rootDir) {
		this.rootDir = rootDir
		this.posts = {}
	}

	generate() {
		console.log('compiling scss')
		this.compileSCSS()
		console.log('copying code.js')
		this.copyCode()
		console.log(`compiling contents`)
		this.loadShortcodes()
		this.build(this.rootDir)
		console.log('generating files')
		this.generateFiles(this.rootDir)
	}

	compileSCSS() {
		let result = sass.renderSync({
			file: path.join(this.rootDir, "_layout/style.scss"),
			outputStyle: 'compressed',
		})
		let cssPath = path.join(this.rootDir, "_book/style.css")
		fs.ensureFileSync(cssPath)
		fs.writeFileSync(cssPath, result.css)
	}

	copyCode() {
		var from = path.join(this.rootDir, "_layout/code.js")
		var to = path.join(this.rootDir, "_book/code.js")
		fs.copySync(from, to)
	}

	loadShortcodes() {
		let codePath = path.join(this.rootDir, '_layout', 'shortcodes.js')
		if(fs.existsSync(codePath)) {
			let codes = require(codePath)
			Object.keys(codes).forEach(name => {
				shortcode.add(name, codes[name])
			})
		}
	}

	build(dir) {
		fs.readdirSync(dir).forEach(name => {
			let fullPath = path.join(dir, name)
			let stat = fs.statSync(fullPath)
			if(stat.isDirectory()) {
				this.build(fullPath)
			} else {
				if(path.extname(name) == '.md') {
					let post = fs.readFileSync(fullPath)
					this.posts[fullPath] = this.compile(post)
				}
			}
		})
	}

	compile(post) {
		post = yamlFront.parse(post)
		post.content = marked(shortcode.parse(post.__content))
		return post
	}

	generateFiles(dir) {
		if(path.basename(dir)[0] == '_') return

		let toc = this.buildTOC(dir)
		this.setNextPost(toc)
		fs.readdirSync(dir).forEach(name => {
			let fullPath = path.join(dir, name)
			let stat = fs.statSync(fullPath)
			if(stat.isDirectory()) {
				this.generateFiles(fullPath)
			} else {
				if(path.extname(name) == '.md') {
					let post = this.posts[fullPath]
					let layout = fs.readFileSync(post.layout ||
						path.join(this.rootDir, '_layout/page.hbs'))
						.toString()
					let html = hbs.compile(layout)(Object.assign(post, {
						toc: this.tocHTML(toc, fullPath),
					}))
					let resultPath = this.resultPath(fullPath)
					fs.ensureFileSync(resultPath)
					fs.writeFileSync(resultPath, html)
				}
			}
		})
	}

	tocHTML(toc, fullPath) {
		let generator = (toc, level) => {
			let items = toc.map(entry => {
				return [
					`<li>`,
					`<a class="${fullPath == entry.file ? "current":"normal"}" href="${entry.path}">${entry.name}</a>`,
					!_.isEmpty(entry.sub) && generator(entry.sub, level + 1) || '',
					`</li>`
				].join('\n')
			}).join('\n')
			return [
				`<ul class="toc level-${level}">`,
				items,
				`</ul>`,
			].join('\n')
		}
		return generator(toc, 0)
	}

	resultPath(fullPath) {
		let fileName = path.basename(fullPath, '.md') + '.html'
		let relDir = path.relative(this.rootDir, path.dirname(fullPath))
		return path.join(this.rootDir, '_book', relDir, fileName)
	}

	buildTOC(dir) {
		let tocPath = this.findTOCPath(dir)
		let toc = JSON.parse(fs.readFileSync(tocPath).toString())

		let parser = toc => {
			return toc.map(entry => {
				let fullPath = path.join(dir, entry)
				let relPath = path.relative(this.rootDir, fullPath)
				entry = _.isObject(entry) ? entry : {
					file: entry,
					name: this.posts[fullPath].title,
					sub: []
				}

				return {
					file: fullPath,
					path: entry.path || `/${relPath.replace(/\.[^/.]+$/, "")}`,
					name: entry.name,
					sub: parser(entry.sub)
				}
			})
		}

		return parser(toc)
	}

	findTOCPath(dir) {
		while(true) {
			let tocPath = path.join(dir, 'toc.json')
			if(fs.existsSync(tocPath)) {
				return tocPath
			}

			dir = path.join(dir, '..')
		}
	}

	setNextPost(toc) {
		toc.forEach((entry, i) => {
			if(_.isEmpty(entry.sub)) {
				if (i + 1 < toc.length) {
					this.posts[entry.file].next = toc[i+1]
				}
			} else {
				this.posts[entry.file].next = entry.sub[0]
				this.setNextPost(entry.sub)
			}
		})
	}
}

module.exports = Generator<|endoftext|>


<commit_before>import '@storybook/addon-actions/register';
import '@storybook/addon-links/register';
import '@storybook/addon-events/register';
import '@storybook/addon-notes/register';
import '@storybook/addon-options/register';
import '@storybook/addon-knobs/register';
import '@storybook/addon-backgrounds/register';
import '@storybook/addon-a11y/register';
import '@storybook/addon-jest/register';
<commit_msg>chore<commit_after>import '@storybook/addon-actions/register';
import '@storybook/addon-links/register';
import '@storybook/addon-events/register';
import '@storybook/addon-notes/register';
import '@storybook/addon-options/register';
import '@storybook/addon-knobs/register';
import '@storybook/addon-backgrounds/register';
import '@storybook/addon-a11y/register';
import '@storybook/addon-jest/register';
import '@storybook/addon-storysource/register';
<|endoftext|>


<commit_before>import undoable from 'redux-undo'

const todo = (state, action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return {
        id: action.id,
        text: action.text,
        completed: false
      }
    case 'TOGGLE_TODO':
      if (state.id !== action.id) {
        return state
      }

      return {
        ...state,
        completed: !state.completed
      }
    default:
      return state
  }
}

const todos = (state = [], action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        todo(undefined, action)
      ]
    case 'TOGGLE_TODO':
      return state.map(t =>
        todo(t, action)
      )
    default:
      return state
  }
}

const undoableTodos = undoable(todos)

export default undoableTodos
<commit_msg>Fix example: todos-with-undo (#2788)<commit_after>import undoable, { includeAction } from 'redux-undo'

const todo = (state, action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return {
        id: action.id,
        text: action.text,
        completed: false
      }
    case 'TOGGLE_TODO':
      if (state.id !== action.id) {
        return state
      }

      return {
        ...state,
        completed: !state.completed
      }
    default:
      return state
  }
}

const todos = (state = [], action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        todo(undefined, action)
      ]
    case 'TOGGLE_TODO':
      return state.map(t =>
        todo(t, action)
      )
    default:
      return state
  }
}

const undoableTodos = undoable(todos, { filter: includeAction(['ADD_TODO', 'TOGGLE_TODO']) })

export default undoableTodos
<|endoftext|>


<commit_before>/* TranscriptSplitter v0.1 - Jean-Louis Grall - MIT License - https://github.com/jlgrall/TranscriptSplitter */

(function($, undefined) {
"use strict";

	/* Helpers */
	var Array_proto = Array.prototype,
		Array_push = Array_proto.push,
		Array_splice = Array_proto.splice,
		spliceArray = function(array, start, deleteCount, addItems) {
			var spliceArgs = [start, deleteCount];
			Array_push.apply(spliceArgs, addItems);
			return Array_splice.apply(array, spliceArgs);
		};

	/* The max line length that the user aims for: */
	var maxLength = 42;

	var getUnmodifiedLinesInText = function(text, oldText) {
			var tl = text.length,
				ol = oldText.length,
				min = Math.min(tl, ol),
				preLength = 0,
				preLines = 0,
				postLength = 0,
				postLines = 0,
				i;
			for(i = 0; i < min; i++) {
				if(text.charAt(i) !== oldText.charAt(i)) break;
				else if(text.charAt(i) === "\n") {
					preLines++;
					preLength = i + 1;
				}
			}
			if(i === min) {
				if(tl === ol || text.charAt(i) === "\n") {
					preLines++;
					preLength = i;
				}
			}
			min -= preLength;
			for(i = 0; i < min; i++) {
				if(text.charAt(tl - 1 - i) !== oldText.charAt(ol - 1 - i)) break;
				else if(text.charAt(tl - 1 - i) === "\n") {
					postLines++;
					postLength = i + 1;
				}
			}
			if(min > 0 && i === min) {
				if(text.charAt(tl - 1 - i) === "\n" && tl - 1 - i > preLength) {
					postLines++;
					postLength = i;
				}
				else if(oldText.charAt(ol - 1 - i) === "\n" && ol - 1 - i > preLength) {
					postLines++;
					postLength = i;
				}
			}
			return {
				preLength: preLength,
				preLines: preLines,
				postLength: postLength,
				postLines: postLines
			};
		},
		baseLineinfoElement = $("
??
"),
		createLineElement = function() {
			return baseLineinfoElement.clone();
		},
		updateLineElement = function(elem, length) {
			if(length === 0) elem.addClass("empty");
			else elem.removeClass("empty");
			if(length > maxLength) elem.addClass("error");
			else elem.removeClass("error");
			return elem.text(length);
		},
		createLineInfo = function(text, start, end) {
			var length = end - start;
			return {
				length: length,
				elem: null
			};
		},
		getLinesInfos = function(text, from, to) {
			var linesDescr = [],
				start = from;
			for(var i = from; i < to; i++) {
				if(text.charAt(i) === "\n") {
					linesDescr.push(createLineInfo(text, start, i));
					start = i + 1;
				}
			}
			if(i > start || start === from) linesDescr.push(createLineInfo(text, start, i));
			return linesDescr;
		},
		updateLineLengths = function(scrolledlinesDiv, linesInfos, text, oldText) {
			var unmodLines = getUnmodifiedLinesInText(text, oldText),
				hasModifiedLines = text.length !== oldText.length || unmodLines.preLength !== text.length || unmodLines.postLength !== 0;

			//console.log(unmodLines)

			if(hasModifiedLines) {
				var from = unmodLines.preLength,
					to = text.length - unmodLines.postLength,
					modifiedLinesInfos = getLinesInfos(text, from, to);

				//console.log(text.length, from, to, modifiedLinesInfos.map(function(val) { return val.length; }))

				var modifiedOldLinesNb = linesInfos.length - unmodLines.preLines - unmodLines.postLines,
					updateOldLinesNb = Math.min(modifiedOldLinesNb, modifiedLinesInfos.length),
					removeOldLinesNb = modifiedOldLinesNb - updateOldLinesNb,
					insertNewLinesNb = modifiedLinesInfos.length - updateOldLinesNb;

				var start = unmodLines.preLines;
				for(var i = 0; i < updateOldLinesNb; i++) {
					var modifiedOldLineInfos = linesInfos[start + i],
						modifiedLineInfos = modifiedLinesInfos[i];
					modifiedOldLineInfos.length = modifiedLineInfos.length;
					updateLineElement(modifiedOldLineInfos.elem, modifiedLineInfos.length);
				}
				var insertLinesInfos = modifiedLinesInfos.slice(updateOldLinesNb);
				start += updateOldLinesNb;

				for(i = 0; i < removeOldLinesNb; i++) {
					modifiedOldLineInfos = linesInfos[start + i];
					modifiedOldLineInfos.elem.remove();
				}

				if(insertNewLinesNb > 0) {
					var insertElems = [];
					for(i = 0; i < insertNewLinesNb; i++) {
						modifiedLineInfos = insertLinesInfos[i];
						var elem = updateLineElement(createLineElement(), modifiedLineInfos.length);
						modifiedLineInfos.elem = elem;
						insertElems.push(elem);
					}
					if(start === 0) scrolledlinesDiv.prepend(insertElems);
					else linesInfos[start - 1].elem.after(insertElems);
				}

				spliceArray(linesInfos, start, removeOldLinesNb, insertLinesInfos);
			}
		};

	var getCharWidthFor = function(elem) {
			var temp = $("").css({
					"display": "inline",
					"fontSize": elem.css("fontSize"),
					"fontFamily": elem.css("fontFamily"),
					"lineHeight": elem.css("lineHeight")
				}),
				tempText = ["m"];
			while(tempText.length < 200) tempText.push("m");
			temp.text(tempText.join("")).insertAfter(elem);
			var charWidth = temp.innerWidth() / 200;
			temp.remove();
			return charWidth;
		},
		setbgPos = function(textarea, bgPos, scrollLeft) {
			var arr = [];
			for(var i = 0, l = bgPos.length; i < l; i++) {
				arr.push((bgPos[i] - scrollLeft) + "px 0");
			}
			textarea.css("backgroundPosition", arr.join(","));
		},
		findCaret = function(ta) {
			return ta.selectionDirection === "forward" ? ta.selectionEnd : ta.selectionStart;
		},
		findCaretInLine = function(ta, text) {
			var caret = findCaret(ta),
				pos = text.lastIndexOf("\n", caret - 1);
			return caret - 1 - pos;
		},
		setCaretPosition = function(ta, pos) {
			return ta.selectionStart = ta.selectionEnd = pos;
		},
		findCharAroundPos = function(text, pos, _char, at) {
			for(var i = 0, l = at.length; i < l; i++) {
				if(text.charAt(pos + at[i]) === _char) return pos + at[i];
			}
			return -1;
		},
		spliceTextarea = function(ta, text, start, deleteCount, addString, caret) {
			if(addString === undefined) addString = "";
			if(caret === undefined) caret = findCaret(ta);
			if(caret >= start) {
				caret += addString.length - (caret === start ? 0 : deleteCount);
			}
			text = text.substr(0, start) + addString + text.substr(start + deleteCount);
			ta.value = text;
			setCaretPosition(ta, caret);
			return text;
		};

	var transcriptSplitter = function(textarea, options) {

			// Get the Options
			var opts = $.extend({}, $.fn.transcriptSplitter.defaults, options);

			var ta = textarea[0],
				textareaOriginalWidth = textarea.outerWidth();

			/* Turn off the wrapping of lines as we don't want to screw up the line numbers */
			textarea.attr("wrap", "off");

			/* Wrap the text area in the elements we need */
			var transsplitterwrapDiv = $("

"),
				linesDiv = $("

").appendTo(transsplitterwrapDiv),
				scrolledlinesDiv = $("

").appendTo(linesDiv),
				linedTextAreaDiv = $("

").appendTo(transsplitterwrapDiv),
				linePosDiv = $("
-1
").appendTo(transsplitterwrapDiv);

			transsplitterwrapDiv.insertAfter(textarea);
			linedTextAreaDiv.append(textarea);

			/* Positions of backgrounds relative to the characters width */
			var charWidth = getCharWidthFor(textarea),
				bgPos = [charWidth * 2 * maxLength, charWidth * maxLength];

			/* Narrow the width of textarea */
			if(opts.keepWidth) {
				var addedWidth = transsplitterwrapDiv.outerWidth() - textarea.outerWidth();
				textarea.outerWidth(textareaOriginalWidth - addedWidth);
			}

			/* Keep informations for each line */
			var oldText = "",
				linesInfos = [createLineInfo(oldText, 0, 0)],
				elem = updateLineElement(createLineElement(), 0);
			linesInfos[0].elem = elem;
			scrolledlinesDiv.prepend(elem);

			/* Event: text changes */
			var textareaLineHeight = parseInt(textarea.css("lineHeight"), 10);
			textarea.on("change keyup", function(e) {
				//var start = Date.now();
				var text = textarea.val();

				var which = e.which;
				if(e.type === "keyup" && which === 8 || which === 13 || which === 46) {	// Backspace || Return || Delete
					var caret = findCaret(ta);

					if(which === 46) which = 8;	// Delete => Backspace
					if(which === 8 && oldText.charAt(caret) === "\n") {	// Backspace
						ta.scrollTop -= textareaLineHeight;
						if(text.charAt(caret - 1) !== "\n" && caret > 0) {
							var spacePos = findCharAroundPos(text, caret, " ", [-1, 0]);
							if(spacePos === -1) {
								text = spliceTextarea(ta, text, caret, 0, " ");
							}
						}
					}
					else if(which === 13) {	// Return
						ta.scrollTop += textareaLineHeight;
						var spacePos = findCharAroundPos(text, caret, " ", [-2, 0]);
						if(spacePos !== -1) {
							text = spliceTextarea(ta, text, spacePos, 1);
						}
					}
				}

				updateLineLengths(scrolledlinesDiv, linesInfos, text, oldText);
				oldText = text;
				//console.log(Date.now() - start);
			});

			/*  */
			var checkLinePos = function() {
					var linePos = findCaretInLine(ta, textarea.val());
					if(linePos > maxLength) linePosDiv.addClass("error");
					else linePosDiv.removeClass("error");
					linePosDiv.text(linePos + "/" + maxLength);
				},
				lastSelectionStart = -1,
				lastSelectionEnd = -1,
				findLinePos_mousemove = function(e) {
					if(ta.selectionStart !== lastSelectionStart || ta.selectionEnd !== lastSelectionEnd) {
						lastSelectionStart = ta.selectionStart;
						lastSelectionEnd = ta.selectionEnd;
						checkLinePos();
					}
				};
			textarea.on("keydown click", function(e) {
				setTimeout(checkLinePos);
			}).on("mousedown", function(e) {
				textarea.on("mousemove", findLinePos_mousemove);
			}).on("mouseup", function(e) {
				textarea.off("mousemove", findLinePos_mousemove);
				lastSelectionStart = -1;
				lastSelectionEnd = -1;
			});

			/* Event scroll: make lineinfos and backgrounds scroll in sync */
			var lastScrollTop = 0,
				lastScrollLeft = 0;
			textarea.on("scroll", function(e) {
				var scrollTop = ta.scrollTop;
				if(scrollTop !== lastScrollTop) {
					scrolledlinesDiv[0].style.top = (-this.scrollTop) + "px";
					lastScrollTop = scrollLeft;
				}
				var scrollLeft = ta.scrollLeft;
				if(scrollLeft !== lastScrollLeft) {
					setbgPos(textarea, bgPos, scrollLeft);
					lastScrollLeft = scrollLeft;
				}
			});

			setbgPos(textarea, bgPos, ta.scrollLeft);
			textarea.change();
			checkLinePos();
	};

	transcriptSplitter.prototype = {
		// default options
		options: {
			keepWidth: true
		}
	};

	$.gadget("transcriptSplitter", transcriptSplitter);

})($);<commit_msg>Fix addition of a space at end of line<commit_after>/* TranscriptSplitter v0.1 - Jean-Louis Grall - MIT License - https://github.com/jlgrall/TranscriptSplitter */

(function($, undefined) {
"use strict";

	/* Helpers */
	var Array_proto = Array.prototype,
		Array_push = Array_proto.push,
		Array_splice = Array_proto.splice,
		spliceArray = function(array, start, deleteCount, addItems) {
			var spliceArgs = [start, deleteCount];
			Array_push.apply(spliceArgs, addItems);
			return Array_splice.apply(array, spliceArgs);
		};

	/* The max line length that the user aims for: */
	var maxLength = 42;

	var getUnmodifiedLinesInText = function(text, oldText) {
			var tl = text.length,
				ol = oldText.length,
				min = Math.min(tl, ol),
				preLength = 0,
				preLines = 0,
				postLength = 0,
				postLines = 0,
				i;
			for(i = 0; i < min; i++) {
				if(text.charAt(i) !== oldText.charAt(i)) break;
				else if(text.charAt(i) === "\n") {
					preLines++;
					preLength = i + 1;
				}
			}
			if(i === min) {
				if(tl === ol || text.charAt(i) === "\n") {
					preLines++;
					preLength = i;
				}
			}
			min -= preLength;
			for(i = 0; i < min; i++) {
				if(text.charAt(tl - 1 - i) !== oldText.charAt(ol - 1 - i)) break;
				else if(text.charAt(tl - 1 - i) === "\n") {
					postLines++;
					postLength = i + 1;
				}
			}
			if(min > 0 && i === min) {
				if(text.charAt(tl - 1 - i) === "\n" && tl - 1 - i > preLength) {
					postLines++;
					postLength = i;
				}
				else if(oldText.charAt(ol - 1 - i) === "\n" && ol - 1 - i > preLength) {
					postLines++;
					postLength = i;
				}
			}
			return {
				preLength: preLength,
				preLines: preLines,
				postLength: postLength,
				postLines: postLines
			};
		},
		baseLineinfoElement = $("
??
"),
		createLineElement = function() {
			return baseLineinfoElement.clone();
		},
		updateLineElement = function(elem, length) {
			if(length === 0) elem.addClass("empty");
			else elem.removeClass("empty");
			if(length > maxLength) elem.addClass("error");
			else elem.removeClass("error");
			return elem.text(length);
		},
		createLineInfo = function(text, start, end) {
			var length = end - start;
			return {
				length: length,
				elem: null
			};
		},
		getLinesInfos = function(text, from, to) {
			var linesDescr = [],
				start = from;
			for(var i = from; i < to; i++) {
				if(text.charAt(i) === "\n") {
					linesDescr.push(createLineInfo(text, start, i));
					start = i + 1;
				}
			}
			if(i > start || start === from) linesDescr.push(createLineInfo(text, start, i));
			return linesDescr;
		},
		updateLineLengths = function(scrolledlinesDiv, linesInfos, text, oldText) {
			var unmodLines = getUnmodifiedLinesInText(text, oldText),
				hasModifiedLines = text.length !== oldText.length || unmodLines.preLength !== text.length || unmodLines.postLength !== 0;

			//console.log(unmodLines)

			if(hasModifiedLines) {
				var from = unmodLines.preLength,
					to = text.length - unmodLines.postLength,
					modifiedLinesInfos = getLinesInfos(text, from, to);

				//console.log(text.length, from, to, modifiedLinesInfos.map(function(val) { return val.length; }))

				var modifiedOldLinesNb = linesInfos.length - unmodLines.preLines - unmodLines.postLines,
					updateOldLinesNb = Math.min(modifiedOldLinesNb, modifiedLinesInfos.length),
					removeOldLinesNb = modifiedOldLinesNb - updateOldLinesNb,
					insertNewLinesNb = modifiedLinesInfos.length - updateOldLinesNb;

				var start = unmodLines.preLines;
				for(var i = 0; i < updateOldLinesNb; i++) {
					var modifiedOldLineInfos = linesInfos[start + i],
						modifiedLineInfos = modifiedLinesInfos[i];
					modifiedOldLineInfos.length = modifiedLineInfos.length;
					updateLineElement(modifiedOldLineInfos.elem, modifiedLineInfos.length);
				}
				var insertLinesInfos = modifiedLinesInfos.slice(updateOldLinesNb);
				start += updateOldLinesNb;

				for(i = 0; i < removeOldLinesNb; i++) {
					modifiedOldLineInfos = linesInfos[start + i];
					modifiedOldLineInfos.elem.remove();
				}

				if(insertNewLinesNb > 0) {
					var insertElems = [];
					for(i = 0; i < insertNewLinesNb; i++) {
						modifiedLineInfos = insertLinesInfos[i];
						var elem = updateLineElement(createLineElement(), modifiedLineInfos.length);
						modifiedLineInfos.elem = elem;
						insertElems.push(elem);
					}
					if(start === 0) scrolledlinesDiv.prepend(insertElems);
					else linesInfos[start - 1].elem.after(insertElems);
				}

				spliceArray(linesInfos, start, removeOldLinesNb, insertLinesInfos);
			}
		};

	var getCharWidthFor = function(elem) {
			var temp = $("").css({
					"display": "inline",
					"fontSize": elem.css("fontSize"),
					"fontFamily": elem.css("fontFamily"),
					"lineHeight": elem.css("lineHeight")
				}),
				tempText = ["m"];
			while(tempText.length < 200) tempText.push("m");
			temp.text(tempText.join("")).insertAfter(elem);
			var charWidth = temp.innerWidth() / 200;
			temp.remove();
			return charWidth;
		},
		setbgPos = function(textarea, bgPos, scrollLeft) {
			var arr = [];
			for(var i = 0, l = bgPos.length; i < l; i++) {
				arr.push((bgPos[i] - scrollLeft) + "px 0");
			}
			textarea.css("backgroundPosition", arr.join(","));
		},
		findCaret = function(ta) {
			return ta.selectionDirection === "forward" ? ta.selectionEnd : ta.selectionStart;
		},
		findCaretInLine = function(ta, text) {
			var caret = findCaret(ta),
				pos = text.lastIndexOf("\n", caret - 1);
			return caret - 1 - pos;
		},
		setCaretPosition = function(ta, pos) {
			return ta.selectionStart = ta.selectionEnd = pos;
		},
		findCharAroundPos = function(text, pos, _char, at) {
			for(var i = 0, l = at.length; i < l; i++) {
				if(text.charAt(pos + at[i]) === _char) return pos + at[i];
			}
			return -1;
		},
		spliceTextarea = function(ta, text, start, deleteCount, addString, caret) {
			if(addString === undefined) addString = "";
			if(caret === undefined) caret = findCaret(ta);
			if(caret >= start) {
				caret += addString.length - (caret === start ? 0 : deleteCount);
			}
			text = text.substr(0, start) + addString + text.substr(start + deleteCount);
			ta.value = text;
			setCaretPosition(ta, caret);
			return text;
		};

	var transcriptSplitter = function(textarea, options) {

			// Get the Options
			var opts = $.extend({}, $.fn.transcriptSplitter.defaults, options);

			var ta = textarea[0],
				textareaOriginalWidth = textarea.outerWidth();

			/* Turn off the wrapping of lines as we don't want to screw up the line numbers */
			textarea.attr("wrap", "off");

			/* Wrap the text area in the elements we need */
			var transsplitterwrapDiv = $("

"),
				linesDiv = $("

").appendTo(transsplitterwrapDiv),
				scrolledlinesDiv = $("

").appendTo(linesDiv),
				linedTextAreaDiv = $("

").appendTo(transsplitterwrapDiv),
				linePosDiv = $("
-1
").appendTo(transsplitterwrapDiv);

			transsplitterwrapDiv.insertAfter(textarea);
			linedTextAreaDiv.append(textarea);

			/* Positions of backgrounds relative to the characters width */
			var charWidth = getCharWidthFor(textarea),
				bgPos = [charWidth * 2 * maxLength, charWidth * maxLength];

			/* Narrow the width of textarea */
			if(opts.keepWidth) {
				var addedWidth = transsplitterwrapDiv.outerWidth() - textarea.outerWidth();
				textarea.outerWidth(textareaOriginalWidth - addedWidth);
			}

			/* Keep informations for each line */
			var oldText = "",
				linesInfos = [createLineInfo(oldText, 0, 0)],
				elem = updateLineElement(createLineElement(), 0);
			linesInfos[0].elem = elem;
			scrolledlinesDiv.prepend(elem);

			/* Event: text changes */
			var textareaLineHeight = parseInt(textarea.css("lineHeight"), 10);
			textarea.on("change keyup", function(e) {
				//var start = Date.now();
				var text = textarea.val();

				var which = e.which;
				if(e.type === "keyup" && which === 8 || which === 13 || which === 46) {	// Backspace || Return || Delete
					var caret = findCaret(ta);

					if(which === 46) which = 8;	// Delete => Backspace
					if(which === 8 && oldText.charAt(caret) === "\n") {	// Backspace
						ta.scrollTop -= textareaLineHeight;
						if(text.charAt(caret - 1) !== "\n" && caret > 0) {
							var spacePos = findCharAroundPos(text, caret, " ", [-1, 0]);
							if(spacePos === -1 && text.charAt(caret) !== "\n" && caret < text.length) {
								text = spliceTextarea(ta, text, caret, 0, " ");
							}
						}
					}
					else if(which === 13) {	// Return
						ta.scrollTop += textareaLineHeight;
						var spacePos = findCharAroundPos(text, caret, " ", [-2, 0]);
						if(spacePos !== -1) {
							text = spliceTextarea(ta, text, spacePos, 1);
						}
					}
				}

				updateLineLengths(scrolledlinesDiv, linesInfos, text, oldText);
				oldText = text;
				//console.log(Date.now() - start);
			});

			/*  */
			var checkLinePos = function() {
					var linePos = findCaretInLine(ta, textarea.val());
					if(linePos > maxLength) linePosDiv.addClass("error");
					else linePosDiv.removeClass("error");
					linePosDiv.text(linePos + "/" + maxLength);
				},
				lastSelectionStart = -1,
				lastSelectionEnd = -1,
				findLinePos_mousemove = function(e) {
					if(ta.selectionStart !== lastSelectionStart || ta.selectionEnd !== lastSelectionEnd) {
						lastSelectionStart = ta.selectionStart;
						lastSelectionEnd = ta.selectionEnd;
						checkLinePos();
					}
				};
			textarea.on("keydown click", function(e) {
				setTimeout(checkLinePos);
			}).on("mousedown", function(e) {
				textarea.on("mousemove", findLinePos_mousemove);
			}).on("mouseup", function(e) {
				textarea.off("mousemove", findLinePos_mousemove);
				lastSelectionStart = -1;
				lastSelectionEnd = -1;
			});

			/* Event scroll: make lineinfos and backgrounds scroll in sync */
			var lastScrollTop = 0,
				lastScrollLeft = 0;
			textarea.on("scroll", function(e) {
				var scrollTop = ta.scrollTop;
				if(scrollTop !== lastScrollTop) {
					scrolledlinesDiv[0].style.top = (-this.scrollTop) + "px";
					lastScrollTop = scrollLeft;
				}
				var scrollLeft = ta.scrollLeft;
				if(scrollLeft !== lastScrollLeft) {
					setbgPos(textarea, bgPos, scrollLeft);
					lastScrollLeft = scrollLeft;
				}
			});

			setbgPos(textarea, bgPos, ta.scrollLeft);
			textarea.change();
			checkLinePos();
	};

	transcriptSplitter.prototype = {
		// default options
		options: {
			keepWidth: true
		}
	};

	$.gadget("transcriptSplitter", transcriptSplitter);

})($);<|endoftext|>


<commit_before>var camera, scene, renderer;
var effect, controls;
var element, container;
var meshCar;
var ceilingRoom2;
var exceleration = 0;

var loader = new THREE.JSONLoader();

var clock = new THREE.Clock();

init();
animate();

function init() {

	renderer = new THREE.WebGLRenderer();
	element = renderer.domElement;
	container = document.getElementById('example');
	container.appendChild(element);

	effect = new THREE.StereoEffect(renderer);
	scene = new THREE.Scene();

	camera = new THREE.PerspectiveCamera(90, 1, 0.001, 700);
      // launch pad start position
      camera.position.set( -0, 315, 0);
      // first room start position
      // camera.position.set( 0, 15, 0);

      // camera.position.set(0,180,170)
      scene.add(camera);

      controls = new THREE.OrbitControls(camera, element);
      controls.rotateUp(Math.PI / 4);
      controls.target.set(
      	camera.position.x + 0.1,
      	camera.position.y,
      	camera.position.z
      	);
      controls.noZoom = true;
      controls.noPan = true;

      function setOrientationControls(e) {
      	if (!e.alpha) {
      		return;
      	}

      	controls = new THREE.DeviceOrientationControls(camera, true);
      	controls.connect();
      	controls.update();

      	element.addEventListener('click', fullscreen, false);

      	window.removeEventListener('deviceorientation', setOrientationControls, true);
      }
      window.addEventListener('deviceorientation', setOrientationControls, true);

    // Adding light to the scene
      var ambiLight1 = new THREE.AmbientLight( 0x404040 ); // soft white light

      scene.add(
        light,
        ambiLight,
        directionalLight1,
        directionalLight2,
        directionalLight3,
        directionalLight4
        );

 	  // Adding objects to the scene
    scene.add(  marko,
      bao,
      ganesh,
      andrew,
      ganeshWallYW,
      andrewWallYE,
      baoWallNZ,
      markoWallZS,
      room1HallWallXW,
      room1HallWallXE,
      room1HallWallZS,
      room1HallWallZN,
      room2WallZS,
      room2WallZN,
      room2WallXW,
      room2WallXE,
      room2WallXEshort,
      room2HallWallXE,
      room2HallWallZN,
      room2HallWallZS,
      garageDoor,
      ceilingRoom1,
      ceilingRoom2,
      floor,
      meshdisk,
      dbcHole,
      launchPadFloor,
      launchPadCeiling,
      launchPadWallZN,
      launchPadWallZS,
      launchPadWallXE,
      launchPadWallXW,
      dbcWallZN,
      dbcWallZS,
      dbcWallXE,
      dbcWallXW
    );

    // Adding the car object
    loader.load('car.js', function (geometry, materials) {

      meshCar = new THREE.Mesh(
      	geometry,
      	customMaterial.carMaterial
      	);

      meshCar.scale.x = 0.2;
      meshCar.scale.y = 0.2;
      meshCar.scale.z = 0.2;

      meshCar.position.set(-90,3,92)

      meshCar.receiveShadow = true;
      meshCar.castShadow = true;

      scene.add(meshCar);
      render();
    });

    window.addEventListener('resize', resize, false);
    setTimeout(resize, 1);
  }

    function resize() {
    var width = container.offsetWidth;
    var height = container.offsetHeight;

    camera.aspect = width / height;
    camera.updateProjectionMatrix();

    renderer.setSize(width, height);
    effect.setSize(width, height);
  }

  function update(dt) {
    resize();

    camera.updateProjectionMatrix();

    controls.update(dt);
  }

  function render(dt) {
    effect.render(scene, camera);
  }

  function animate(t) {
    requestAnimationFrame(animate);

    update(clock.getDelta());
    render(clock.getDelta());

    var movementSpeed = 0.1;
    var timer = clock.getElapsedTime();
    var beginWait = 4;
    var startTimer = 10;

      // car movement
      if ((timer > (startTimer + 24)) && (timer < (startTimer + 56))) {
       meshCar.rotation.y += 0.01;
      };

      if ((timer > (startTimer + 57)) && (timer < (startTimer + 64))) {
       meshCar.position.y += 0.07;
      };

      if ((timer > (startTimer + 64)) && (timer < (startTimer + 66))) {
       meshCar.position.y += 0.07;
       meshCar.rotation.x -= 0.003

      };

      if ((timer > (startTimer + 66)) && (timer < (startTimer + 70))) {
       meshCar.position.z += 0.8;
       meshCar.position.y += 0.8;
        // meshCar.rotation.z += 0.03;
      };

      // GRAVITY
      if ((timer > (beginWait + 1)) && (timer < (beginWait +  2.84))) {
        camera.position.y -= (movementSpeed * exceleration);
        exceleration += 0.5;
      };

      // camera movement
      if ((timer > (startTimer + 1)) && (timer < (startTimer +  6.5))) {
       camera.position.x -= movementSpeed;
       camera.position.z += movementSpeed;
      };

      if ((timer > (startTimer + 6.5)) && (timer < (startTimer + 24))) {
      	camera.position.x -= movementSpeed;
        // camera.position.z += movementSpeed;
      };

      if ((timer > (startTimer + 23.9)) && (timer < (startTimer + 40))) {
        // camera.position.x -= movementSpeed;
        camera.position.z += movementSpeed;
      };

      // ceiling movement
      if ((timer > (startTimer + 43)) && (timer < (startTimer + 58))) {
        // camera.position.x -= movementSpeed;
        // camera.position.z += movementSpeed;
        ceilingRoom2.position.x -= movementSpeed;
      };

  }

  function fullscreen() {
    if (container.requestFullscreen) {
      container.requestFullscreen();
    } else if (container.msRequestFullscreen) {
      container.msRequestFullscreen();
    } else if (container.mozRequestFullScreen) {
      container.mozRequestFullScreen();
    } else if (container.webkitRequestFullscreen) {
      container.webkitRequestFullscreen();
    }
  }
<commit_msg>fall stop adjusted to camera postion<commit_after>var camera, scene, renderer;
var effect, controls;
var element, container;
var meshCar;
var ceilingRoom2;
var exceleration = 0;

var loader = new THREE.JSONLoader();

var clock = new THREE.Clock();

init();
animate();

function init() {

	renderer = new THREE.WebGLRenderer();
	element = renderer.domElement;
	container = document.getElementById('example');
	container.appendChild(element);

	effect = new THREE.StereoEffect(renderer);
	scene = new THREE.Scene();

	camera = new THREE.PerspectiveCamera(90, 1, 0.001, 700);
      // launch pad start position
      camera.position.set( -0, 315, 0);
      // first room start position
      // camera.position.set( 0, 15, 0);

      // camera.position.set(0,180,170)
      scene.add(camera);

      controls = new THREE.OrbitControls(camera, element);
      controls.rotateUp(Math.PI / 4);
      controls.target.set(
      	camera.position.x + 0.1,
      	camera.position.y,
      	camera.position.z
      	);
      controls.noZoom = true;
      controls.noPan = true;

      function setOrientationControls(e) {
      	if (!e.alpha) {
      		return;
      	}

      	controls = new THREE.DeviceOrientationControls(camera, true);
      	controls.connect();
      	controls.update();

      	element.addEventListener('click', fullscreen, false);

      	window.removeEventListener('deviceorientation', setOrientationControls, true);
      }
      window.addEventListener('deviceorientation', setOrientationControls, true);

    // Adding light to the scene
      var ambiLight1 = new THREE.AmbientLight( 0x404040 ); // soft white light

      scene.add(
        light,
        ambiLight,
        directionalLight1,
        directionalLight2,
        directionalLight3,
        directionalLight4
        );

 	  // Adding objects to the scene
    scene.add(  marko,
      bao,
      ganesh,
      andrew,
      ganeshWallYW,
      andrewWallYE,
      baoWallNZ,
      markoWallZS,
      room1HallWallXW,
      room1HallWallXE,
      room1HallWallZS,
      room1HallWallZN,
      room2WallZS,
      room2WallZN,
      room2WallXW,
      room2WallXE,
      room2WallXEshort,
      room2HallWallXE,
      room2HallWallZN,
      room2HallWallZS,
      garageDoor,
      ceilingRoom1,
      ceilingRoom2,
      floor,
      meshdisk,
      dbcHole,
      launchPadFloor,
      launchPadCeiling,
      launchPadWallZN,
      launchPadWallZS,
      launchPadWallXE,
      launchPadWallXW,
      dbcWallZN,
      dbcWallZS,
      dbcWallXE,
      dbcWallXW
    );

    // Adding the car object
    loader.load('car.js', function (geometry, materials) {

      meshCar = new THREE.Mesh(
      	geometry,
      	customMaterial.carMaterial
      	);

      meshCar.scale.x = 0.2;
      meshCar.scale.y = 0.2;
      meshCar.scale.z = 0.2;

      meshCar.position.set(-90,3,92)

      meshCar.receiveShadow = true;
      meshCar.castShadow = true;

      scene.add(meshCar);
      render();
    });

    window.addEventListener('resize', resize, false);
    setTimeout(resize, 1);
  }

    function resize() {
    var width = container.offsetWidth;
    var height = container.offsetHeight;

    camera.aspect = width / height;
    camera.updateProjectionMatrix();

    renderer.setSize(width, height);
    effect.setSize(width, height);
  }

  function update(dt) {
    resize();

    camera.updateProjectionMatrix();

    controls.update(dt);
  }

  function render(dt) {
    effect.render(scene, camera);
  }

  function animate(t) {
    requestAnimationFrame(animate);

    update(clock.getDelta());
    render(clock.getDelta());

    var movementSpeed = 0.1;
    var timer = clock.getElapsedTime();
    var beginWait = 4;
    var startTimer = 10;

      // car movement
      if ((timer > (startTimer + 24)) && (timer < (startTimer + 56))) {
       meshCar.rotation.y += 0.01;
      };

      if ((timer > (startTimer + 57)) && (timer < (startTimer + 64))) {
       meshCar.position.y += 0.07;
      };

      if ((timer > (startTimer + 64)) && (timer < (startTimer + 66))) {
       meshCar.position.y += 0.07;
       meshCar.rotation.x -= 0.003

      };

      if ((timer > (startTimer + 66)) && (timer < (startTimer + 70))) {
       meshCar.position.z += 0.8;
       meshCar.position.y += 0.8;
        // meshCar.rotation.z += 0.03;
      };

      // GRAVITY
      if ((timer > (beginWait + 1)) && (camera.position.y > 15)) {  //(timer < (beginWait +  2.84)
        camera.position.y -= (movementSpeed * exceleration);
        exceleration += 0.5;
      };

      // camera movement
      if ((timer > (startTimer + 1)) && (timer < (startTimer +  6.5))) {
       camera.position.x -= movementSpeed;
       camera.position.z += movementSpeed;
      };

      if ((timer > (startTimer + 6.5)) && (timer < (startTimer + 24))) {
      	camera.position.x -= movementSpeed;
        // camera.position.z += movementSpeed;
      };

      if ((timer > (startTimer + 23.9)) && (timer < (startTimer + 40))) {
        // camera.position.x -= movementSpeed;
        camera.position.z += movementSpeed;
      };

      // ceiling movement
      if ((timer > (startTimer + 43)) && (timer < (startTimer + 58))) {
        // camera.position.x -= movementSpeed;
        // camera.position.z += movementSpeed;
        ceilingRoom2.position.x -= movementSpeed;
      };

  }

  function fullscreen() {
    if (container.requestFullscreen) {
      container.requestFullscreen();
    } else if (container.msRequestFullscreen) {
      container.msRequestFullscreen();
    } else if (container.mozRequestFullScreen) {
      container.mozRequestFullScreen();
    } else if (container.webkitRequestFullscreen) {
      container.webkitRequestFullscreen();
    }
  }
<|endoftext|>


<commit_before>module.exports = Renderer;

var EntityManager = require('tiny-ecs').EntityManager;
var Vec2          = require('tiny-ecs').Vec2;
var Style         = require('../../lib/renderer/Style.js');
var Canvas        = require('../../lib/renderer/Canvas.js');
var Position      = require('../components/Position.js');
var Spatial       = require('../components/Spatial.js');
var LevelObject   = require('../components/LevelObject.js');

/**
 * @constructor
 * @param {EntityManager} entities
 * @param {Canvas} screen
 */
function Renderer(screen, entities)
{
  this.screen   = screen;
  this.entities = entities;
  global.renderer = this;
}

var FILTER = [Position, Spatial];

/**
 * @param {Number} dt
 * @param {Number} time
 */
Renderer.prototype.update = function(dt, time)
{
  var entities = this.entities.queryComponents(FILTER);
  var screen = this.screen;

  for (var n = 0; n < entities.length; n++) {
    var entity = entities[n];

    if (entity.levelObject) {
      switch(entity.levelObject.type) {
        case LevelObject.types.GEM:
          this.drawGem(entity);
          break;
        case LevelObject.types.PLAYER_START:
          this.drawStart(entity);
          break;
      }
    } else if (entity.colorSpirit) {
      this.drawWall(entity);
    }
  }
};

var startSize = new Vec2(25, 25);
var startStyle = new Style()
startStyle.stroke = '#fff';
startStyle.strokeWidth = 2;

Renderer.prototype.drawStart = function(entity)
{
  this.screen
    .save()
    .vtranslate(entity.position.location)
    .drawHwRect(startSize, startStyle)
    .restore();
};

Renderer.prototype.drawGem = function(entity)
{
  this.screen
    .save()
    .vtranslate(entity.position.location)
    .drawCircle(entity.spatial.hwidth.x, entity.colorSpirit.style)
    .restore();
};

Renderer.prototype.drawWall = function(entity)
{
  this.screen
    .save()
    .vtranslate(entity.position.location)
    .drawHwRect(entity.spatial.hwidth, entity.colorSpirit.style)
    .restore();
};

<commit_msg>Draw player start<commit_after>module.exports = Renderer;

var EntityManager = require('tiny-ecs').EntityManager;
var Vec2          = require('tiny-ecs').Vec2;
var Style         = require('../../lib/renderer/Style.js');
var Canvas        = require('../../lib/renderer/Canvas.js');
var Position      = require('../components/Position.js');
var Spatial       = require('../components/Spatial.js');
var LevelObject   = require('../components/LevelObject.js');
var ColorSpirit   = require('../components/ColorSpirit.js');

/**
 * @constructor
 * @param {EntityManager} entities
 * @param {Canvas} screen
 */
function Renderer(screen, entities)
{
  this.screen   = screen;
  this.entities = entities;
  global.renderer = this;
}

var COLOR_FILTER = [Position, Spatial, ColorSpirit];
var LEVEL_FILTER = [Position, LevelObject];

/**
 * @param {Number} dt
 * @param {Number} time
 */
Renderer.prototype.update = function(dt, time)
{
  this.drawColorEntities();
  this.drawLevelObjects();
};

Renderer.prototype.drawLevelObjects = function()
{
  var entities = this.entities.queryComponents(LEVEL_FILTER);
  var screen = this.screen;

  for (var n = 0; n < entities.length; n++) {
    var entity = entities[n];

    if (entity.levelObject.type === LevelObject.types.PLAYER_START)
      this.drawStart(entity);
  }
};

Renderer.prototype.drawColorEntities = function()
{
  var entities = this.entities.queryComponents(COLOR_FILTER);
  var screen = this.screen;

  for (var n = 0; n < entities.length; n++) {
    var entity = entities[n];

    if (entity.levelObject &&
      entity.levelObject.type === LevelObject.types.GEM) {
      this.drawGem(entity);
    } else {
      this.drawWall(entity);
    }
  }
};

var startSize = new Vec2(25, 25);
var startStyle = new Style()
startStyle.stroke = '#fff';
startStyle.strokeWidth = 2;

Renderer.prototype.drawStart = function(entity)
{
  this.screen
    .save()
    .vtranslate(entity.position.location)
    .drawHwRect(startSize, startStyle)
    .restore();
};

Renderer.prototype.drawGem = function(entity)
{
  this.screen
    .save()
    .vtranslate(entity.position.location)
    .drawCircle(entity.spatial.hwidth.x, entity.colorSpirit.style)
    .restore();
};

Renderer.prototype.drawWall = function(entity)
{
  this.screen
    .save()
    .vtranslate(entity.position.location)
    .drawHwRect(entity.spatial.hwidth, entity.colorSpirit.style)
    .restore();
};

<|endoftext|>


<commit_before>// ==UserScript==
// @name        Nobody gives a Fark
// @description Removes junk on Fark.com
// @date        2013-02-23
// @include     http://*.fark.com/*
// @include     http://fark.com/*
// @include     http://foobies.com/*
// @include     http://*.foobies.com/*
// @license     MIT
// @run-at      document-start
// @grant       none
// ==/UserScript==

//
// Removes Fark "featured partners" and crap like that.
//

// Add global CSS styles
// from http://diveintogreasemonkey.org/patterns/add-css.html
function addGlobalStyle(css) {
    var head, style;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}

// Removes an element given the class name.
function hideByClassName(className) {
   var elements = document.getElementsByClassName( className );
   for ( var i = 0; i < elements.length; i++ ) {
     var element = elements[i];
     element.parentNode.removeChild( element );
  }
}

// Removes an element given the ID.
function hideByID(idName) {
    var element = document.getElementById(idName);
    if ( element )
        element.parentNode.removeChild( element );
}

// Run the JS prior to page display for faster results.
window.addEventListener ('beforescriptexecute', remover, true);
function remover() {
    hideByID('header');         // No need for a header
    hideByID('BF_WIDGET_1');       // "Featured partner" sites listed with main links
    hideByID('BF_WIDGET_2');
    hideByID('boxSwap');           // Featured sites
    hideByID('alsoOnFarkTable');   // Also on Fark
    hideByID('facebook');          // Social media
    hideByID('gplus');
    hideByID('twitter');
    hideByID('pinterest');

    hideByClassName('shoprotator');         // Fark shop
    hideByClassName('BF_WIDGET');           // "Featured partner" sites (again, for safety)
    hideByClassName('alsoOnFark');          // Also on Fark header
    hideByClassName('shareLinkContainer');  // Social media
    hideByClassName('abbu');                // Inline Total Fark upsell, WTFark ads
    hideByClassName('top_right_container'); // Ad box in sidebar

    addGlobalStyle('#abPleaBar { visibility:hidden; }'); // Beg bar
    addGlobalStyle('#look_At_totalfark { display: none; }'); // TotalFark sidebar ad

    // Nuke Google Analytics and Taboola Javascript
    var scripts = document.getElementsByTagName('script');
    for ( var i = 0; i < scripts.length; i++ ) {
        if(scripts[i].getAttribute('src').indexOf('google-analytics') != -1 ||
           scripts[i].getAttribute('src').indexOf('taboola') != -1) {
          scripts[i].parentNode.removeChild(scripts[i]);
       }
    }
}

// That's it!  Any suggestions, e-mail me kthnxbye.
<commit_msg>Hide e-generator thing<commit_after>// ==UserScript==
// @name        Nobody gives a Fark
// @description Removes junk on Fark.com
// @date        2013-02-23
// @include     http://*.fark.com/*
// @include     http://fark.com/*
// @include     http://foobies.com/*
// @include     http://*.foobies.com/*
// @license     MIT
// @run-at      document-start
// @grant       none
// ==/UserScript==

//
// Removes Fark "featured partners" and crap like that.
//

// Add global CSS styles
// from http://diveintogreasemonkey.org/patterns/add-css.html
function addGlobalStyle(css) {
    var head, style;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}

// Removes an element given the class name.
function hideByClassName(className) {
   var elements = document.getElementsByClassName( className );
   for ( var i = 0; i < elements.length; i++ ) {
     var element = elements[i];
     element.parentNode.removeChild( element );
  }
}

// Removes an element given the ID.
function hideByID(idName) {
    var element = document.getElementById(idName);
    if ( element )
        element.parentNode.removeChild( element );
}

// Run the JS prior to page display for faster results.
window.addEventListener ('beforescriptexecute', remover, true);
function remover() {
    hideByID('header');         // No need for a header
    hideByID('BF_WIDGET_1');       // "Featured partner" sites listed with main links
    hideByID('BF_WIDGET_2');
    hideByID('boxSwap');           // Featured sites
    hideByID('alsoOnFarkTable');   // Also on Fark
    hideByID('facebook');          // Social media
    hideByID('gplus');
    hideByID('twitter');
    hideByID('pinterest');

    hideByClassName('shoprotator');         // Fark shop
    hideByClassName('BF_WIDGET');           // "Featured partner" sites (again, for safety)
    hideByClassName('alsoOnFark');          // Also on Fark header
    hideByClassName('shareLinkContainer');  // Social media
    hideByClassName('abbu');                // Inline Total Fark upsell, WTFark ads
    hideByClassName('top_right_container'); // Ad box in sidebar
    hideByClassName('spau');                // E-generator

    addGlobalStyle('#abPleaBar { visibility:hidden; }'); // Beg bar
    addGlobalStyle('#look_At_totalfark { display: none; }'); // TotalFark sidebar ad

    // Nuke Google Analytics and Taboola Javascript
    var scripts = document.getElementsByTagName('script');
    for ( var i = 0; i < scripts.length; i++ ) {
        if(scripts[i].getAttribute('src').indexOf('google-analytics') != -1 ||
           scripts[i].getAttribute('src').indexOf('taboola') != -1) {
          scripts[i].parentNode.removeChild(scripts[i]);
       }
    }
}

// That's it!  Any suggestions, e-mail me kthnxbye.
<|endoftext|>


<commit_before>function main(){

  var camera, scene, renderer;
  var walls;
  var container;

  var asteroids = [];
  var asteroidSpeedX = [];
  var asteroidSpeedY = [];
  var asteroidRot = [];
  var asteroidScale = [];

  init();
  update();

  function init(){

    container = document.createElement( 'div' );
    document.body.appendChild( container );

    renderer = new THREE.WebGLRenderer();
		renderer.setPixelRatio( 600/450 );
		renderer.setSize( 600, 450 );
		container.appendChild( renderer.domElement );

    //camera = new THREE.PerspectiveCamera( 60, ratio, 0.1, 1000 );
    camera = new THREE.OrthographicCamera(-300, 300, 225, -225, 0.1, 1000);
    //camera = new THREE.OrthographicCamera(-85, 85, 65, -65, 0.1, 1000);
    camera.position.z = 100;

    scene = new THREE.Scene();

    var asteroidGeo = new THREE.Geometry();
    asteroidGeo.vertices.push(
      new THREE.Vector3(0, -4, 0),
      new THREE.Vector3(-2, -2, 0),
      new THREE.Vector3(-6, -2, 0),
      new THREE.Vector3(-6, 2, 0),
      new THREE.Vector3(-2, 4, 0),
      new THREE.Vector3(-2, 6, 0),
      new THREE.Vector3(4, 6, 0),
      new THREE.Vector3(4, 2, 0),
      new THREE.Vector3(6, 0, 0),
      new THREE.Vector3(4, -4, 0),
      new THREE.Vector3(0, -4, 0)
    );

    var asteroidMat = new THREE.LineBasicMaterial({color: 0xFFFFFF});

    for (i = 0; i < 20; i++){

      asteroids[i] = new THREE.Line(asteroidGeo, asteroidMat);

      asteroids[i].position.x = Math.random() * (300 - -300) + -300;
      asteroids[i].position.y = Math.random() * (225 - -225) + -225;

      asteroids[i].rotation.z = Math.random() * 2 * 3.14;

      asteroidScale[i] = Math.random() * (5 - 1) + 1;
      asteroids[i].scale.x = asteroidScale[i];
      asteroids[i].scale.y = asteroidScale[i];

      asteroidRot[i] = Math.random() * (0.01 - -0.01) + -0.01;

      asteroidSpeedX[i] = Math.random() * (0.5 - -0.5) + -0.5;
      asteroidSpeedY[i] = Math.random() * (0.5 - -0.5) + -0.5;

      scene.add(asteroids[i]);

    }

console.log(scene);

    scene.add(asteroids[0]);
  }

  function update(){
    requestAnimationFrame(update);

    for (var i = 0; i < 20; i++){

      asteroids[i].position.x += asteroidSpeedX[i];
      asteroids[i].position.y += asteroidSpeedY[i];
      if (asteroids[i].position.x > 330 || asteroids[i].position.x < -330) {
        asteroids[i].position.x = -asteroids[i].position.x;
      }
      if (asteroids[i].position.y > 255 || asteroids[i].position.y < -255) {
        asteroids[i].position.y = -asteroids[i].position.y;
      }
      asteroids[i].rotateZ(asteroidRot[i]);
    }

    renderer.render(scene, camera);
  }

}
<commit_msg>added player and movement. started adding basic collision system<commit_after>var camera, scene, renderer;
var walls;
var container;

var keyState = [];

var numOfAsteroids = 15;
var asteroids = [];
var asteroidSpeedX = [];
var asteroidSpeedY = [];
var asteroidRot = [];
var asteroidScale = [];

var ship;

var asteroidMat = [];

function main() {
    init();
    update();
}

function init() {

    container = document.createElement('div');
    document.body.appendChild(container);

    renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio(600 / 450);
    renderer.setSize(600, 450);
    container.appendChild(renderer.domElement);

    //camera = new THREE.PerspectiveCamera( 60, ratio, 0.1, 1000 );
    camera = new THREE.OrthographicCamera(-300, 300, 225, -225, 0.1, 1000);
    //camera = new THREE.OrthographicCamera(-85, 85, 65, -65, 0.1, 1000);
    camera.position.z = 100;

    scene = new THREE.Scene();

    for (i = 0; i < 1024; i++){
        keyState[i] = false;
    }

    var asteroidGeo = new THREE.Geometry();
    asteroidGeo.vertices.push(
        new THREE.Vector3(0, -4, 0),
        new THREE.Vector3(-2, -2, 0),
        new THREE.Vector3(-6, -2, 0),
        new THREE.Vector3(-6, 2, 0),
        new THREE.Vector3(-2, 4, 0),
        new THREE.Vector3(-2, 6, 0),
        new THREE.Vector3(4, 6, 0),
        new THREE.Vector3(4, 2, 0),
        new THREE.Vector3(6, 0, 0),
        new THREE.Vector3(4, -4, 0),
        new THREE.Vector3(0, -4, 0)
    );

    var shipGeo = new THREE.Geometry();
    shipGeo.vertices.push(
        new THREE.Vector3(0, 2, 0),
        new THREE.Vector3(-1, -1, 0),
        new THREE.Vector3(0, 0, 0),
        new THREE.Vector3(1, -1, 0),
        new THREE.Vector3(0, 2, 0)
    );
    var shipMat = new THREE.LineBasicMaterial({color : 0xFFFFFF});
    ship = new THREE.Line(shipGeo, shipMat);
    ship.scale.x = 5;
    ship.scale.y = 5;
    scene.add(ship);

    for (i = 0; i < numOfAsteroids; i++) {

        asteroidMat[i] = new THREE.LineBasicMaterial({
            color: 0xFFFFFF
        });

        asteroids[i] = new THREE.Line(asteroidGeo, asteroidMat[i]);

        asteroids[i].position.x = Math.random() * (300 - -300) + -300;
        asteroids[i].position.y = Math.random() * (225 - -225) + -225;

        asteroids[i].rotation.z = Math.random() * 2 * 3.14;

        asteroidScale[i] = Math.random() * (5 - 1) + 1;
        asteroids[i].scale.x = asteroidScale[i];
        asteroids[i].scale.y = asteroidScale[i];

        asteroidRot[i] = Math.random() * (0.01 - -0.01) + -0.01;

        asteroidSpeedX[i] = Math.random() * (0.5 - -0.5) + -0.5;
        asteroidSpeedY[i] = Math.random() * (0.5 - -0.5) + -0.5;

        scene.add(asteroids[i]);

        window.addEventListener('keydown', onKeyDown, false);
        window.addEventListener('keyup', onKeyUp, false);

    }
}

function update() {
    requestAnimationFrame(update);

    movePlayer();

    for (i = 0; i < numOfAsteroids; i++) {

        asteroids[i].position.x += asteroidSpeedX[i];
        asteroids[i].position.y += asteroidSpeedY[i];
        if (asteroids[i].position.x > 330 || asteroids[i].position.x < -330) {
            asteroids[i].position.x = -asteroids[i].position.x;
        }
        if (asteroids[i].position.y > 255 || asteroids[i].position.y < -255) {
            asteroids[i].position.y = -asteroids[i].position.y;
        }
        asteroids[i].rotateZ(asteroidRot[i]);

    }

    checkCollision();

    renderer.render(scene, camera);
}

function onKeyDown(event){
    keyState[event.keyCode || event.charCode] = true;
}

function onKeyUp(event){
    keyState[event.keyCode || event.charCode] = false;
}

function movePlayer(){
    if (keyState['a'.charCodeAt(0) - 32]){
        ship.rotateZ(0.1);
    }
    if (keyState['d'.charCodeAt(0) - 32]){
        ship.rotateZ(-0.1);
    }
    if (keyState['w'.charCodeAt(0) - 32]){
        ship.translateY(2);
    }
    if (keyState['s'.charCodeAt(0) - 32]){
        ship.translateY(-2);
    }
    if (keyState[32]){
        ship.material.setValues({ color : 0xff0000 });
    }

}

function checkCollision() {
    for (i = 0; i < numOfAsteroids; i++) {
        for (j = 0; j < numOfAsteroids; j++) {
            if (j != i) {
                var dx = asteroids[i].position.x - asteroids[j].position.x;
                var dy = asteroids[i].position.y - asteroids[j].position.y;
                var distance = Math.sqrt(dx * dx + dy * dy);
                if (distance < 40) {

                    //asteroids[i].material.setValues({
                    //    color: 0xFF0000
                    //});
                    //asteroids[j].material.setValues({
                    //    color: 0xFF0000
                    //});
                    //console.log('collide');
                    //if (asteroidScale[i] > asteroidScale[j]) {
                        asteroidSpeedX[j] *= -1;
                        asteroidSpeedY[j] *= -1;
                    //} else {
                    //    asteroidSpeedX[i] *= -1;
                    //    asteroidSpeedY[i] *= -1;
                    //}

                } else {

                    asteroids[i].material.setValues({
                        color: 0xFFFFFF
                    });
                    asteroids[j].material.setValues({
                        color: 0xFFFFFF
                    });
                }
            }
        }
    }

}
<|endoftext|>