<commit_before>/*
 * server.js: OpenStack Cloud server
 *
 * (C) 2013 Charlie Robbins, Ken Perkins, Ross Kukulinski & the Contributors.
 *
 */

var util    = require('util'),
    compute = require('../../core/compute'),
    base    = require('../../core/compute/server'),
    _       = require('underscore');

var Server = exports.Server = function Server(client, details) {
  base.Server.call(this, client, details);
};

util.inherits(Server, base.Server);

Server.prototype._setProperties = function (details) {
  var self = this;
  // Set core properties
  this.id   = details.id;
  this.name = details.name;

  if (details.status) {
    switch (details.status.toUpperCase()) {
      case 'BUILD':
      case 'REBUILD':
        this.status = this.STATUS.provisioning;
        break;
      case 'ACTIVE':
        this.status = this.STATUS.running;
        break;
      case 'SUSPENDED':
      case 'SHUTOFF':
        this.status = this.STATUS.stopped;
        break;
      case 'REBOOT':
      case 'HARD_REBOOT':
        this.status = this.STATUS.reboot;
        break;
      case 'QUEUE_RESIZE':
      case 'PREP_RESIZE':
      case 'RESIZE':
      case 'VERIFY_RESIZE':
      case 'SHARE_IP':
      case 'SHARE_IP_NO_CONFIG':
      case 'DELETE_IP':
      case 'PASSWORD':
        this.status = this.STATUS.updating;
        break;
      case 'RESCUE':
      case 'ERROR':
        this.status = this.STATUS.error;
        break;
      default:
        this.status = this.STATUS.unknown;
        break;
    }
  }

  //
  // Set extra properties
  //
  this.progress  = details.progress;
  this.imageId   = details.imageId   || this.imageId;
  this.adminPass = details.adminPass || this.adminPass;
  this.addresses = details.addresses || {};
  this.metadata  = details.metadata  || {};
  this.flavorId  = details.flavorId  || this.flavorId;
  this.hostId    = details.hostId    || this.hostId;
  this.created   = details.created   || this.created;
  this.updated   = details.updated   || this.updated;
  this.original  = this.openstack = details;
  this.keyName   = details.key_name;
  this.securityGroups = details.security_groups || [];

  if (Object.keys(this.addresses).length && !this.addresses.public
    && !this.addresses.private) {
    this.addresses = Object.keys(this.addresses)
      .map(function (network) {
        return self.addresses[network];
      })
      .reduce(function (all, interfaces) {
        Object.keys(interfaces).map(function (interface) {
          return interfaces[interface].addr;
        })
        .forEach(function (addr) {
          return compute.isPrivate(addr)
            ? all['private'].push(addr)
            : all['public'].push(addr);
        });

        return all;
      }, { public: [], private: [] });
  }

  // Try to set the flavorId using a flavor object
  if (typeof this.flavorId === 'undefined' &&
      details.flavor && details.flavor.id) {
    this.flavorId = details.flavor.id;
  }

  // Try to set the imageId using an image object
  if (typeof this.imageId === 'undefined' &&
      details.image && details.image.id) {
    this.imageId = details.image.id;
  }
};

//
// Updates the addresses for this instance
// Parameters: type['public' || 'private]? callback
//
Server.prototype.getAddresses = function (type, callback) {
  if (!callback && typeof type === 'function') {
    callback = type;
    type = '';
  }

  var self = this;
  this.client.getServerAddresses(this, type, function (err, addresses) {
    if (err) {
      return callback(err);
    }

    if (type === '') {
      self.addresses = addresses;
    }
    else {
      self.addresses = addresses || {};
      self.addresses[type] = addresses[type];
    }

    callback(null, addresses);
  });
};

Server.prototype.toJSON = function() {
  return _.pick(this, ['id', 'name', 'status', 'hostId', 'adminPass', 'addresses',
    'links', 'key_name', 'imageId', 'flavorId', 'user_id', 'tenant_id', 'progress',
    'OS-EXT-STS:task_state', 'OS-EXT-STS:vm_state', 'OS-EXT-STS:power_state',
    'OS-DCF:diskConfig', 'accessIPv4', 'accessIPv6', 'config_drive', 'metadata',
    'created', 'updated', 'keyName', 'securityGroups']);
};
<commit_msg>Always push floating IP to public array<commit_after>/*
 * server.js: OpenStack Cloud server
 *
 * (C) 2013 Charlie Robbins, Ken Perkins, Ross Kukulinski & the Contributors.
 *
 */

var util    = require('util'),
    compute = require('../../core/compute'),
    base    = require('../../core/compute/server'),
    _       = require('underscore');

var Server = exports.Server = function Server(client, details) {
  base.Server.call(this, client, details);
};

util.inherits(Server, base.Server);

Server.prototype._setProperties = function (details) {
  var self = this;
  // Set core properties
  this.id   = details.id;
  this.name = details.name;

  if (details.status) {
    switch (details.status.toUpperCase()) {
      case 'BUILD':
      case 'REBUILD':
        this.status = this.STATUS.provisioning;
        break;
      case 'ACTIVE':
        this.status = this.STATUS.running;
        break;
      case 'SUSPENDED':
      case 'SHUTOFF':
        this.status = this.STATUS.stopped;
        break;
      case 'REBOOT':
      case 'HARD_REBOOT':
        this.status = this.STATUS.reboot;
        break;
      case 'QUEUE_RESIZE':
      case 'PREP_RESIZE':
      case 'RESIZE':
      case 'VERIFY_RESIZE':
      case 'SHARE_IP':
      case 'SHARE_IP_NO_CONFIG':
      case 'DELETE_IP':
      case 'PASSWORD':
        this.status = this.STATUS.updating;
        break;
      case 'RESCUE':
      case 'ERROR':
        this.status = this.STATUS.error;
        break;
      default:
        this.status = this.STATUS.unknown;
        break;
    }
  }

  //
  // Set extra properties
  //
  this.progress  = details.progress;
  this.imageId   = details.imageId   || this.imageId;
  this.adminPass = details.adminPass || this.adminPass;
  this.addresses = details.addresses || {};
  this.metadata  = details.metadata  || {};
  this.flavorId  = details.flavorId  || this.flavorId;
  this.hostId    = details.hostId    || this.hostId;
  this.created   = details.created   || this.created;
  this.updated   = details.updated   || this.updated;
  this.original  = this.openstack = details;
  this.keyName   = details.key_name;
  this.securityGroups = details.security_groups || [];

  if (Object.keys(this.addresses).length && !this.addresses.public
    && !this.addresses.private) {
    this.addresses = Object.keys(this.addresses)
      .map(function (network) {
        return self.addresses[network];
      })
      .reduce(function (all, interfaces) {
        Object.keys(interfaces).map(function (interface) {
          return {
            addr: interfaces[interface].addr,
            type: interfaces[interface]['OS-EXT-IPS:type']
          };
        })
        .forEach(function (interface) {
          return compute.isPrivate(interface.addr) && interface.type === 'fixed'
            ? all['private'].push(interface.addr)
            : all['public'].push(interface.addr);
        });

        return all;
      }, { public: [], private: [] });
  }

  // Try to set the flavorId using a flavor object
  if (typeof this.flavorId === 'undefined' &&
      details.flavor && details.flavor.id) {
    this.flavorId = details.flavor.id;
  }

  // Try to set the imageId using an image object
  if (typeof this.imageId === 'undefined' &&
      details.image && details.image.id) {
    this.imageId = details.image.id;
  }
};

//
// Updates the addresses for this instance
// Parameters: type['public' || 'private]? callback
//
Server.prototype.getAddresses = function (type, callback) {
  if (!callback && typeof type === 'function') {
    callback = type;
    type = '';
  }

  var self = this;
  this.client.getServerAddresses(this, type, function (err, addresses) {
    if (err) {
      return callback(err);
    }

    if (type === '') {
      self.addresses = addresses;
    }
    else {
      self.addresses = addresses || {};
      self.addresses[type] = addresses[type];
    }

    callback(null, addresses);
  });
};

Server.prototype.toJSON = function() {
  return _.pick(this, ['id', 'name', 'status', 'hostId', 'adminPass', 'addresses',
    'links', 'key_name', 'imageId', 'flavorId', 'user_id', 'tenant_id', 'progress',
    'OS-EXT-STS:task_state', 'OS-EXT-STS:vm_state', 'OS-EXT-STS:power_state',
    'OS-DCF:diskConfig', 'accessIPv4', 'accessIPv6', 'config_drive', 'metadata',
    'created', 'updated', 'keyName', 'securityGroups']);
};
<|endoftext|>


<commit_before>'use strict';

/**
 *  Starts the test runner which in turn loads test frameworks,
 *  assertion libraries and then executes tests.
 *
 *  Example Usage:
 *  gulp test
 *  gulp test --watch
 */

var gulp = require('gulp'),
    chalk = require('chalk'),
    args = require('yargs').argv,
    common = require('./_common');

// Attempt to load test suite package to see if it is present or not.
var testSuiteWrapper = false;
try { testSuiteWrapper = require('fe-skeleton-testsuite'); } catch(e) {}

gulp.task('test', function(done) {
    if (!testSuiteWrapper) {
        console.log(chalk.bgRed.white(' FE Skeleton: Missing `fe-skeleton-testsuite` package. Please install in `devDependencies`.'));
        done(1);
        return;
    }

    var karmaSettings = {
        configFile: common.configPath
    };

    if (args.watch) {
        karmaSettings.autoWatch = true;
        karmaSettings.singleRun = false;
    }

    testSuiteWrapper.runTests(karmaSettings, done);
});<commit_msg>Adding an easy copy/paste line that would install the FE package.<commit_after>'use strict';

/**
 *  Starts the test runner which in turn loads test frameworks,
 *  assertion libraries and then executes tests.
 *
 *  Example Usage:
 *  gulp test
 *  gulp test --watch
 */

var gulp = require('gulp'),
    chalk = require('chalk'),
    args = require('yargs').argv,
    common = require('./_common');

// Attempt to load test suite package to see if it is present or not.
var testSuiteWrapper = false;
try { testSuiteWrapper = require('fe-skeleton-testsuite'); } catch(e) {}

gulp.task('test', function(done) {
    if (!testSuiteWrapper) {
        console.log(chalk.bgRed.white(' FE Skeleton: Missing `fe-skeleton-testsuite` package. Please install in `devDependencies`.'));
        console.log(chalk.bgRed.white('              You can do so via `npm install --save-dev fe-skeleton-testsuite`.'));
        done(1);
        return;
    }

    var karmaSettings = {
        configFile: common.configPath
    };

    if (args.watch) {
        karmaSettings.autoWatch = true;
        karmaSettings.singleRun = false;
    }

    testSuiteWrapper.runTests(karmaSettings, done);
});<|endoftext|>


<commit_before>/**
 * Created by kee on 15/10/21.
 */
import axios from 'axios';
// const host = 'HTTP://localhost:3001' ;

const host = 'http://localhost:3002' ;

export default function apis({ url, method, ...others }) {
  // console.log(host + url)
  // alert(host + url)
  let AUTH_TOKEN = localStorage.getItem('token');
  // if (AUTH_TOKEN) {
  //   axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
  // }else {
  //   axios.defaults.headers.common['Authorization'] = null;
  // }
  // console.log(axios.defaults.headers.common['Authorization']);
  return axios({
    url: host + url,
    headers: {'Authorization': AUTH_TOKEN},
    method: method,
    ...others
  });
}

// export default function apisOfToken({ url, method, ...others }) {
//   others.token = localStorage.getItem('token');
//   return axios({
//     url: host + url,
//     method: method,
//     ...others
//   });
// }
<commit_msg>commit<commit_after>/**
 * Created by kee on 15/10/21.
 */
import axios from 'axios';
// const host = 'HTTP://localhost:3001' ;

const host = 'http://47.100.20.3:3002' ;

export default function apis({ url, method, ...others }) {
  // console.log(host + url)
  // alert(host + url)
  let AUTH_TOKEN = localStorage.getItem('token');
  // if (AUTH_TOKEN) {
  //   axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
  // }else {
  //   axios.defaults.headers.common['Authorization'] = null;
  // }
  // console.log(axios.defaults.headers.common['Authorization']);
  return axios({
    url: host + url,
    headers: {'Authorization': AUTH_TOKEN},
    method: method,
    ...others
  });
}

// export default function apisOfToken({ url, method, ...others }) {
//   others.token = localStorage.getItem('token');
//   return axios({
//     url: host + url,
//     method: method,
//     ...others
//   });
// }
<|endoftext|>


<commit_before>var gulp = require("gulp");
var gulpSync = require("gulp-sync")(gulp);
var path = require("path");

var wonderPackage = require("wonder-package");

var bundleDTS = wonderPackage.bundleDTS;
var compileTs = wonderPackage.compileTs;
var package = wonderPackage.package;
var format = wonderPackage.format;

var config = require("./build/gulp_task/common/config");

var tsFilePaths = config.tsFilePaths;
var tsFileDir = config.tsFileDir;
var distPath = config.distPath;
var tsconfigFile = config.tsconfigFile;
var indexFileDir = config.indexFileDir;
var glslFilePaths = config.glslFilePaths;

var createShaderChunk = require("./build/gulp_task/createInnerFile/ShaderChunk/create").createShaderChunk;

require("./build/gulp_task/clean/clean");
require("./build/gulp_task/test/test");

var generateIndex = require("wonder-tool-generate_es2015_index").generate;
var ts = require("typescript");

gulp.task("generateIndex", function(done) {
    var rootDir = path.join(process.cwd(), "src"),
        destDir = "./src/";

    generateIndex("/", rootDir, ["*.ts", "**/*.ts"], destDir, {
        target: ts.ScriptTarget.ES5,
        module: ts.ModuleKind.System
    }, {
        exclude: ["System.ts", ".d.ts", "Utils.ts"]
    });

    done();
});

gulp.task("compileTsES2015", function(done) {
    compileTs.compileTsES2015(path.join(process.cwd(), tsconfigFile), {
        sourceDir: tsFileDir,
        cwd:"/",
        targetDir:path.join(distPath, "./es2015/")
    }, done);
});

gulp.task("compileTsCommonjs", function(done) {
    compileTs.compileTsCommonjs(path.join(process.cwd(), tsconfigFile), {
        sourceDir: tsFileDir,
        cwd:"/",
        targetDir:path.join(distPath, "./commonjs/")
    }, done);
});

gulp.task("generateDTS", function(done) {
    var indexDTSPath = path.join(indexFileDir, "index.d.ts");

    bundleDTS.generateES2015DTS(indexDTSPath, "wonder.js/dist/es2015", path.join(distPath, "wd.es2015.d.ts"));
    bundleDTS.generateCommonjsDTS(indexDTSPath, "wonder.js/dist/commonjs", path.join(distPath, "wd.commonjs.d.ts"));

    done();
});

gulp.task("formatTs", function(done) {
    format.formatTs(tsFilePaths, "/", done);
});

gulp.task("createShaderChunk", function() {
    return createShaderChunk(glslFilePaths);
});

gulp.task("rollupRenderWorker", function(done) {
    package.rollup(path.join(process.cwd(), "./rollup.config.renderWorker.js"), done);
});

gulp.task("rollupNoWorker", function(done) {
    package.rollup(path.join(process.cwd(), "./rollup.config.js"), done);
});

gulp.task("rollup", gulpSync.sync(["rollupNoWorker", "rollupRenderWorker"]));

gulp.task("build", gulpSync.sync(["clean", "createShaderChunk", "generateIndex", "compileTsES2015", "compileTsCommonjs", "generateDTS", "rollup", "formatTs"]));

gulp.task("watch", function(){
    var totalPaths = tsFilePaths.concat(glslFilePaths);

    // gulp.watch(totalPaths, gulpSync.sync(["createShaderChunk", "compileTsES2015", "rollup"]));
    // gulp.watch(totalPaths, gulpSync.sync(["compileTsES2015", "rollup"]));
    gulp.watch(totalPaths, gulpSync.sync(["generateIndex", "compileTsES2015"]));
});

gulp.task("watchForTest", function(){
    var totalPaths = tsFilePaths.concat(glslFilePaths);

    gulp.watch(totalPaths, gulpSync.sync(["generateIndex", "compileTsES2015", "rollup"]));
});

gulp.task("watchForTestNoWorker", function(){
    var totalPaths = tsFilePaths.concat(glslFilePaths);

    gulp.watch(totalPaths, gulpSync.sync(["generateIndex", "createShaderChunk", "compileTsES2015", "rollupNoWorker"]));
});

gulp.task("watchForTestRenderWorker", function(){
    var totalPaths = tsFilePaths.concat(glslFilePaths);

    gulp.watch(totalPaths, gulpSync.sync(["generateIndex", "createShaderChunk", "compileTsES2015", "rollupRenderWorker"]));
});
<commit_msg>refactor: remove gulp task "watch"<commit_after>var gulp = require("gulp");
var gulpSync = require("gulp-sync")(gulp);
var path = require("path");

var wonderPackage = require("wonder-package");

var bundleDTS = wonderPackage.bundleDTS;
var compileTs = wonderPackage.compileTs;
var package = wonderPackage.package;
var format = wonderPackage.format;

var config = require("./build/gulp_task/common/config");

var tsFilePaths = config.tsFilePaths;
var tsFileDir = config.tsFileDir;
var distPath = config.distPath;
var tsconfigFile = config.tsconfigFile;
var indexFileDir = config.indexFileDir;
var glslFilePaths = config.glslFilePaths;

var createShaderChunk = require("./build/gulp_task/createInnerFile/ShaderChunk/create").createShaderChunk;

require("./build/gulp_task/clean/clean");
require("./build/gulp_task/test/test");

var generateIndex = require("wonder-tool-generate_es2015_index").generate;
var ts = require("typescript");

gulp.task("generateIndex", function(done) {
    var rootDir = path.join(process.cwd(), "src"),
        destDir = "./src/";

    generateIndex("/", rootDir, ["*.ts", "**/*.ts"], destDir, {
        target: ts.ScriptTarget.ES5,
        module: ts.ModuleKind.System
    }, {
        exclude: ["System.ts", ".d.ts", "Utils.ts"]
    });

    done();
});

gulp.task("compileTsES2015", function(done) {
    compileTs.compileTsES2015(path.join(process.cwd(), tsconfigFile), {
        sourceDir: tsFileDir,
        cwd:"/",
        targetDir:path.join(distPath, "./es2015/")
    }, done);
});

gulp.task("compileTsCommonjs", function(done) {
    compileTs.compileTsCommonjs(path.join(process.cwd(), tsconfigFile), {
        sourceDir: tsFileDir,
        cwd:"/",
        targetDir:path.join(distPath, "./commonjs/")
    }, done);
});

gulp.task("generateDTS", function(done) {
    var indexDTSPath = path.join(indexFileDir, "index.d.ts");

    bundleDTS.generateES2015DTS(indexDTSPath, "wonder.js/dist/es2015", path.join(distPath, "wd.es2015.d.ts"));
    bundleDTS.generateCommonjsDTS(indexDTSPath, "wonder.js/dist/commonjs", path.join(distPath, "wd.commonjs.d.ts"));

    done();
});

gulp.task("formatTs", function(done) {
    format.formatTs(tsFilePaths, "/", done);
});

gulp.task("createShaderChunk", function() {
    return createShaderChunk(glslFilePaths);
});

gulp.task("rollupRenderWorker", function(done) {
    package.rollup(path.join(process.cwd(), "./rollup.config.renderWorker.js"), done);
});

gulp.task("rollupNoWorker", function(done) {
    package.rollup(path.join(process.cwd(), "./rollup.config.js"), done);
});

gulp.task("rollup", gulpSync.sync(["rollupNoWorker", "rollupRenderWorker"]));

gulp.task("build", gulpSync.sync(["clean", "createShaderChunk", "generateIndex", "compileTsES2015", "compileTsCommonjs", "generateDTS", "rollup", "formatTs"]));

gulp.task("watchForTest", function(){
    var totalPaths = tsFilePaths.concat(glslFilePaths);

    gulp.watch(totalPaths, gulpSync.sync(["generateIndex", "compileTsES2015", "rollup"]));
});

gulp.task("watchForTestNoWorker", function(){
    var totalPaths = tsFilePaths.concat(glslFilePaths);

    gulp.watch(totalPaths, gulpSync.sync(["generateIndex", "createShaderChunk", "compileTsES2015", "rollupNoWorker"]));
});

gulp.task("watchForTestRenderWorker", function(){
    var totalPaths = tsFilePaths.concat(glslFilePaths);

    gulp.watch(totalPaths, gulpSync.sync(["generateIndex", "createShaderChunk", "compileTsES2015", "rollupRenderWorker"]));
});
<|endoftext|>


<commit_before>/**
 * @constructor
 */
function HypnoWingLayer(layer) {
  this.config = layer.config;

  this.scene = new THREE.Scene();
  this.camera = new THREE.PerspectiveCamera(45, 16 / 9, 1, 100);

  this.camera.position.z = 0;
  this.camera.position.y = 34;

  this.camera.lookAt(new THREE.Vector3(0,0,0));

  var light = new THREE.PointLight( 0xffffff, 1, 100 );
  light.position.set( 2, 2, 2 );
  this.scene.add(light);

  this.large_square_geom = new THREE.Geometry();
  this.create_geoms(this.large_square_geom, 11);

  this.top_material = new THREE.ShaderMaterial(SHADERS.topshader);
  this.wall_material = new THREE.ShaderMaterial(SHADERS.wallshader);

  this.create_layer(0);
  this.create_layer(-20);
  this.create_layer(-40);
  this.create_layer(-60);
  this.create_layer(-80);
  this.create_layer(-100);
  this.create_layer(-120);
  this.create_layer(-140);
  this.create_layer(-160);
  this.create_layer(-180);
  this.create_layer(-200);
  this.create_layer(-220);
  this.create_layer(-240);
  this.create_layer(-260);

  this.renderPass = new THREE.RenderPass(this.scene, this.camera);
}

// Create a full layer of squares
HypnoWingLayer.prototype.create_layer = function(y) {
 var distance = 8.485; // sqrt(6^2 + 6^2)
 var elevation = 1;
 var elevation2 = 0.5;
 var elevation3 = 1;

  // Center cube
  this.create_small(0,y+elevation,0,0);
  this.create_large(0,y,0,Math.PI/4);

  // Over, under, right left cube
  this.create_small(distance,y+elevation,0,0);
  this.create_large(distance,y+elevation2,0,Math.PI/4);

  this.create_small(-distance,y+elevation,0,0);
  this.create_large(-distance,y+elevation2,0,Math.PI/4);

  this.create_small(0,y+elevation,distance,0);
  this.create_large(0,y+elevation2,distance,Math.PI/4);

  this.create_small(0,y+elevation,-distance,0);
  this.create_large(0,y+elevation2,-distance,Math.PI/4);

  // Corner cubes
  this.create_small(distance,y+elevation,distance,0);
  this.create_large(distance,y+elevation3,distance,Math.PI/4);

  this.create_small(-distance,y+elevation,-distance,0);
  this.create_large(-distance,y+elevation3,-distance,Math.PI/4);

  this.create_small(distance,y+elevation,-distance,0);
  this.create_large(distance,y+elevation3,-distance,Math.PI/4);

  this.create_small(-distance,y+elevation,distance,0);
  this.create_large(-distance,y+elevation3,distance,Math.PI/4);
}

// Create a small cube at the desired location.
HypnoWingLayer.prototype.create_small = function(x, y, z, ry) {
  var mesh = new THREE.Mesh();

  this.create_top(mesh, this.small_square_geom, this.top_material);

  this.create_walls(mesh, 1, this.wall_material, false);
  this.create_walls(mesh, 2, this.wall_material, true);

  mesh.position.x = x;
  mesh.position.y = y;
  mesh.position.z = z;
  mesh.rotation.y = ry;

  var small_scale = 1.2;
  mesh.scale.set(small_scale, small_scale, small_scale);

  //this.scene.add(mesh);
}

// Create a large cube at the desired location.
HypnoWingLayer.prototype.create_large = function(x, y, z, ry) {
  var mesh = new THREE.Mesh();

  this.create_top(mesh, this.large_square_geom, this.top_material);

  //this.create_walls(mesh, 3, this.wall_material, false);
  //this.create_walls(mesh, 4, this.wall_material, true);

  mesh.position.x = x;
  mesh.position.y = y;
  mesh.position.z = z;
  mesh.rotation.y = ry;

  this.scene.add(mesh);
}

// Create a top
HypnoWingLayer.prototype.create_top = function(parrent, geometry, material) {
  var mesh = new THREE.Mesh( geometry, material );
  parrent.add( mesh );
}

// Create walls with an offset from the center forming a square tube facing inward or outward.
HypnoWingLayer.prototype.create_walls = function(parrent, offset, material, outer_wall) {

  var small_inner_side_geom = new THREE.PlaneGeometry(2 * offset, 2 * offset);

  var side1 = new THREE.Mesh( small_inner_side_geom, material );
  side1.position.set(0, -offset, -offset);
  side1.rotation.y = Math.PI * outer_wall;
  parrent.add( side1 );

  var side2 = new THREE.Mesh( small_inner_side_geom, material );
  side2.position.set(offset, -offset, 0);
  side2.rotation.y = Math.PI * -0.5 + Math.PI * outer_wall;
  parrent.add( side2 );

  var side3 = new THREE.Mesh( small_inner_side_geom, material );
  side3.position.set(0, -offset, offset);
  side3.rotation.y = Math.PI * 1 + Math.PI * outer_wall;
  parrent.add( side3 );

  var side4 = new THREE.Mesh( small_inner_side_geom, material );
  side4.position.set(-offset, -offset, 0);
  side4.rotation.y = Math.PI * 0.5 + Math.PI * outer_wall;
  parrent.add( side4 );
}

// Create the custom geometry for the top surfaces (square with hole)
HypnoWingLayer.prototype.create_geoms = function(geometry, size) {
  // Large square with hole
  /*this.large_square_geom = new THREE.Geometry();
  var lv0 = new THREE.Vector3(4,0,4);
  var lv1 = new THREE.Vector3(3,0,3);
  var lv2 = new THREE.Vector3(4,0,-4);
  var lv3 = new THREE.Vector3(3,0,-3);
  var lv4 = new THREE.Vector3(-4,0,4);
  var lv5 = new THREE.Vector3(-3,0,3);
  var lv6 = new THREE.Vector3(-4,0,-4);
  var lv7 = new THREE.Vector3(-3,0,-3);

  this.large_square_geom.vertices.push(lv0);
  this.large_square_geom.vertices.push(lv1);
  this.large_square_geom.vertices.push(lv2);
  this.large_square_geom.vertices.push(lv3);
  this.large_square_geom.vertices.push(lv4);
  this.large_square_geom.vertices.push(lv5);
  this.large_square_geom.vertices.push(lv6);
  this.large_square_geom.vertices.push(lv7);

  this.large_square_geom.faces.push( new THREE.Face3( 0, 2, 1 ) );
  this.large_square_geom.faces.push( new THREE.Face3( 1, 2, 3 ) );
  this.large_square_geom.faces.push( new THREE.Face3( 0, 1, 5 ) );
  this.large_square_geom.faces.push( new THREE.Face3( 0, 5, 4 ) );
  this.large_square_geom.faces.push( new THREE.Face3( 4, 5, 7 ) );
  this.large_square_geom.faces.push( new THREE.Face3( 4, 7, 6 ) );
  this.large_square_geom.faces.push( new THREE.Face3( 3, 2, 6 ) );
  this.large_square_geom.faces.push( new THREE.Face3( 3, 6, 7 ) );

  var lt0 = new THREE.Vector2( 1, 1 );
  var lt1 = new THREE.Vector2( 7/8, 7/8 );
  var lt2 = new THREE.Vector2( 1, 0 );
  var lt3 = new THREE.Vector2( 7/8, 1/8 );
  var lt4 = new THREE.Vector2( 0, 1 );
  var lt5 = new THREE.Vector2( 1/8, 7/8 );
  var lt6 = new THREE.Vector2( 0, 0 );
  var lt7 = new THREE.Vector2( 1/8, 1/8 );

  this.large_square_geom.faceVertexUvs[0][0] = [lt0, lt2, lt1];
  this.large_square_geom.faceVertexUvs[0][1] = [lt1, lt2, lt3];
  this.large_square_geom.faceVertexUvs[0][2] = [lt0, lt1, lt5];
  this.large_square_geom.faceVertexUvs[0][3] = [lt0, lt5, lt4];
  this.large_square_geom.faceVertexUvs[0][4] = [lt4, lt5, lt7];
  this.large_square_geom.faceVertexUvs[0][5] = [lt4, lt7, lt6];
  this.large_square_geom.faceVertexUvs[0][6] = [lt3, lt2, lt6];
  this.large_square_geom.faceVertexUvs[0][7] = [lt3, lt6, lt7];
*/

  var lv0 = new THREE.Vector3(0,0,0);
  var lv1 = new THREE.Vector3(0,-1,0);
  var lv2 = new THREE.Vector3(0,-10,0);
  var lv3 = new THREE.Vector3(0,-11,0);
  var lv4 = new THREE.Vector3(size,0,0);
  var lv5 = new THREE.Vector3(size-1,-1,0);
  var lv6 = new THREE.Vector3(size-1,-10,0);
  var lv7 = new THREE.Vector3(size,-11,0);

  geometry.vertices.push(lv0);
  geometry.vertices.push(lv1);
  geometry.vertices.push(lv2);
  geometry.vertices.push(lv3);
  geometry.vertices.push(lv4);
  geometry.vertices.push(lv5);
  geometry.vertices.push(lv6);
  geometry.vertices.push(lv7);

  geometry.faces.push( new THREE.Face3( 0, 4, 1 ) );
  geometry.faces.push( new THREE.Face3( 0, 4, 6 ) );
  geometry.faces.push( new THREE.Face3( 4, 7, 6 ) );
  geometry.faces.push( new THREE.Face3( 4, 5, 7 ) );
  geometry.faces.push( new THREE.Face3( 5, 3, 7 ) );
  geometry.faces.push( new THREE.Face3( 7, 3, 2 ) );
  geometry.faces.push( new THREE.Face3( 1, 6, 2 ) );
  geometry.faces.push( new THREE.Face3( 2, 6, 7 ) );

  var lt0 = new THREE.Vector2( 0, 0 );
  var lt1 = new THREE.Vector2( 0, 0.25 );
  var lt2 = new THREE.Vector2( 0, 0.75 );
  var lt3 = new THREE.Vector2( 0, 1 );
  var lt4 = new THREE.Vector2( 1, 0 );
  var lt5 = new THREE.Vector2( 0.75, 0.25 );
  var lt6 = new THREE.Vector2( 0.75, 0.75 );
  var lt7 = new THREE.Vector2( 1, 1 );

  geometry.faceVertexUvs[0][0] = [lt0, lt4, lt1];
  geometry.faceVertexUvs[0][1] = [lt0, lt4, lt6];
  geometry.faceVertexUvs[0][2] = [lt4, lt7, lt6];
  geometry.faceVertexUvs[0][3] = [lt4, lt5, lt7];
  geometry.faceVertexUvs[0][4] = [lt5, lt3, lt7];
  geometry.faceVertexUvs[0][5] = [lt7, lt3, lt2];
  geometry.faceVertexUvs[0][6] = [lt1, lt6, lt2];
  geometry.faceVertexUvs[0][7] = [lt2, lt6, lt7];

  // Planes
  //side_geom = new THREE.PlaneGeometry(2, 2);
  //this.small_outer_side_geom = new THREE.PlaneGeometry( 4, 4 );
  //this.large_inner_side_geom = new THREE.PlaneGeometry( 6, 6 );
  //this.large_outer_side_geom = new THREE.PlaneGeometry( 8, 8 );

};

HypnoWingLayer.prototype.getEffectComposerPass = function() {
  return this.renderPass;
};

HypnoWingLayer.prototype.start = function() {
};

HypnoWingLayer.prototype.end = function() {
};

HypnoWingLayer.prototype.update = function(frame) {
  this.top_material.uniforms.time.value = frame * 0;

  //this.camera.position.y = 34 - frame/20 ;

  this.wall_material.uniforms.colorA.value = new THREE.Color(19 / 255, 18 / 255, 94 / 255);
  this.wall_material.uniforms.colorB.value = new THREE.Color(208 / 255, 225 / 255, 255 / 255);
  this.wall_material.uniforms.time.value = frame;

  this.top_material.uniforms.tiles.value = 4;
  this.top_material.uniforms.time.value = frame;
};
<commit_msg>Fixed UV map<commit_after>/**
 * @constructor
 */
function HypnoWingLayer(layer) {
  this.config = layer.config;

  this.scene = new THREE.Scene();
  this.camera = new THREE.PerspectiveCamera(45, 16 / 9, 1, 100);

  this.camera.position.z = 0;
  this.camera.position.y = 34;

  this.camera.lookAt(new THREE.Vector3(0,0,0));

  var light = new THREE.PointLight( 0xffffff, 1, 100 );
  light.position.set( 2, 2, 2 );
  this.scene.add(light);

  this.large_square_geom = new THREE.Geometry();
  this.create_geoms(this.large_square_geom, 11);

  this.top_material = new THREE.ShaderMaterial(SHADERS.topshader);
  this.wall_material = new THREE.ShaderMaterial(SHADERS.wallshader);

  this.top_material = new THREE.MeshBasicMaterial( {
    color: 0xffffff,
    specular: 0x050505,
    shininess: 100,
    map: Loader.loadTexture('res/' + 'UV-testmap.jpg'),
    opacity: 1.0, transparent: false
  } );

  this.create_layer(0);
  this.create_layer(-20);
  this.create_layer(-40);
  this.create_layer(-60);
  this.create_layer(-80);
  this.create_layer(-100);
  this.create_layer(-120);
  this.create_layer(-140);
  this.create_layer(-160);
  this.create_layer(-180);
  this.create_layer(-200);
  this.create_layer(-220);
  this.create_layer(-240);
  this.create_layer(-260);

  this.renderPass = new THREE.RenderPass(this.scene, this.camera);
}

// Create a full layer of squares
HypnoWingLayer.prototype.create_layer = function(y) {
 var distance = 8.485; // sqrt(6^2 + 6^2)
 var elevation = 1;
 var elevation2 = 0.5;
 var elevation3 = 1;

  // Center cube
  this.create_small(0,y+elevation,0,0);
  this.create_large(0,y,0,Math.PI/4);

  // Over, under, right left cube
  this.create_small(distance,y+elevation,0,0);
  this.create_large(distance,y+elevation2,0,Math.PI/4);

  this.create_small(-distance,y+elevation,0,0);
  this.create_large(-distance,y+elevation2,0,Math.PI/4);

  this.create_small(0,y+elevation,distance,0);
  this.create_large(0,y+elevation2,distance,Math.PI/4);

  this.create_small(0,y+elevation,-distance,0);
  this.create_large(0,y+elevation2,-distance,Math.PI/4);

  // Corner cubes
  this.create_small(distance,y+elevation,distance,0);
  this.create_large(distance,y+elevation3,distance,Math.PI/4);

  this.create_small(-distance,y+elevation,-distance,0);
  this.create_large(-distance,y+elevation3,-distance,Math.PI/4);

  this.create_small(distance,y+elevation,-distance,0);
  this.create_large(distance,y+elevation3,-distance,Math.PI/4);

  this.create_small(-distance,y+elevation,distance,0);
  this.create_large(-distance,y+elevation3,distance,Math.PI/4);
}

// Create a small cube at the desired location.
HypnoWingLayer.prototype.create_small = function(x, y, z, ry) {
  var mesh = new THREE.Mesh();

  this.create_top(mesh, this.small_square_geom, this.top_material);

  this.create_walls(mesh, 1, this.wall_material, false);
  this.create_walls(mesh, 2, this.wall_material, true);

  mesh.position.x = x;
  mesh.position.y = y;
  mesh.position.z = z;
  mesh.rotation.y = ry;

  var small_scale = 1.2;
  mesh.scale.set(small_scale, small_scale, small_scale);

  //this.scene.add(mesh);
}

// Create a large cube at the desired location.
HypnoWingLayer.prototype.create_large = function(x, y, z, ry) {
  var mesh = new THREE.Mesh();

  this.create_top(mesh, this.large_square_geom, this.top_material);

  //this.create_walls(mesh, 3, this.wall_material, false);
  //this.create_walls(mesh, 4, this.wall_material, true);

  mesh.position.x = x;
  mesh.position.y = y;
  mesh.position.z = z;
  mesh.rotation.y = ry;

  this.scene.add(mesh);
}

// Create a top
HypnoWingLayer.prototype.create_top = function(parrent, geometry, material) {
  var mesh = new THREE.Mesh( geometry, material );
  parrent.add( mesh );
}

// Create walls with an offset from the center forming a square tube facing inward or outward.
HypnoWingLayer.prototype.create_walls = function(parrent, offset, material, outer_wall) {

  var small_inner_side_geom = new THREE.PlaneGeometry(2 * offset, 2 * offset);

  var side1 = new THREE.Mesh( small_inner_side_geom, material );
  side1.position.set(0, -offset, -offset);
  side1.rotation.y = Math.PI * outer_wall;
  parrent.add( side1 );

  var side2 = new THREE.Mesh( small_inner_side_geom, material );
  side2.position.set(offset, -offset, 0);
  side2.rotation.y = Math.PI * -0.5 + Math.PI * outer_wall;
  parrent.add( side2 );

  var side3 = new THREE.Mesh( small_inner_side_geom, material );
  side3.position.set(0, -offset, offset);
  side3.rotation.y = Math.PI * 1 + Math.PI * outer_wall;
  parrent.add( side3 );

  var side4 = new THREE.Mesh( small_inner_side_geom, material );
  side4.position.set(-offset, -offset, 0);
  side4.rotation.y = Math.PI * 0.5 + Math.PI * outer_wall;
  parrent.add( side4 );
}

// Create the custom geometry for the top surfaces (square with hole)
HypnoWingLayer.prototype.create_geoms = function(geometry, size) {
  // Large square with hole
  /*this.large_square_geom = new THREE.Geometry();
  var lv0 = new THREE.Vector3(4,0,4);
  var lv1 = new THREE.Vector3(3,0,3);
  var lv2 = new THREE.Vector3(4,0,-4);
  var lv3 = new THREE.Vector3(3,0,-3);
  var lv4 = new THREE.Vector3(-4,0,4);
  var lv5 = new THREE.Vector3(-3,0,3);
  var lv6 = new THREE.Vector3(-4,0,-4);
  var lv7 = new THREE.Vector3(-3,0,-3);

  this.large_square_geom.vertices.push(lv0);
  this.large_square_geom.vertices.push(lv1);
  this.large_square_geom.vertices.push(lv2);
  this.large_square_geom.vertices.push(lv3);
  this.large_square_geom.vertices.push(lv4);
  this.large_square_geom.vertices.push(lv5);
  this.large_square_geom.vertices.push(lv6);
  this.large_square_geom.vertices.push(lv7);

  this.large_square_geom.faces.push( new THREE.Face3( 0, 2, 1 ) );
  this.large_square_geom.faces.push( new THREE.Face3( 1, 2, 3 ) );
  this.large_square_geom.faces.push( new THREE.Face3( 0, 1, 5 ) );
  this.large_square_geom.faces.push( new THREE.Face3( 0, 5, 4 ) );
  this.large_square_geom.faces.push( new THREE.Face3( 4, 5, 7 ) );
  this.large_square_geom.faces.push( new THREE.Face3( 4, 7, 6 ) );
  this.large_square_geom.faces.push( new THREE.Face3( 3, 2, 6 ) );
  this.large_square_geom.faces.push( new THREE.Face3( 3, 6, 7 ) );

  var lt0 = new THREE.Vector2( 1, 1 );
  var lt1 = new THREE.Vector2( 7/8, 7/8 );
  var lt2 = new THREE.Vector2( 1, 0 );
  var lt3 = new THREE.Vector2( 7/8, 1/8 );
  var lt4 = new THREE.Vector2( 0, 1 );
  var lt5 = new THREE.Vector2( 1/8, 7/8 );
  var lt6 = new THREE.Vector2( 0, 0 );
  var lt7 = new THREE.Vector2( 1/8, 1/8 );

  this.large_square_geom.faceVertexUvs[0][0] = [lt0, lt2, lt1];
  this.large_square_geom.faceVertexUvs[0][1] = [lt1, lt2, lt3];
  this.large_square_geom.faceVertexUvs[0][2] = [lt0, lt1, lt5];
  this.large_square_geom.faceVertexUvs[0][3] = [lt0, lt5, lt4];
  this.large_square_geom.faceVertexUvs[0][4] = [lt4, lt5, lt7];
  this.large_square_geom.faceVertexUvs[0][5] = [lt4, lt7, lt6];
  this.large_square_geom.faceVertexUvs[0][6] = [lt3, lt2, lt6];
  this.large_square_geom.faceVertexUvs[0][7] = [lt3, lt6, lt7];
*/

  var lv0 = new THREE.Vector3(0,0,0);
  var lv1 = new THREE.Vector3(0,-1,0);
  var lv2 = new THREE.Vector3(0,-10,0);
  var lv3 = new THREE.Vector3(0,-11,0);
  var lv4 = new THREE.Vector3(size,0,0);
  var lv6 = new THREE.Vector3(size-1,-1,0);
  var lv7 = new THREE.Vector3(size-1,-10,0);
  var lv5 = new THREE.Vector3(size,-11,0);

  geometry.vertices.push(lv0);
  geometry.vertices.push(lv1);
  geometry.vertices.push(lv2);
  geometry.vertices.push(lv3);
  geometry.vertices.push(lv4);
  geometry.vertices.push(lv5);
  geometry.vertices.push(lv6);
  geometry.vertices.push(lv7);

  geometry.faces.push( new THREE.Face3( 0, 6, 1 ) );
  geometry.faces.push( new THREE.Face3( 0, 4, 6 ) );
  geometry.faces.push( new THREE.Face3( 4, 7, 6 ) );
  geometry.faces.push( new THREE.Face3( 4, 5, 7 ) );
  geometry.faces.push( new THREE.Face3( 5, 3, 7 ) );
  geometry.faces.push( new THREE.Face3( 7, 3, 2 ) );
  geometry.faces.push( new THREE.Face3( 1, 6, 2 ) );
  geometry.faces.push( new THREE.Face3( 2, 6, 7 ) );

  var lt0 = new THREE.Vector2( 0, 0 );
  var lt1 = new THREE.Vector2( 0, 0.25 );
  var lt2 = new THREE.Vector2( 0, 0.75 );
  var lt3 = new THREE.Vector2( 0, 1 );
  var lt4 = new THREE.Vector2( 1, 0 );
  var lt6 = new THREE.Vector2( 0.75, 0.25 );
  var lt7 = new THREE.Vector2( 0.75, 0.75 );
  var lt5 = new THREE.Vector2( 1, 1 );

  geometry.faceVertexUvs[0][0] = [lt0, lt6, lt1];
  geometry.faceVertexUvs[0][1] = [lt0, lt4, lt6];
  geometry.faceVertexUvs[0][2] = [lt4, lt7, lt6];
  geometry.faceVertexUvs[0][3] = [lt4, lt5, lt7];
  geometry.faceVertexUvs[0][4] = [lt5, lt3, lt7];
  geometry.faceVertexUvs[0][5] = [lt7, lt3, lt2];
  geometry.faceVertexUvs[0][6] = [lt1, lt6, lt2];
  geometry.faceVertexUvs[0][7] = [lt2, lt6, lt7];

  // Planes
  //side_geom = new THREE.PlaneGeometry(2, 2);
  //this.small_outer_side_geom = new THREE.PlaneGeometry( 4, 4 );
  //this.large_inner_side_geom = new THREE.PlaneGeometry( 6, 6 );
  //this.large_outer_side_geom = new THREE.PlaneGeometry( 8, 8 );

};

HypnoWingLayer.prototype.getEffectComposerPass = function() {
  return this.renderPass;
};

HypnoWingLayer.prototype.start = function() {
};

HypnoWingLayer.prototype.end = function() {
};

HypnoWingLayer.prototype.update = function(frame) {
  //this.top_material.uniforms.time.value = frame * 0;

  //this.camera.position.y = 34 - frame/20 ;

  this.wall_material.uniforms.colorA.value = new THREE.Color(19 / 255, 18 / 255, 94 / 255);
  this.wall_material.uniforms.colorB.value = new THREE.Color(208 / 255, 225 / 255, 255 / 255);
  this.wall_material.uniforms.time.value = frame;

  //this.top_material.uniforms.tiles.value = 4;
  //this.top_material.uniforms.time.value = frame;
};
<|endoftext|>


<commit_before>'use strict';

var readFileSync = require('fs').readFileSync;

var assign = require('lodash.assign');

var gulp = require('gulp');
var gulpif = require('gulp-if');
var rename = require('gulp-rename');
var util = require('gulp-util');
var vinylSource = require('vinyl-source-stream');
var vinylBuffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var typescript = require('gulp-typescript');
var sass = require('gulp-sass');
var htmlmin = require('gulp-htmlmin');
var cssmin = require('gulp-cssmin');
var connect = require('gulp-connect');
var concat = require('gulp-concat');
var inlineNg2Template = require('gulp-inline-ng2-template');

var rev = require('gulp-rev');
var revReplace = require('gulp-rev-replace');

var del = require('del');

var sequence = require('run-sequence');

var production = false;
var webserver = false;

var htmlminOpt = {
  collapseWhitespace: true,
  conservativeCollapse: true,
  removeComments: true,
  removeCommentsFromCDATA: true,
  caseSensitive: true,
  minifyJS: true,
  minifyCSS: true,
  minifyURLs: true
}

var tsOpt= {
  target: "es5",
  module: "system",
  moduleResolution: "node",
  emitDecoratorMetadata: true,
  experimentalDecorators: true,
  noImplicitAny: true,
  removeComments: true,
  outFile: 'bundle.js',
  rootDir: 'ts',
  typescript: require('typescript')
}

var depList = [
  'lib/fix.js',
  'lib/material.min.js',
  'node_modules/es6-shim/es6-shim.js',
  'node_modules/systemjs/dist/system-polyfills.js',
  'node_modules/angular2/bundles/angular2-polyfills.min.js',
  'node_modules/systemjs/dist/system.js',
  'node_modules/rxjs/bundles/Rx.js',
  'node_modules/angular2/bundles/angular2.dev.js', // Minified version is broken
  'node_modules/angular2/bundles/router.dev.js',
  'node_modules/angular2/bundles/http.dev.js'
];

var fontList = [
  'node_modules/material-design-icons/iconfont/MaterialIcons-Regular.eot',
  'node_modules/material-design-icons/iconfont/MaterialIcons-Regular.woff',
  'node_modules/material-design-icons/iconfont/MaterialIcons-Regular.woff2',
  'node_modules/material-design-icons/iconfont/MaterialIcons-Regular.ttf',
];

var tsProject = typescript.createProject(tsOpt);

function buildjs(bundler) {
  return gulp.src(['./typings/browser.d.ts','./ts/**/*.ts', '!./ts/config.example.ts'])
      .on('error', util.log)
      .pipe(inlineNg2Template({ base: '/html' })) // Currently doesn't support source maps
      .pipe(sourcemaps.init())
      .pipe(typescript(tsProject))
      .pipe(gulpif(production, uglify({mangle: false})))
      .pipe(gulpif(!production, sourcemaps.write('./')))
      .pipe(rev())
      .pipe(gulp.dest('./build/js'))
      .pipe(rev.manifest({
        path: './build/rev-manifest.json',
        base: './build',
        merge: true
      }))
      .pipe(gulp.dest('./build'));
};

function buildcss() {
  return gulp.src('./sass/**/*.scss')
      .on('error', util.log)
      .pipe(sourcemaps.init())
      .pipe(sass().on('error', sass.logError))
      .pipe(gulp.src('./lib/*.css', {passthrough: true}))
      .pipe(concat('main.css'))
      .pipe(gulpif(production, cssmin()))
      .pipe(gulpif(!production, sourcemaps.write('./')))
      .pipe(rev())
      .pipe(gulp.dest('./build/css'))
      .pipe(rev.manifest({
        path: './build/rev-manifest.json',
        base: './build',
        merge: true
      }))
      .pipe(gulp.dest('./build'));
};

function builddep() {
  return gulp.src(depList)
      .pipe(concat({path: './bundle-dep.js', cwd: ''}))
      .pipe(gulpif(production, uglify({mangle: false})))
      .pipe(rev())
      .pipe(gulp.dest('./build/js'))
      .pipe(rev.manifest({
        path: './build/rev-manifest.json',
        base: './build',
        merge: true
      }))
      .pipe(gulp.dest('./build'));
}

function buildfont() {
  return gulp.src(fontList)
      .pipe(rev())
      .pipe(gulp.dest('./build/fonts'))
      .pipe(rev.manifest({
        path: './build/rev-manifest.json',
        base: './build',
        merge: true
      }))
      .pipe(gulp.dest('./build'));
}

function buildrev() {
  function replaceMap(filename) {
    if(filename.indexOf('.map') > -1) {
      return filename.replace(/.*\//g, '');
    } else return filename;
  }
  return gulp.src(['./build/**/*.*', '!./build/rev-manifest.json'])
      .pipe(revReplace({
        manifest: gulp.src('./build/rev-manifest.json'),
        modifiedUnreved: replaceMap,
        modifiedReved: replaceMap
      }))
      .pipe(gulp.dest('./dist'))
      .pipe(gulpif(webserver, connect.reload()));
}

gulp.task('prebuild:production', function(done) {
  production = true;
  done();
});

gulp.task('clean', function() {
  return del(['dist', 'build']);
});

gulp.task('clean:js', function() {
  return del(['dist/js/**/*.*', '!dist/js/bundle-dep-*.*', 'build/js/**/*.*', '!build/js/bundle-dep-*.*']);
});

gulp.task('clean:css', function() {
  return del(['dist/css', 'build/css']);
});

gulp.task('clean:dep', function() {
  return del('dist/js/bundle-dep-*.*', 'build/js/bundle-dep-*.*');
});

gulp.task('clean:font', function() {
  return del('dist/fonts/**/*.*', 'build/fonts/**/*.*');
});

gulp.task('clean:index', function() {
  return del('dist/index.html');
});

gulp.task('build:js', gulp.series('clean:js', buildjs));
gulp.task('build:css', gulp.series('clean:css', buildcss));
gulp.task('build:dep', gulp.series('clean:dep', builddep));
gulp.task('build:font', gulp.series('clean:font', buildfont));
gulp.task('build:index', gulp.series('clean:index', function() {
  return gulp.src('./html/index.html')
      .pipe(gulp.dest('./build'));
}));
gulp.task('build:rev', gulp.series(buildrev));

gulp.task('build', gulp.series(gulp.series('build:font', 'build:dep', 'build:js', 'build:css', 'build:index'), 'build:rev'));
gulp.task('build:production', gulp.series('prebuild:production', 'build'));
gulp.task('watch', gulp.series('build', function(done) {
  gulp.watch(['./ts/**/*.ts', './html/views/**/*.html', './html/tmpl/**/*.html'], gulp.series('build:js', 'build:rev'));
  gulp.watch('./sass/**/*.scss', gulp.series('build:css', 'build:rev'));
  gulp.watch('./html/index.html', gulp.series('build:index', 'build:rev'));
  done();
}));

gulp.task('webserver', function(done) {
  webserver = true;
  connect.server({
    root: 'dist',
    port: 3001,
    livereload: true,
    fallback: 'dist/index.html',
    debug: true
  });
  done();
});

gulp.task('default', gulp.series('watch', 'webserver'));
<commit_msg>Fixed typo<commit_after>'use strict';

var readFileSync = require('fs').readFileSync;

var assign = require('lodash.assign');

var gulp = require('gulp');
var gulpif = require('gulp-if');
var rename = require('gulp-rename');
var util = require('gulp-util');
var vinylSource = require('vinyl-source-stream');
var vinylBuffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var typescript = require('gulp-typescript');
var sass = require('gulp-sass');
var htmlmin = require('gulp-htmlmin');
var cssmin = require('gulp-cssmin');
var connect = require('gulp-connect');
var concat = require('gulp-concat');
var inlineNg2Template = require('gulp-inline-ng2-template');

var rev = require('gulp-rev');
var revReplace = require('gulp-rev-replace');

var del = require('del');

var sequence = require('run-sequence');

var production = false;
var webserver = false;

var htmlminOpt = {
  collapseWhitespace: true,
  conservativeCollapse: true,
  removeComments: true,
  removeCommentsFromCDATA: true,
  caseSensitive: true,
  minifyJS: true,
  minifyCSS: true,
  minifyURLs: true
}

var tsOpt= {
  target: "es5",
  module: "system",
  moduleResolution: "node",
  emitDecoratorMetadata: true,
  experimentalDecorators: true,
  noImplicitAny: true,
  removeComments: true,
  outFile: 'bundle.js',
  rootDir: 'ts',
  typescript: require('typescript')
}

var depList = [
  'lib/fix.js',
  'lib/material.min.js',
  'node_modules/es6-shim/es6-shim.js',
  'node_modules/systemjs/dist/system-polyfills.js',
  'node_modules/angular2/bundles/angular2-polyfills.min.js',
  'node_modules/systemjs/dist/system.js',
  'node_modules/rxjs/bundles/Rx.js',
  'node_modules/angular2/bundles/angular2.dev.js', // Minified version is broken
  'node_modules/angular2/bundles/router.dev.js',
  'node_modules/angular2/bundles/http.dev.js'
];

var fontList = [
  'node_modules/material-design-icons/iconfont/MaterialIcons-Regular.eot',
  'node_modules/material-design-icons/iconfont/MaterialIcons-Regular.woff',
  'node_modules/material-design-icons/iconfont/MaterialIcons-Regular.woff2',
  'node_modules/material-design-icons/iconfont/MaterialIcons-Regular.ttf',
];

var tsProject = typescript.createProject(tsOpt);

function buildjs(bundler) {
  return gulp.src(['./typings/browser.d.ts','./ts/**/*.ts', '!./ts/config.example.ts'])
      .on('error', util.log)
      .pipe(inlineNg2Template({ base: '/html' })) // Currently doesn't support source maps
      .pipe(sourcemaps.init())
      .pipe(typescript(tsProject))
      .pipe(gulpif(production, uglify({mangle: false})))
      .pipe(gulpif(!production, sourcemaps.write('./')))
      .pipe(rev())
      .pipe(gulp.dest('./build/js'))
      .pipe(rev.manifest({
        path: './build/rev-manifest.json',
        base: './build',
        merge: true
      }))
      .pipe(gulp.dest('./build'));
};

function buildcss() {
  return gulp.src('./sass/**/*.scss')
      .on('error', util.log)
      .pipe(sourcemaps.init())
      .pipe(sass().on('error', sass.logError))
      .pipe(gulp.src('./lib/*.css', {passthrough: true}))
      .pipe(concat('main.css'))
      .pipe(gulpif(production, cssmin()))
      .pipe(gulpif(!production, sourcemaps.write('./')))
      .pipe(rev())
      .pipe(gulp.dest('./build/css'))
      .pipe(rev.manifest({
        path: './build/rev-manifest.json',
        base: './build',
        merge: true
      }))
      .pipe(gulp.dest('./build'));
};

function builddep() {
  return gulp.src(depList)
      .pipe(concat({path: './bundle-dep.js', cwd: ''}))
      .pipe(gulpif(production, uglify({mangle: false})))
      .pipe(rev())
      .pipe(gulp.dest('./build/js'))
      .pipe(rev.manifest({
        path: './build/rev-manifest.json',
        base: './build',
        merge: true
      }))
      .pipe(gulp.dest('./build'));
}

function buildfont() {
  return gulp.src(fontList)
      .pipe(rev())
      .pipe(gulp.dest('./build/fonts'))
      .pipe(rev.manifest({
        path: './build/rev-manifest.json',
        base: './build',
        merge: true
      }))
      .pipe(gulp.dest('./build'));
}

function buildrev() {
  function replaceMap(filename) {
    if(filename.indexOf('.map') > -1) {
      return filename.replace(/.*\//g, '');
    } else return filename;
  }
  return gulp.src(['./build/**/*.*', '!./build/rev-manifest.json'])
      .pipe(revReplace({
        manifest: gulp.src('./build/rev-manifest.json'),
        modifiedUnreved: replaceMap,
        modifiedReved: replaceMap
      }))
      .pipe(gulp.dest('./dist'))
      .pipe(gulpif(webserver, connect.reload()));
}

gulp.task('prebuild:production', function(done) {
  production = true;
  done();
});

gulp.task('clean', function() {
  return del(['dist', 'build']);
});

gulp.task('clean:js', function() {
  return del(['dist/js/**/*.*', '!dist/js/bundle-dep-*.*', 'build/js/**/*.*', '!build/js/bundle-dep-*.*']);
});

gulp.task('clean:css', function() {
  return del(['dist/css', 'build/css']);
});

gulp.task('clean:dep', function() {
  return del('dist/js/bundle-dep-*.*', 'build/js/bundle-dep-*.*');
});

gulp.task('clean:font', function() {
  return del('dist/fonts/**/*.*', 'build/fonts/**/*.*');
});

gulp.task('clean:index', function() {
  return del('dist/index.html');
});

gulp.task('build:js', gulp.series('clean:js', buildjs));
gulp.task('build:css', gulp.series('clean:css', buildcss));
gulp.task('build:dep', gulp.series('clean:dep', builddep));
gulp.task('build:font', gulp.series('clean:font', buildfont));
gulp.task('build:index', gulp.series('clean:index', function() {
  return gulp.src('./html/index.html')
      .pipe(gulp.dest('./build'));
}));
gulp.task('build:rev', gulp.series(buildrev));

gulp.task('build', gulp.series(gulp.series('build:font', 'build:dep', 'build:js', 'build:css', 'build:index'), 'build:rev'));
gulp.task('build:production', gulp.series('prebuild:production', 'build'));
gulp.task('watch', gulp.series('build', function(done) {
  gulp.watch(['./ts/**/*.ts', './html/view/**/*.html', './html/tmpl/**/*.html'], gulp.series('build:js', 'build:rev'));
  gulp.watch('./sass/**/*.scss', gulp.series('build:css', 'build:rev'));
  gulp.watch('./html/index.html', gulp.series('build:index', 'build:rev'));
  done();
}));

gulp.task('webserver', function(done) {
  webserver = true;
  connect.server({
    root: 'dist',
    port: 3001,
    livereload: true,
    fallback: 'dist/index.html',
    debug: true
  });
  done();
});

gulp.task('default', gulp.series('watch', 'webserver'));
<|endoftext|>


<commit_before>/*eslint-disable no-console */

var browserify = require('browserify');
var connect = require('gulp-connect');
var merge = require('merge-stream');
var notify = require('gulp-notify');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var gutil = require('gulp-util');
var source = require('vinyl-source-stream');
var streamify = require('gulp-streamify');
var uglify = require('gulp-uglify');
var watchify = require('watchify');

var files = {
  dependencies: [
    'react',
    'react-dom',
    'react-addons-transition-group',
    'react-addons-css-transition-group',
  ],

  browserify: [
    './demo/main.js',
  ],
};

var browserifyTask = function (options) {

  var bundler = browserify({
    entries: [options.src],
    transform: [
      ['babelify', {
        presets: ['es2015', 'stage-2', 'react'],
        plugins: ['transform-class-properties'],
      }],
    ],
    debug: options.development,
    cache: {}, // Requirement of watchify
    packageCache: {}, // Requirement of watchify
    fullPaths: options.development,
    alias: ['/node_modules/react/react.js:react'],
    extensions: ['.js', '.jsx', '.json'],
  });

  var rebundle = function () {
    var start = Date.now();
    console.log('Building APP bundle');
    return bundler
      .bundle()
      .on('error', gutil.log)
      .pipe(source(options.output))
      .pipe(gulpif(!options.development, streamify(uglify())))
      .pipe(gulp.dest(options.dest))
      .pipe(gulpif(options.development, connect.reload()))
      .pipe(notify(function () {
        console.log('APP bundle built in ' + (Date.now() - start) + 'ms');
      }));
  };

  bundler.external(files.dependencies);

  if (options.development) {
    bundler = watchify(bundler);
    bundler.on('update', rebundle);
  }

  return rebundle();

};

var browserifyDepsTask = function (options) {

  var vendorsBundler = browserify({
    debug: options.development,
    require: files.dependencies,
  });

  var start = new Date();
  console.log('Building VENDORS bundle');
  return vendorsBundler
    .bundle()
    .on('error', gutil.log)
    .pipe(source(options.output))
    .pipe(gulpif(!options.development, streamify(uglify())))
    .on('error', gutil.log)
    .pipe(gulp.dest(options.dest))
    .pipe(notify(function () {
      console.log('VENDORS bundle built in ' + (Date.now() - start) + 'ms');
    }));

};

gulp.task('demo', function() {

  process.env.NODE_ENV = 'development';

  var browserifyDepsOpt = {
    development: true,
    src: files.dependencies,
    output: 'vendors.js',
    dest: './demo/build/scripts',
  };

  var browserifyOpt = {
    development: true,
    src: files.browserify,
    output: 'bundle.js',
    dest: './demo/build/scripts',
  };

  var serverOpt = {
    root: './demo',
    port: 8889,
    livereload: true,
  };

  connect.server(serverOpt);

  return merge(
    browserifyDepsTask(browserifyDepsOpt),
    browserifyTask(browserifyOpt)
  );

});<commit_msg>Fix ESlint errors<commit_after>/*eslint-disable no-console */

var browserify = require('browserify');
var connect = require('gulp-connect');
var merge = require('merge-stream');
var notify = require('gulp-notify');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var gutil = require('gulp-util');
var source = require('vinyl-source-stream');
var streamify = require('gulp-streamify');
var uglify = require('gulp-uglify');
var watchify = require('watchify');

var files = {
  dependencies: [
    'react',
    'react-dom',
    'react-addons-transition-group',
    'react-addons-css-transition-group',
  ],

  browserify: [
    './demo/main.js',
  ],
};

var browserifyTask = function (options) {

  var bundler = browserify({
    entries: [options.src],
    transform: [
      ['babelify', {
        presets: ['es2015', 'stage-2', 'react'],
        plugins: ['transform-class-properties'],
      }],
    ],
    debug: options.development,
    cache: {}, // Requirement of watchify
    packageCache: {}, // Requirement of watchify
    fullPaths: options.development,
    alias: ['/node_modules/react/react.js:react'],
    extensions: ['.js', '.jsx', '.json'],
  });

  var rebundle = function () {
    var start = Date.now();
    console.log('Building APP bundle');
    return bundler
      .bundle()
      .on('error', gutil.log)
      .pipe(source(options.output))
      .pipe(gulpif(!options.development, streamify(uglify())))
      .pipe(gulp.dest(options.dest))
      .pipe(gulpif(options.development, connect.reload()))
      .pipe(notify(function () {
        console.log('APP bundle built in ' + (Date.now() - start) + 'ms');
      }));
  };

  bundler.external(files.dependencies);

  if (options.development) {
    bundler = watchify(bundler);
    bundler.on('update', rebundle);
  }

  return rebundle();

};

var browserifyDepsTask = function (options) {

  var vendorsBundler = browserify({
    debug: options.development,
    require: files.dependencies,
  });

  var start = new Date();
  console.log('Building VENDORS bundle');
  return vendorsBundler
    .bundle()
    .on('error', gutil.log)
    .pipe(source(options.output))
    .pipe(gulpif(!options.development, streamify(uglify())))
    .on('error', gutil.log)
    .pipe(gulp.dest(options.dest))
    .pipe(notify(function () {
      console.log('VENDORS bundle built in ' + (Date.now() - start) + 'ms');
    }));

};

gulp.task('demo', function () {

  process.env.NODE_ENV = 'development';

  var browserifyDepsOpt = {
    development: true,
    src: files.dependencies,
    output: 'vendors.js',
    dest: './demo/build/scripts',
  };

  var browserifyOpt = {
    development: true,
    src: files.browserify,
    output: 'bundle.js',
    dest: './demo/build/scripts',
  };

  var serverOpt = {
    root: './demo',
    port: 8889,
    livereload: true,
  };

  connect.server(serverOpt);

  return merge(
    browserifyDepsTask(browserifyDepsOpt),
    browserifyTask(browserifyOpt)
  );

});<|endoftext|>


<commit_before>var fs = require('fs');
var stream = require('stream');
var log = require('../../log').logger('gcode');
var config = require('../../config');
var countLineNumbers = require('../../util').countLineNumbers
var LineNumberer = require('../../util').LineNumberer

function GCodeRuntime() {
	this.machine = null;
	this.driver = null;
	this.ok_to_disconnect = true;
	this.completeCallback = null;
    this.inFeedHold = false;
    this._file_or_stream_in_progress = false;
}

GCodeRuntime.prototype.toString = function() {
	return "[GCodeRuntime]";
}
//Check if move requires auth
GCodeRuntime.prototype.needsAuth = function(s) {
	//all needs auth (check) so just return true
	return true;
}
GCodeRuntime.prototype.connect = function(machine) {
	this.machine = machine;
	this.driver = machine.driver;
	this.status_handler =  this._onDriverStatus.bind(this);
	this.status_report = {};
	this.driver.on('status',this.status_handler);
	log.info("Connected G-Code Runtime");
};

GCodeRuntime.prototype.disconnect = function() {
	if(this.ok_to_disconnect) {
		this.driver.removeListener('status', this.status_handler);
		log.info("Disconnected G-Code Runtime");
	} else {
		throw new Error("Cannot disconnect GCode Runtime")
	}
};

GCodeRuntime.prototype.pause = function() {
	this.driver.feedHold();
    this.inFeedHold = true;
}

GCodeRuntime.prototype.quit = function() {
	this.driver.quit();
}

GCodeRuntime.prototype.resume = function() {
	this.driver.resume();
    this.inFeedHold = false;
}

GCodeRuntime.prototype._changeState = function(newstate) {
	log.debug("Changing state to " + newstate)
	if(newstate != "idle") {
		this.ok_to_disconnect = false;
	}
	this.machine.setState(this, newstate);
};

GCodeRuntime.prototype._limit = function() {
	var er = this.driver.getLastException();
	if(er && er.st == 203) {
		var msg = er.msg.replace(/\[[^\[\]]*\]/,'');
		this.driver.clearLastException();
		this._fail(msg);
		return true;
	}
	return false;
}

GCodeRuntime.prototype._onDriverStatus = function(status) {
	// Update the machine copy of g2 status variables
	for (var key in this.machine.status) {
		if(key in status) {
			this.machine.status[key] = status[key];
		}
	}
	// Update the machine copy of g2 status variables
	for (key in status) {
		this.status_report[key] = status[key];
	}

	this.machine.emit('status',this.machine.status);
};

GCodeRuntime.prototype._die = function() {
	this.machine.status.current_file = null;
	this.machine.status.line=null;
	this.machine.status.nb_lines=null;
 	try {
 		this.machine.status.job.fail();
 	} catch(e) {}
 	finally {
		this.machine.status.job=null;
 		this.machine.setState(this, 'dead', {error : 'A G2 exception has occurred. You must reboot your tool.'});
 	}
}

GCodeRuntime.prototype._fail = function(message) {
	this.machine.status.current_file = null;
	this.machine.status.line=null;
	this.machine.status.nb_lines=null;
 	try {
 		this.machine.status.job.fail();
 	} catch(e) {}
 	finally {
		this.machine.status.job=null;
 		this.machine.setState(this, 'stopped', {error : message});
 	}
}

GCodeRuntime.prototype._idle = function() {
	this.machine.status.current_file = null;
	this.machine.status.line=null;
	this.machine.status.nb_lines=null;
	var job = this.machine.status.job;
	// Set the machine state to idle and return the units to their default configuration
	var finishUp = function() {
		this.driver.setUnits(config.machine.get('units'), function() {
			var callback = this.completeCallback || function() {};
			this.ok_to_disconnect = true;
			this.completeCallback = null;
			this.machine.setState(this, 'idle');
			callback();
		}.bind(this))
	}.bind(this);

	if(job) {
		if(job.pending_cancel) {
			this.machine.status.job.cancel(function(err, job) {
				this.machine.status.job=null;
				finishUp();
			}.bind(this));
		} else {
			this.machine.status.job.finish(function(err, job) {
				this.machine.status.job=null;
				finishUp();
			}.bind(this));
		}
	} else {
		finishUp();
	}
};

GCodeRuntime.prototype._handleStop = function() {
	this._idle();
}

GCodeRuntime.prototype._handleStateChange = function(stat) {
	switch(stat) {
		case this.driver.STAT_HOLDING:
			this._changeState('paused');
			break;
		case this.driver.STAT_RUNNING:
			this._changeState('running');
			break;
        case this.driver.STAT_STOP:
            // This that the g2core is in stat:3, meaning it has processed all available gcode
            // so we need to tell it to move to stat:4 by sending an end of job "M30"
            // There may have been an M30 in the file but the g2core will have ignored it, this
            // may change someday in the future on the g2core end, so we may end up revisiting this.
            // OTOH, an extra M30 should not cause a problem.
            if (this._file_or_stream_in_progress) {
                this.driver.sendM30();
                this._file_or_stream_in_progress = false;
            }

		default:
			break;
	}
}

// Run a given stream input
GCodeRuntime.prototype.runStream = function(st) {
	var ln = new LineNumberer();
	return this.driver.runStream(st.pipe(ln))
		.on('stat', this._handleStateChange.bind(this))
		.then(this._handleStop.bind(this));
}

// Run a file given the filename
GCodeRuntime.prototype.runFile = function(filename, callback) {
    this._file_or_stream_in_progress = true;
    if(this.machine.status.state === 'idle' || this.machine.status.state === 'armed') {
		countLineNumbers(filename, function(err, lines) {
			this.machine.status.nb_lines = lines;
			var st = fs.createReadStream(filename);
			return this.runStream(st);
		}.bind(this));
	}
}

// Run the provided string
// callback runs only when execution is complete.
GCodeRuntime.prototype.runString = function(string, callback) {
	if(callback) { log.error("CALLBACK PASSED TO RUNSTRING")}

	if(this.machine.status.state === 'idle' || this.machine.status.state === 'armed') {
		// Add line numbers to Gcode string.
		var lines = (string.match(/\n/g) || '');
		// var lines =  string.split('\n');
		this.machine.status.nb_lines = lines.length;
		// for (i=0;i<lines.length;i++){
		// 	if (lines[i][0]!==undefined && lines[i][0].toUpperCase() !== 'N' ){
		// 		lines[i]= 'N'+ (i+1) + lines[i];
		// 	}
		// }
		this.completeCallback = callback;
		this._changeState("running");
		// var stringStream = new stream.Readable();
		// Push lines to stream.
		// for(var i=0; i<lines.length; i++) {
		// 	stringStream.push(lines[i] + "\n");
		// }
		// stringStream.push(null);
		var stringStream = stream.Readable.from(string);
		// stringStream.on('data', (chunk) => {
		// 	log.debug(chunk)
		// });
		this.driver.prime();
		return this.runStream(stringStream);
	}
};

// Run the given string as gcode
GCodeRuntime.prototype.executeCode = function(string, callback) {
	this._file_or_stream_in_progress = true;
	return this.runString(string);
}

exports.GCodeRuntime = GCodeRuntime;<commit_msg>refs #49828 stream without line numbers.<commit_after>var fs = require('fs');
var stream = require('stream');
var log = require('../../log').logger('gcode');
var config = require('../../config');
var countLineNumbers = require('../../util').countLineNumbers
var LineNumberer = require('../../util').LineNumberer

function GCodeRuntime() {
	this.machine = null;
	this.driver = null;
	this.ok_to_disconnect = true;
	this.completeCallback = null;
    this.inFeedHold = false;
    this._file_or_stream_in_progress = false;
}

GCodeRuntime.prototype.toString = function() {
	return "[GCodeRuntime]";
}
//Check if move requires auth
GCodeRuntime.prototype.needsAuth = function(s) {
	//all needs auth (check) so just return true
	return true;
}
GCodeRuntime.prototype.connect = function(machine) {
	this.machine = machine;
	this.driver = machine.driver;
	this.status_handler =  this._onDriverStatus.bind(this);
	this.status_report = {};
	this.driver.on('status',this.status_handler);
	log.info("Connected G-Code Runtime");
};

GCodeRuntime.prototype.disconnect = function() {
	if(this.ok_to_disconnect) {
		this.driver.removeListener('status', this.status_handler);
		log.info("Disconnected G-Code Runtime");
	} else {
		throw new Error("Cannot disconnect GCode Runtime")
	}
};

GCodeRuntime.prototype.pause = function() {
	this.driver.feedHold();
    this.inFeedHold = true;
}

GCodeRuntime.prototype.quit = function() {
	this.driver.quit();
}

GCodeRuntime.prototype.resume = function() {
	this.driver.resume();
    this.inFeedHold = false;
}

GCodeRuntime.prototype._changeState = function(newstate) {
	log.debug("Changing state to " + newstate)
	if(newstate != "idle") {
		this.ok_to_disconnect = false;
	}
	this.machine.setState(this, newstate);
};

GCodeRuntime.prototype._limit = function() {
	var er = this.driver.getLastException();
	if(er && er.st == 203) {
		var msg = er.msg.replace(/\[[^\[\]]*\]/,'');
		this.driver.clearLastException();
		this._fail(msg);
		return true;
	}
	return false;
}

GCodeRuntime.prototype._onDriverStatus = function(status) {
	// Update the machine copy of g2 status variables
	for (var key in this.machine.status) {
		if(key in status) {
			this.machine.status[key] = status[key];
		}
	}
	// Update the machine copy of g2 status variables
	for (key in status) {
		this.status_report[key] = status[key];
	}

	this.machine.emit('status',this.machine.status);
};

GCodeRuntime.prototype._die = function() {
	this.machine.status.current_file = null;
	this.machine.status.line=null;
	this.machine.status.nb_lines=null;
 	try {
 		this.machine.status.job.fail();
 	} catch(e) {}
 	finally {
		this.machine.status.job=null;
 		this.machine.setState(this, 'dead', {error : 'A G2 exception has occurred. You must reboot your tool.'});
 	}
}

GCodeRuntime.prototype._fail = function(message) {
	this.machine.status.current_file = null;
	this.machine.status.line=null;
	this.machine.status.nb_lines=null;
 	try {
 		this.machine.status.job.fail();
 	} catch(e) {}
 	finally {
		this.machine.status.job=null;
 		this.machine.setState(this, 'stopped', {error : message});
 	}
}

GCodeRuntime.prototype._idle = function() {
	this.machine.status.current_file = null;
	this.machine.status.line=null;
	this.machine.status.nb_lines=null;
	var job = this.machine.status.job;
	// Set the machine state to idle and return the units to their default configuration
	var finishUp = function() {
		this.driver.setUnits(config.machine.get('units'), function() {
			var callback = this.completeCallback || function() {};
			this.ok_to_disconnect = true;
			this.completeCallback = null;
			this.machine.setState(this, 'idle');
			callback();
		}.bind(this))
	}.bind(this);

	if(job) {
		if(job.pending_cancel) {
			this.machine.status.job.cancel(function(err, job) {
				this.machine.status.job=null;
				finishUp();
			}.bind(this));
		} else {
			this.machine.status.job.finish(function(err, job) {
				this.machine.status.job=null;
				finishUp();
			}.bind(this));
		}
	} else {
		finishUp();
	}
};

GCodeRuntime.prototype._handleStop = function() {
	this._idle();
}

GCodeRuntime.prototype._handleStateChange = function(stat) {
	switch(stat) {
		case this.driver.STAT_HOLDING:
			this._changeState('paused');
			break;
		case this.driver.STAT_RUNNING:
			this._changeState('running');
			break;
        case this.driver.STAT_STOP:
            // This that the g2core is in stat:3, meaning it has processed all available gcode
            // so we need to tell it to move to stat:4 by sending an end of job "M30"
            // There may have been an M30 in the file but the g2core will have ignored it, this
            // may change someday in the future on the g2core end, so we may end up revisiting this.
            // OTOH, an extra M30 should not cause a problem.
            if (this._file_or_stream_in_progress) {
                this.driver.sendM30();
                this._file_or_stream_in_progress = false;
            }

		default:
			break;
	}
}

// Run a given stream input
GCodeRuntime.prototype.runStream = function(st) {
	var ln = new LineNumberer();
	// return this.driver.runStream(st.pipe(ln))
	return this.driver.runStream(st)
		.on('stat', this._handleStateChange.bind(this))
		.then(this._handleStop.bind(this));
}

// Run a file given the filename
GCodeRuntime.prototype.runFile = function(filename, callback) {
    this._file_or_stream_in_progress = true;
    if(this.machine.status.state === 'idle' || this.machine.status.state === 'armed') {
		countLineNumbers(filename, function(err, lines) {
			this.machine.status.nb_lines = lines;
			var st = fs.createReadStream(filename);
			return this.runStream(st);
		}.bind(this));
	}
}

// Run the provided string
// callback runs only when execution is complete.
GCodeRuntime.prototype.runString = function(string, callback) {
	if(callback) { log.error("CALLBACK PASSED TO RUNSTRING")}

	if(this.machine.status.state === 'idle' || this.machine.status.state === 'armed') {
		// Add line numbers to Gcode string.
		var lines = (string.match(/\n/g) || '');
		// var lines =  string.split('\n');
		this.machine.status.nb_lines = lines.length;
		// for (i=0;i<lines.length;i++){
		// 	if (lines[i][0]!==undefined && lines[i][0].toUpperCase() !== 'N' ){
		// 		lines[i]= 'N'+ (i+1) + lines[i];
		// 	}
		// }
		this.completeCallback = callback;
		this._changeState("running");
		// var stringStream = new stream.Readable();
		// Push lines to stream.
		// for(var i=0; i<lines.length; i++) {
		// 	stringStream.push(lines[i] + "\n");
		// }
		// stringStream.push(null);
		var stringStream = stream.Readable.from(string);
		// stringStream.on('data', (chunk) => {
		// 	log.debug(chunk)
		// });
		return this.runStream(stringStream);
	}
};

// Run the given string as gcode
GCodeRuntime.prototype.executeCode = function(string, callback) {
	this._file_or_stream_in_progress = true;
	return this.runString(string);
}

exports.GCodeRuntime = GCodeRuntime;<|endoftext|>


<commit_before>import { setTransform, isTransformSupported } from './utils';
import React from 'react';
import classnames from 'classnames';

export function getScroll(w, top) {
  let ret = w[`page${top ? 'Y' : 'X'}Offset`];
  const method = `scroll${top ? 'Top' : 'Left'}`;
  if (typeof ret !== 'number') {
    const d = w.document;
    // ie6,7,8 standard mode
    ret = d.documentElement[method];
    if (typeof ret !== 'number') {
      // quirks mode
      ret = d.body[method];
    }
  }
  return ret;
}

function offset(elem) {
  let box;
  let x;
  let y;
  const doc = elem.ownerDocument;
  const body = doc.body;
  const docElem = doc && doc.documentElement;
  box = elem.getBoundingClientRect();
  x = box.left;
  y = box.top;
  x -= docElem.clientLeft || body.clientLeft || 0;
  y -= docElem.clientTop || body.clientTop || 0;
  const w = doc.defaultView || doc.parentWindow;
  x += getScroll(w);
  y += getScroll(w, true);
  return {
    left: x, top: y,
  };
}

function componentDidUpdate(component, init) {
  const refs = component.refs;
  const wrapNode = refs.nav || refs.root;
  const containerOffset = offset(wrapNode);
  const inkBarNode = refs.inkBar;
  const activeTab = refs.activeTab;
  const inkBarNodeStyle = inkBarNode.style;
  const tabBarPosition = component.props.tabBarPosition;
  if (init) {
    // prevent mount animation
    inkBarNodeStyle.display = 'none';
  }
  if (activeTab) {
    const tabNode = activeTab;
    const tabOffset = offset(tabNode);
    const transformSupported = isTransformSupported(inkBarNodeStyle);
    if (tabBarPosition === 'top' || tabBarPosition === 'bottom') {
      const left = tabOffset.left - containerOffset.left;
      // use 3d gpu to optimize render
      if (transformSupported) {
        setTransform(inkBarNodeStyle, `translate3d(${left}px,0,0)`);
        inkBarNodeStyle.width = `${tabNode.offsetWidth}px`;
        inkBarNodeStyle.height = '';
      } else {
        inkBarNodeStyle.left = `${left}px`;
        inkBarNodeStyle.top = '';
        inkBarNodeStyle.bottom = '';
        inkBarNodeStyle.right = `${wrapNode.offsetWidth - left - tabNode.offsetWidth}px`;
      }
    } else {
      const top = tabOffset.top - containerOffset.top;
      if (transformSupported) {
        setTransform(inkBarNodeStyle, `translate3d(0,${top}px,0)`);
        inkBarNodeStyle.height = `${tabNode.offsetHeight}px`;
        inkBarNodeStyle.width = '';
      } else {
        inkBarNodeStyle.left = '';
        inkBarNodeStyle.right = '';
        inkBarNodeStyle.top = `${top}px`;
        inkBarNodeStyle.bottom = `${wrapNode.offsetHeight - top - tabNode.offsetHeight}px`;
      }
    }
  }
  inkBarNodeStyle.display = activeTab ? 'block' : 'none';
}

export default {

  getDefaultProps() {
    return {
      inkBarAnimated: true,
    }
  },

  componentDidUpdate() {
    componentDidUpdate(this);
  },

  componentDidMount() {
    componentDidUpdate(this, true);
  },

  getInkBarNode() {
    const { prefixCls, styles, inkBarAnimated } = this.props;
    const className = `${prefixCls}-ink-bar`;
    const classes = classnames({
      [className]: true,
      [
        inkBarAnimated ?
          `${className}-animated` :
          `${className}-no-animated`
        ]: true,
    });
    return (
      <div
        style={styles.inkBar}
        className={classes}
        key="inkBar"
        ref="inkBar"
      />
    );
  },
};
<commit_msg>Minor revision 2<commit_after>import { setTransform, isTransformSupported } from './utils';
import React from 'react';
import classnames from 'classnames';

export function getScroll(w, top) {
  let ret = w[`page${top ? 'Y' : 'X'}Offset`];
  const method = `scroll${top ? 'Top' : 'Left'}`;
  if (typeof ret !== 'number') {
    const d = w.document;
    // ie6,7,8 standard mode
    ret = d.documentElement[method];
    if (typeof ret !== 'number') {
      // quirks mode
      ret = d.body[method];
    }
  }
  return ret;
}

function offset(elem) {
  let box;
  let x;
  let y;
  const doc = elem.ownerDocument;
  const body = doc.body;
  const docElem = doc && doc.documentElement;
  box = elem.getBoundingClientRect();
  x = box.left;
  y = box.top;
  x -= docElem.clientLeft || body.clientLeft || 0;
  y -= docElem.clientTop || body.clientTop || 0;
  const w = doc.defaultView || doc.parentWindow;
  x += getScroll(w);
  y += getScroll(w, true);
  return {
    left: x, top: y,
  };
}

function componentDidUpdate(component, init) {
  const refs = component.refs;
  const wrapNode = refs.nav || refs.root;
  const containerOffset = offset(wrapNode);
  const inkBarNode = refs.inkBar;
  const activeTab = refs.activeTab;
  const inkBarNodeStyle = inkBarNode.style;
  const tabBarPosition = component.props.tabBarPosition;
  if (init) {
    // prevent mount animation
    inkBarNodeStyle.display = 'none';
  }
  if (activeTab) {
    const tabNode = activeTab;
    const tabOffset = offset(tabNode);
    const transformSupported = isTransformSupported(inkBarNodeStyle);
    if (tabBarPosition === 'top' || tabBarPosition === 'bottom') {
      const left = tabOffset.left - containerOffset.left;
      // use 3d gpu to optimize render
      if (transformSupported) {
        setTransform(inkBarNodeStyle, `translate3d(${left}px,0,0)`);
        inkBarNodeStyle.width = `${tabNode.offsetWidth}px`;
        inkBarNodeStyle.height = '';
      } else {
        inkBarNodeStyle.left = `${left}px`;
        inkBarNodeStyle.top = '';
        inkBarNodeStyle.bottom = '';
        inkBarNodeStyle.right = `${wrapNode.offsetWidth - left - tabNode.offsetWidth}px`;
      }
    } else {
      const top = tabOffset.top - containerOffset.top;
      if (transformSupported) {
        setTransform(inkBarNodeStyle, `translate3d(0,${top}px,0)`);
        inkBarNodeStyle.height = `${tabNode.offsetHeight}px`;
        inkBarNodeStyle.width = '';
      } else {
        inkBarNodeStyle.left = '';
        inkBarNodeStyle.right = '';
        inkBarNodeStyle.top = `${top}px`;
        inkBarNodeStyle.bottom = `${wrapNode.offsetHeight - top - tabNode.offsetHeight}px`;
      }
    }
  }
  inkBarNodeStyle.display = activeTab ? 'block' : 'none';
}

export default {

  getDefaultProps() {
    return {
      inkBarAnimated: true,
    };
  },

  componentDidUpdate() {
    componentDidUpdate(this);
  },

  componentDidMount() {
    componentDidUpdate(this, true);
  },

  getInkBarNode() {
    const { prefixCls, styles, inkBarAnimated } = this.props;
    const className = `${prefixCls}-ink-bar`;
    const classes = classnames({
      [className]: true,
      [
        inkBarAnimated ?
          `${className}-animated` :
          `${className}-no-animated`
        ]: true,
    });
    return (
      <div
        style={styles.inkBar}
        className={classes}
        key="inkBar"
        ref="inkBar"
      />
    );
  },
};
<|endoftext|>