<commit_before>var kunstmaanbundles = kunstmaanbundles || {};

kunstmaanbundles.autoCollapseTabs = (function($, window, undefined) {

    var $tabs, $btnMore, $dropdown,
        dropdownItems, tabsHeight, children, singleTabHeight;

    init = function() {
        $tabs = $('.js-auto-collapse-tabs');
        $btnMore = $('.tab__more');
        $dropdown = $('#collapsed');
        singleTabHeight = $tabs.find('li:first-child').innerHeight(); // get single height

        doCheck();

        $(window).on('resize', function() {
            doCheck();
        }); // when window is resized
    };

    doCheck= function() {
        tabsHeight = $tabs.innerHeight();
        children = $tabs.children('li:not(:last-child):not(:first-child)'); // Don't count the 'more' tab and always show first tab

        if (tabsHeight >= singleTabHeight) {

            while (tabsHeight > singleTabHeight && children.size() > 0) {
                $btnMore.show(); // show immediately when first tab is added to dropdown

                // move tab to dropdown
                $(children[children.size()-1]).prependTo($dropdown);

                // recalculate
                tabsHeight = $tabs.innerHeight();
                children = $tabs.children('li:not(:last-child):not(:first-child)');
            }

        } else {
            dropdownItems = $dropdown.children('li');

            while (tabsHeight < singleTabHeight && dropdownItems.size() > 0) {
                $(dropdownItems[0]).insertBefore($tabs.children('li:last-child'));

                // recalculate
                tabsHeight = $tabs.innerHeight();
                dropdownItems = $dropdown.children('li');
            }

            if (tabsHeight > singleTabHeight) { // double chk height again
                this.doCheck();
            }
        }

        // hide the more button if dropdown is empty
        dropdownItems = $dropdown.children('li');
        if (dropdownItems.size() <= 0) {
            $btnMore.hide();

        } else {
            $btnMore.show();

            // check if active element is in dropdown
            if ($dropdown.children('li.active').size() > 0) {
                $btnMore.addClass('active');
            } else {
                $btnMore.removeClass('active');
            }
        }
    };

    return {
        init: init
    };

}(jQuery, window));
<commit_msg>Fix page edit tab logic<commit_after>

var kunstmaanbundles = kunstmaanbundles || {};

kunstmaanbundles.autoCollapseTabs = (function($, window, undefined) {

    var $tabs, $btnMore, $dropdown,
        dropdownItems, tabsHeight, children, singleTabHeight, initTabLogic, replaceUrlParam;

    init = function() {
        $tabs = $('.js-auto-collapse-tabs');
        $btnMore = $('.tab__more');
        $dropdown = $('#collapsed');
        singleTabHeight = $tabs.find('li:first-child').innerHeight(); // get single height

        initTabLogic();
        doCheck();

        $(window).on('resize', function() {
            doCheck();
        }); // when window is resized
    };

    initTabLogic = function () {
        // If there is a tab defined in the url, we activate it
        var currentTabElement = $('#currenttab');
        if (currentTabElement && currentTabElement.val().length > 0) {
            $('.js-auto-collapse-tabs.nav-tabs a[href="' + $('#currenttab').val() + '"]').tab('show');
        }

        // When tab click, add the current tab in the url
        $('.js-auto-collapse-tabs.nav-tabs a').click(function (e) {
            $(this).tab('show');

            var activeTab = this.hash.substr(1);
            if (history.pushState) {
                window.history.pushState({}, null, replaceUrlParam(window.location.href, 'currenttab', activeTab));
            }

            if ($('#currenttab').length > 0) {
                $('#currenttab').val(activeTab);
            }
        });

        // When the form get ssubmitted, change the action url
        $('#pageadminform .js-save-btn').on('click', function() {
            var form = $('#pageadminform');
            form.attr('action', window.location.href);
        });
    };

    replaceUrlParam = function (url, paramName, paramValue) {
        var pattern = new RegExp('(' + paramName + '=).*?(&|$)'),
            newUrl = url;

        if (url.search(pattern) >= 0) {
            newUrl = url.replace(pattern, '$1' + paramValue + '$2');
        } else {
            newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
        }

        return newUrl;
    };

    doCheck= function() {
        tabsHeight = $tabs.innerHeight();
        children = $tabs.children('li:not(:last-child):not(:first-child)'); // Don't count the 'more' tab and always show first tab

        if (tabsHeight >= singleTabHeight) {

            while (tabsHeight > singleTabHeight && children.size() > 0) {
                $btnMore.show(); // show immediately when first tab is added to dropdown

                // move tab to dropdown
                $(children[children.size()-1]).prependTo($dropdown);

                // recalculate
                tabsHeight = $tabs.innerHeight();
                children = $tabs.children('li:not(:last-child):not(:first-child)');
            }

        } else {
            dropdownItems = $dropdown.children('li');

            while (tabsHeight < singleTabHeight && dropdownItems.size() > 0) {
                $(dropdownItems[0]).insertBefore($tabs.children('li:last-child'));

                // recalculate
                tabsHeight = $tabs.innerHeight();
                dropdownItems = $dropdown.children('li');
            }

            if (tabsHeight > singleTabHeight) { // double chk height again
                this.doCheck();
            }
        }

        // hide the more button if dropdown is empty
        dropdownItems = $dropdown.children('li');
        if (dropdownItems.size() <= 0) {
            $btnMore.hide();

        } else {
            $btnMore.show();

            // check if active element is in dropdown
            if ($dropdown.children('li.active').size() > 0) {
                $btnMore.addClass('active');
            } else {
                $btnMore.removeClass('active');
            }
        }
    };

    return {
        init: init
    };

}(jQuery, window));
<|endoftext|>


<commit_before>import * as glmatrix from 'gl-matrix';
import {Vec3} from '../Math/Vec3';
import twgl from 'twgl-base.js';

let ID = 0;

class SceneObject {
	constructor({material = null, name = null} = {material: null, name: null}) {
		this.id = ID++;
		this.name = name || `SceneObject#${this.id}`;
		this.vao = null;

		if (material !== null) {
			this.material = material;
			this.program = material.program;
		}

		this._position = new Vec3();
		this._rotationAxis = new Vec3();
		this._scale = new Vec3(1, 1, 1);

		this.children = [];
		this.parent = null;

		this._visible = true;
		this.frustrumCulled = true;

		this.normalMatrix = glmatrix.mat4.create();

		this.localMatrix = glmatrix.mat4.create();
		this.worldMatrix = glmatrix.mat4.create();
	}

	updateWorldMatrix(parentWorldMatrix) {
		if (parentWorldMatrix) {
			glmatrix.mat4.multiply(this.worldMatrix, parentWorldMatrix, this.localMatrix);
		}

		else if (!this.parent) {
			glmatrix.mat4.copy(this.worldMatrix, this.localMatrix);
		}

		this.children.forEach((child) => {
			child.updateWorldMatrix(this.worldMatrix);
		});
	}

	setParent(parent) {
		if (this.parent) {
			const index = this.parent.children.indexOf(this);
			if (index !== -1) {
				this.parent.children.splice(index, 1);
			}
		}
		if (parent) {
			parent.children.push(this);
		}
		this.parent = parent;
	}

	removeChild(child) {
		const index = this.children.indexOf(child);
		if (index !== -1) {
			this.children.splice(index, 1);
			child.parent = null;
		}
	}

	initObject(gl) {
		this.program = this.material.createMaterial(gl);

		this.programInfo = twgl.createProgramInfoFromProgram(gl.glContext, this.program);

		this.bufferInfo = twgl.createBufferInfoFromArrays(gl.glContext, this.attributes);
		this.vao = twgl.createVAOFromBufferInfo(gl.glContext, this.programInfo.attribSetters, this.bufferInfo);

		const lightUboInfo = twgl.createUniformBlockInfo(gl.glContext, this.programInfo, 'Lights');

		twgl.setBlockUniforms(lightUboInfo, {
			u_direction: [0.15, 0.8, 0.75],
			u_color: [1.0, 1.0, 1.0],
			u_intencity: 0.7
		});
		twgl.setUniformBlock(gl.glContext, this.programInfo, lightUboInfo);
		twgl.bindUniformBlock(gl.glContext, this.programInfo, lightUboInfo);
	}

	set position(positionVec) {
		Object.keys(positionVec).forEach((key) => {
			this._position[key] = positionVec[key];
		});

		glmatrix.mat4.translate(this.localMatrix, this.localMatrix, this._position.asArray());

		this.updateMatrices();
	}

	get position() {
		return this._position;
	}

	set visible(isVisible) {
		this._visible = false;
		for (const child of this.children) {
			child.visible = isVisible;
		}
	}

	get visible() {
		return this._visible;
	}

	set scale(scale) {
		Object.keys(scale).forEach((key) => {
			this._scale[key] = scale[key];
		});

		glmatrix.mat4.scale(this.localMatrix, this.localMatrix, this._scale.asArray());

		this.updateMatrices();
	}

	get scale() {
		return this._scale;
	}

	rotate(vecRotateAxis, angle) {
		Object.keys(vecRotateAxis).forEach((key) => {
			this._rotationAxis[key] = vecRotateAxis[key];
		});

		glmatrix.mat4.rotate(this.localMatrix, this.localMatrix, angle, this._rotationAxis.asArray());

		this.updateMatrices();
	}

	updateMatrices() {
		this._updateNormalMatrix();
	}

	_updateNormalMatrix() {
		glmatrix.mat4.invert(this.normalMatrix, this.localMatrix);
		glmatrix.mat4.transpose(this.normalMatrix, this.normalMatrix);
	}
}
export {SceneObject};
<commit_msg>UBO to direct lights. Need to refactor<commit_after>import * as glmatrix from 'gl-matrix';
import {Vec3} from '../Math/Vec3';
import twgl from 'twgl-base.js';

let ID = 0;

class SceneObject {
	constructor({material = null, name = null} = {material: null, name: null}) {
		this.id = ID++;
		this.name = name || `SceneObject#${this.id}`;
		this.vao = null;

		if (material !== null) {
			this.material = material;
			this.program = material.program;
		}

		this._position = new Vec3();
		this._rotationAxis = new Vec3();
		this._scale = new Vec3(1, 1, 1);

		this.children = [];
		this.parent = null;

		this._visible = true;
		this.frustrumCulled = true;

		this.normalMatrix = glmatrix.mat4.create();

		this.localMatrix = glmatrix.mat4.create();
		this.worldMatrix = glmatrix.mat4.create();
	}

	updateWorldMatrix(parentWorldMatrix) {
		if (parentWorldMatrix) {
			glmatrix.mat4.multiply(this.worldMatrix, parentWorldMatrix, this.localMatrix);
		}

		else if (!this.parent) {
			glmatrix.mat4.copy(this.worldMatrix, this.localMatrix);
		}

		this.children.forEach((child) => {
			child.updateWorldMatrix(this.worldMatrix);
		});
	}

	setParent(parent) {
		if (this.parent) {
			const index = this.parent.children.indexOf(this);
			if (index !== -1) {
				this.parent.children.splice(index, 1);
			}
		}
		if (parent) {
			parent.children.push(this);
		}
		this.parent = parent;
	}

	removeChild(child) {
		const index = this.children.indexOf(child);
		if (index !== -1) {
			this.children.splice(index, 1);
			child.parent = null;
		}
	}

	initObject(gl) {
		this.program = this.material.createMaterial(gl);

		this.programInfo = twgl.createProgramInfoFromProgram(gl.glContext, this.program);

		this.bufferInfo = twgl.createBufferInfoFromArrays(gl.glContext, this.attributes);
		this.vao = twgl.createVAOFromBufferInfo(gl.glContext, this.programInfo.attribSetters, this.bufferInfo);

		const lightUboInfo = twgl.createUniformBlockInfo(gl.glContext, this.programInfo, 'Lights');

		twgl.setBlockUniforms(lightUboInfo, {
			'directLight.u_direction': [0.15, 0.8, 0.75],
			'directLight.u_color': [1.0, 1.0, 1.0],
			'directLight.u_intencity': 0.7
		});

		twgl.setUniformBlock(gl.glContext, this.programInfo, lightUboInfo);
		twgl.bindUniformBlock(gl.glContext, this.programInfo, lightUboInfo);
	}

	set position(positionVec) {
		Object.keys(positionVec).forEach((key) => {
			this._position[key] = positionVec[key];
		});

		glmatrix.mat4.translate(this.localMatrix, this.localMatrix, this._position.asArray());

		this.updateMatrices();
	}

	get position() {
		return this._position;
	}

	set visible(isVisible) {
		this._visible = false;
		for (const child of this.children) {
			child.visible = isVisible;
		}
	}

	get visible() {
		return this._visible;
	}

	set scale(scale) {
		Object.keys(scale).forEach((key) => {
			this._scale[key] = scale[key];
		});

		glmatrix.mat4.scale(this.localMatrix, this.localMatrix, this._scale.asArray());

		this.updateMatrices();
	}

	get scale() {
		return this._scale;
	}

	rotate(vecRotateAxis, angle) {
		Object.keys(vecRotateAxis).forEach((key) => {
			this._rotationAxis[key] = vecRotateAxis[key];
		});

		glmatrix.mat4.rotate(this.localMatrix, this.localMatrix, angle, this._rotationAxis.asArray());

		this.updateMatrices();
	}

	updateMatrices() {
		this._updateNormalMatrix();
	}

	_updateNormalMatrix() {
		glmatrix.mat4.invert(this.normalMatrix, this.localMatrix);
		glmatrix.mat4.transpose(this.normalMatrix, this.normalMatrix);
	}
}
export {SceneObject};
<|endoftext|>


<commit_before>var asciidoctor = require("gulp-asciidoctor");
var del = require("del");
var gulp = require("gulp");
var livereload = require("gulp-livereload");

gulp.task("build", function() {
  return gulp.src("src/**/*.adoc")
    .pipe(asciidoctor({
      base_dir: "src"
    }))
    .pipe(gulp.dest("build"))
    .pipe(livereload());
});

gulp.task("watch", ["build"], function() {
  livereload.listen();
  return gulp.watch(["src/**/*.adoc"], ["build"]);
});

gulp.task("clean", function(cb) {
  del(["build"], cb);
});

gulp.task("default", ["build"]);
<commit_msg>Copy default asciidoctor stylesheet<commit_after>var asciidoctor = require("gulp-asciidoctor");
var del = require("del");
var gulp = require("gulp");
var livereload = require("gulp-livereload");
var path = require("path");

var paths = {
  asciidoctor_js: "node_modules/asciidoctor.js/dist",
  build: "build",
  src: "src"
};

gulp.task("css", function() {
  return gulp.src(path.join(paths.asciidoctor_js, "css", "asciidoctor.css"))
    .pipe(gulp.dest(paths.build));
});

gulp.task("build", ["css"], function() {
  return gulp.src(path.join(paths.src, "**", "*.adoc"))
    .pipe(asciidoctor({
      base_dir: paths.src,
      doctype:'article'
    }))
    .pipe(gulp.dest(paths.build))
    .pipe(livereload());
});

gulp.task("watch", ["build"], function() {
  livereload.listen();
  return gulp.watch([path.join(paths.src, "**", "*.adoc")], ["build"]);
});

gulp.task("clean", function(cb) {
  del(["build"], cb);
});

gulp.task("default", ["build"]);
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const replaceBackslashes = require('../testUtils/replaceBackslashes');
const standalone = require('../standalone');
const stripIndent = require('common-tags').stripIndent;

function fixture(name) {
	return replaceBackslashes(path.join(__dirname, './fixtures/disableOptions', name));
}

it('invalidScopeDisables simple case', () => {
	const config = {
		rules: {
			'block-closing-brace-newline-after': ['always'],
			'block-closing-brace-newline-before': ['always'],
		},
	};

	const css = stripIndent`
    /* stylelint-disable block-no-empty */
    a {}
    /* stylelint-enable block-no-empty */
    a {
      b {} /* stylelint-disable-line block-no-empty */
    }
    `;

	return standalone({
		config,
		code: css,
		reportInvalidScopeDisables: true,
	}).then((linted) => {
		const results = linted.results;

		expect(results).toHaveLength(1);

		expect(invalidScopeDisables(results[0].warnings)).toEqual([
			{
				line: 1,
				column: 1,
				rule: '--report-invalid-scope-disables',
				text: 'Rule "block-no-empty" isn\'t enabled',
				severity: 'error',
			},
			{
				line: 5,
				column: 8,
				rule: '--report-invalid-scope-disables',
				text: 'Rule "block-no-empty" isn\'t enabled',
				severity: 'error',
			},
		]);
	});
});

it('invalidScopeDisables from config', () => {
	const config = {
		reportInvalidScopeDisables: true,
		rules: {
			'block-closing-brace-newline-after': ['always'],
			'block-closing-brace-newline-before': ['always'],
		},
	};

	const css = stripIndent`
    /* stylelint-disable block-no-empty */
    a {}
    /* stylelint-enable block-no-empty */
    a {
      b {} /* stylelint-disable-line block-no-empty */
    }
    `;

	return standalone({
		config,
		code: css,
	}).then((linted) => {
		const results = linted.results;

		expect(results).toHaveLength(1);

		expect(invalidScopeDisables(results[0].warnings)).toEqual([
			{
				line: 1,
				column: 1,
				rule: '--report-invalid-scope-disables',
				text: 'Rule "block-no-empty" isn\'t enabled',
				severity: 'error',
			},
			{
				line: 5,
				column: 8,
				rule: '--report-invalid-scope-disables',
				text: 'Rule "block-no-empty" isn\'t enabled',
				severity: 'error',
			},
		]);
	});
});

it('invalidScopeDisables complex case', () => {
	const config = {
		rules: {
			'block-no-empty': true,
		},
	};

	return standalone({
		config,
		files: [
			fixture('disabled-ranges-1.css'),
			fixture('disabled-ranges-2.css'),
			// ignore files contain `CssSyntaxError`
			fixture('disabled-ranges-3.css'),
		],
		reportInvalidScopeDisables: true,
	}).then((linted) => {
		const results = linted.results;

		expect(results).toHaveLength(3);

		expect(invalidScopeDisables(results[0].warnings)).toEqual([
			{
				line: 1,
				column: 1,
				rule: '--report-invalid-scope-disables',
				text: 'Rule "color-named" isn\'t enabled',
				severity: 'error',
			},
		]);
		expect(invalidScopeDisables(results[1].warnings)).toEqual([
			{
				line: 5,
				column: 6,
				rule: '--report-invalid-scope-disables',
				text: 'Rule "color-named" isn\'t enabled',
				severity: 'error',
			},
		]);
		expect(invalidScopeDisables(results[2].warnings)).toHaveLength(0);
	});
});

it('invalidScopeDisables ignored case', () => {
	const config = {
		rules: {
			'color-named': 'never',
		},
	};

	return standalone({
		config,
		files: [fixture('disabled-ranges-1.css'), fixture('ignored-file.css')],
		ignoreDisables: true,
		ignorePath: fixture('.stylelintignore'),
		reportInvalidScopeDisables: true,
	}).then((linted) => {
		const results = linted.results;

		expect(results).toHaveLength(1);

		expect(invalidScopeDisables(results[0].warnings)).toEqual([
			{
				line: 5,
				column: 1,
				rule: '--report-invalid-scope-disables',
				text: 'Rule "block-no-empty" isn\'t enabled',
				severity: 'error',
			},
		]);
	});
});

it('invalidScopeDisables without config', () => {
	return standalone({
		config: {
			rules: {},
		},
		code: 'a {}',
		ignoreDisables: true,
		reportInvalidScopeDisables: true,
	}).then((linted) => {
		const results = linted.results;

		expect(results).toHaveLength(1);
		expect(invalidScopeDisables(results[0].warnings)).toHaveLength(0);
	});
});

it('invalidScopeDisables for config file', () => {
	return standalone({
		files: [fixture('file-config/disabled-ranges-1.css')],
		reportInvalidScopeDisables: true,
	}).then((linted) => {
		const results = linted.results;

		expect(results).toHaveLength(1);

		expect(invalidScopeDisables(results[0].warnings)).toEqual([
			{
				line: 4,
				column: 1,
				rule: '--report-invalid-scope-disables',
				text: 'Rule "foo" isn\'t enabled',
				severity: 'error',
			},
		]);
	});
});

it('invalidScopeDisables true except', () => {
	const config = {
		rules: {
			'block-closing-brace-newline-after': ['always'],
			'block-closing-brace-newline-before': ['always'],
		},
	};

	const css = stripIndent`
    /* stylelint-disable block-no-empty */
    a {}
    /* stylelint-enable block-no-empty */
    a {
      b {} /* stylelint-disable-line color-hex-case */
    }
    `;

	return standalone({
		config,
		code: css,
		reportInvalidScopeDisables: [true, { except: ['color-hex-case'] }],
	}).then((linted) => {
		const results = linted.results;

		expect(results).toHaveLength(1);

		expect(invalidScopeDisables(results[0].warnings)).toEqual([
			{
				line: 1,
				column: 1,
				rule: '--report-invalid-scope-disables',
				text: 'Rule "block-no-empty" isn\'t enabled',
				severity: 'error',
			},
		]);
	});
});

it('invalidScopeDisables false except', () => {
	const config = {
		rules: {
			'block-closing-brace-newline-after': ['always'],
			'block-closing-brace-newline-before': ['always'],
		},
	};

	const css = stripIndent`
    /* stylelint-disable block-no-empty */
    a {}
    /* stylelint-enable block-no-empty */
    a {
      b {} /* stylelint-disable-line invalid-hex-case */
    }
    `;

	return standalone({
		config,
		code: css,
		reportInvalidScopeDisables: [false, { except: 'invalid-hex-case' }],
	}).then((linted) => {
		const results = linted.results;

		expect(results).toHaveLength(1);

		expect(invalidScopeDisables(results[0].warnings)).toEqual([
			{
				line: 5,
				column: 8,
				rule: '--report-invalid-scope-disables',
				text: 'Rule "invalid-hex-case" isn\'t enabled',
				severity: 'error',
			},
		]);
	});
});

it('invalidScopeDisables severity', () => {
	const config = {
		rules: {
			'block-closing-brace-newline-after': ['always'],
			'block-closing-brace-newline-before': ['always'],
		},
	};

	const css = stripIndent`
    /* stylelint-disable block-no-empty */
    a {}
    /* stylelint-enable block-no-empty */
    a {
      b {} /* stylelint-disable-line block-no-empty */
    }
    `;

	return standalone({
		config,
		code: css,
		reportInvalidScopeDisables: [true, { severity: 'warning' }],
	}).then((linted) => {
		const results = linted.results;

		expect(results).toHaveLength(1);

		expect(invalidScopeDisables(results[0].warnings)).toEqual([
			{
				line: 1,
				column: 1,
				rule: '--report-invalid-scope-disables',
				text: 'Rule "block-no-empty" isn\'t enabled',
				severity: 'warning',
			},
			{
				line: 5,
				column: 8,
				rule: '--report-invalid-scope-disables',
				text: 'Rule "block-no-empty" isn\'t enabled',
				severity: 'warning',
			},
		]);
	});
});

function invalidScopeDisables(warnings) {
	return warnings.filter((warning) => warning.rule === '--report-invalid-scope-disables');
}
<commit_msg>Refactor `lib/__tests__/invalidScopeDisables.test.js` (#5285)<commit_after>'use strict';

const path = require('path');
const { stripIndent } = require('common-tags');

const replaceBackslashes = require('../testUtils/replaceBackslashes');
const standalone = require('../standalone');

function fixture(name) {
	return replaceBackslashes(path.join(__dirname, 'fixtures', 'disableOptions', name));
}

it('invalidScopeDisables simple case', async () => {
	const config = {
		rules: {
			'block-closing-brace-newline-after': ['always'],
			'block-closing-brace-newline-before': ['always'],
		},
	};

	const css = stripIndent`
		/* stylelint-disable block-no-empty */
		a {}
		/* stylelint-enable block-no-empty */
		a {
			b {} /* stylelint-disable-line block-no-empty */
		}
		`;

	const { results } = await standalone({
		config,
		code: css,
		reportInvalidScopeDisables: true,
	});

	expect(results).toHaveLength(1);
	expect(invalidScopeDisables(results[0].warnings)).toEqual([
		{
			line: 1,
			column: 1,
			rule: '--report-invalid-scope-disables',
			text: 'Rule "block-no-empty" isn\'t enabled',
			severity: 'error',
		},
		{
			line: 5,
			column: 7,
			rule: '--report-invalid-scope-disables',
			text: 'Rule "block-no-empty" isn\'t enabled',
			severity: 'error',
		},
	]);
});

it('invalidScopeDisables from config', async () => {
	const config = {
		reportInvalidScopeDisables: true,
		rules: {
			'block-closing-brace-newline-after': ['always'],
			'block-closing-brace-newline-before': ['always'],
		},
	};

	const css = stripIndent`
		/* stylelint-disable block-no-empty */
		a {}
		/* stylelint-enable block-no-empty */
		a {
			b {} /* stylelint-disable-line block-no-empty */
		}
		`;

	const { results } = await standalone({
		config,
		code: css,
	});

	expect(results).toHaveLength(1);
	expect(invalidScopeDisables(results[0].warnings)).toEqual([
		{
			line: 1,
			column: 1,
			rule: '--report-invalid-scope-disables',
			text: 'Rule "block-no-empty" isn\'t enabled',
			severity: 'error',
		},
		{
			line: 5,
			column: 7,
			rule: '--report-invalid-scope-disables',
			text: 'Rule "block-no-empty" isn\'t enabled',
			severity: 'error',
		},
	]);
});

it('invalidScopeDisables complex case', async () => {
	const config = {
		rules: {
			'block-no-empty': true,
		},
	};

	const { results } = await standalone({
		config,
		files: [
			fixture('disabled-ranges-1.css'),
			fixture('disabled-ranges-2.css'),
			// ignore files contain `CssSyntaxError`
			fixture('disabled-ranges-3.css'),
		],
		reportInvalidScopeDisables: true,
	});

	expect(results).toHaveLength(3);
	expect(invalidScopeDisables(results[0].warnings)).toEqual([
		{
			line: 1,
			column: 1,
			rule: '--report-invalid-scope-disables',
			text: 'Rule "color-named" isn\'t enabled',
			severity: 'error',
		},
	]);
	expect(invalidScopeDisables(results[1].warnings)).toEqual([
		{
			line: 5,
			column: 6,
			rule: '--report-invalid-scope-disables',
			text: 'Rule "color-named" isn\'t enabled',
			severity: 'error',
		},
	]);
	expect(invalidScopeDisables(results[2].warnings)).toHaveLength(0);
});

it('invalidScopeDisables ignored case', async () => {
	const config = {
		rules: {
			'color-named': 'never',
		},
	};

	const { results } = await standalone({
		config,
		files: [fixture('disabled-ranges-1.css'), fixture('ignored-file.css')],
		ignoreDisables: true,
		ignorePath: fixture('.stylelintignore'),
		reportInvalidScopeDisables: true,
	});

	expect(results).toHaveLength(1);
	expect(invalidScopeDisables(results[0].warnings)).toEqual([
		{
			line: 5,
			column: 1,
			rule: '--report-invalid-scope-disables',
			text: 'Rule "block-no-empty" isn\'t enabled',
			severity: 'error',
		},
	]);
});

it('invalidScopeDisables without config', async () => {
	const { results } = await standalone({
		config: {
			rules: {},
		},
		code: 'a {}',
		ignoreDisables: true,
		reportInvalidScopeDisables: true,
	});

	expect(results).toHaveLength(1);
	expect(invalidScopeDisables(results[0].warnings)).toHaveLength(0);
});

it('invalidScopeDisables for config file', async () => {
	const { results } = await standalone({
		files: [fixture('file-config/disabled-ranges-1.css')],
		reportInvalidScopeDisables: true,
	});

	expect(results).toHaveLength(1);
	expect(invalidScopeDisables(results[0].warnings)).toEqual([
		{
			line: 4,
			column: 1,
			rule: '--report-invalid-scope-disables',
			text: 'Rule "foo" isn\'t enabled',
			severity: 'error',
		},
	]);
});

it('invalidScopeDisables true except', async () => {
	const config = {
		rules: {
			'block-closing-brace-newline-after': ['always'],
			'block-closing-brace-newline-before': ['always'],
		},
	};

	const css = stripIndent`
		/* stylelint-disable block-no-empty */
		a {}
		/* stylelint-enable block-no-empty */
		a {
			b {} /* stylelint-disable-line color-hex-case */
		}
		`;

	const { results } = await standalone({
		config,
		code: css,
		reportInvalidScopeDisables: [true, { except: ['color-hex-case'] }],
	});

	expect(results).toHaveLength(1);
	expect(invalidScopeDisables(results[0].warnings)).toEqual([
		{
			line: 1,
			column: 1,
			rule: '--report-invalid-scope-disables',
			text: 'Rule "block-no-empty" isn\'t enabled',
			severity: 'error',
		},
	]);
});

it('invalidScopeDisables false except', async () => {
	const config = {
		rules: {
			'block-closing-brace-newline-after': ['always'],
			'block-closing-brace-newline-before': ['always'],
		},
	};

	const css = stripIndent`
		/* stylelint-disable block-no-empty */
		a {}
		/* stylelint-enable block-no-empty */
		a {
			b {} /* stylelint-disable-line invalid-hex-case */
		}
		`;

	const { results } = await standalone({
		config,
		code: css,
		reportInvalidScopeDisables: [false, { except: 'invalid-hex-case' }],
	});

	expect(results).toHaveLength(1);
	expect(invalidScopeDisables(results[0].warnings)).toEqual([
		{
			line: 5,
			column: 7,
			rule: '--report-invalid-scope-disables',
			text: 'Rule "invalid-hex-case" isn\'t enabled',
			severity: 'error',
		},
	]);
});

it('invalidScopeDisables severity', async () => {
	const config = {
		rules: {
			'block-closing-brace-newline-after': ['always'],
			'block-closing-brace-newline-before': ['always'],
		},
	};

	const css = stripIndent`
		/* stylelint-disable block-no-empty */
		a {}
		/* stylelint-enable block-no-empty */
		a {
			b {} /* stylelint-disable-line block-no-empty */
		}
		`;

	const { results } = await standalone({
		config,
		code: css,
		reportInvalidScopeDisables: [true, { severity: 'warning' }],
	});

	expect(results).toHaveLength(1);
	expect(invalidScopeDisables(results[0].warnings)).toEqual([
		{
			line: 1,
			column: 1,
			rule: '--report-invalid-scope-disables',
			text: 'Rule "block-no-empty" isn\'t enabled',
			severity: 'warning',
		},
		{
			line: 5,
			column: 7,
			rule: '--report-invalid-scope-disables',
			text: 'Rule "block-no-empty" isn\'t enabled',
			severity: 'warning',
		},
	]);
});

function invalidScopeDisables(warnings) {
	return warnings.filter((warning) => warning.rule === '--report-invalid-scope-disables');
}
<|endoftext|>


<commit_before>/**
 * This is a new Dojo 1.7 style build profile. Look at util/build/buildControlDefault.js if you want to explore the
 * default Dojo build profile options.
 */

// This function is used to determine whether or not a resource should be tagged as copy-only. See the resourceTags
// property below for more information.
function copyOnly(mid) {
    return mid in {
        // There are no modules right now in dojo boilerplate that are copy-only. If you have some, though, just add
        // them here like this:
        // 'app/module': 1
    };
}

var profile = {
    // basePath is relative to the directory containing this profile file; in this case, it is being set to the
    // src/ directory, which is the same place as the baseUrl directory in the loader configuration. (If you change
    // this, you will also need to update run.js).
    basePath: '..',

    // This is the directory within the release directory where built packages will be placed. The release directory
    // itself is defined by build.sh. You really probably should not use this; it is a legacy option from very old
    // versions of Dojo (like, version 0.1). If you do use it, you will need to update build.sh, too.
    // releaseName: '',

    // Builds a new release.
    action: 'release',

    // Strips all comments from CSS files.
    cssOptimize: 'comments',

    // Excludes tests, demos, and original template files from being included in the built version.
    mini: true,

    // Uses Closure Compiler as the JavaScript minifier. This can also be set to "shrinksafe" to use ShrinkSafe.
    // Note that you will probably get some “errors” with CC; these are generally safe to ignore, and will be
    // fixed in a later version of Dojo. This defaults to "" (no compression) if not provided.
    //optimize: 'closure',

    // We’re building layers, so we need to set the minifier to use for those, too. This defaults to "shrinksafe" if
    // it is not provided.
    layerOptimize: 'closure',

    // Strips all calls to console functions within the code. You can also set this to "warn" to strip everything
    // but console.error, and any other truthy value to strip everything but console.warn and console.error.
    stripConsole: 'all',

    // The default selector engine is not included by default in a dojo.js build in order to make mobile builds
    // smaller. We add it back here to avoid that extra HTTP request. There is also a "lite" selector available; if
    // you use that, you’ll need to set selectorEngine in app/run.js too. (The "lite" engine is only suitable if you
    // are not supporting IE7 and earlier.)
    selectorEngine: 'acme',

    // Builds can be split into multiple different JavaScript files called “layers”. This allows applications to
    // defer loading large sections of code until they are actually required while still allowing multiple modules to
    // be compiled into a single file.
    layers: {
        // This is the main loader module. It is a little special because it is treated like an AMD module even though
        // it is actually just plain JavaScript. There is some extra magic in the build system specifically for this
        // module ID.
        'dojo/dojo': {
            // In addition to the loader (dojo/dojo) and the loader configuration file (app/run), we’re also including
            // the main application (app/main) and the dojo/i18n and dojo/domReady modules because they are one of the
            // conditional dependencies in app/main (the other being app/Dialog) but we don’t want to have to make
            // extra HTTP requests for such tiny files.
            include: [ 'dojo/dojo', 'dojo/i18n', 'dojo/domReady', 'JBrowse' ],

            // By default, the build system will try to include dojo/main in the built dojo/dojo layer, which adds a
            // bunch of stuff we don’t want or need. We want the initial script load to be as small and quick as
            // possible, so we configure it as a custom, bootable base.
            boot: true,
            customBase: true
        },

        // In the demo application, we conditionally require app/Dialog on the client-side, so we’re building a
        // separate layer containing just that client-side code. (Practically speaking, you’d probably just want
        // to roll everything into a single layer, but I wanted to make sure to illustrate multi-layer builds.)
        'JBrowse/View/TrackList/Faceted': {
            include: [ 'JBrowse/View/TrackList/Faceted', 'dojox/data/CsvStore' ],
            exclude: ['JBrowse']
        }
    },

    // Providing hints to the build system allows code to be conditionally removed on a more granular level than
    // simple module dependencies can allow. This is especially useful for creating tiny mobile builds.
    // Keep in mind that dead code removal only happens in minifiers that support it! Currently, ShrinkSafe does not
    // support dead code removal; Closure Compiler and UglifyJS do.
    staticHasFeatures: {
        // The trace & log APIs are used for debugging the loader, so we don’t need them in the build
        'dojo-trace-api':0,
        'dojo-log-api':0,

        // This causes normally private loader data to be exposed for debugging, so we don’t need that either
        'dojo-publish-privates':0,

        // We’re fully async, so get rid of the legacy loader
        'dojo-sync-loader':0,

        // dojo-xhr-factory relies on dojo-sync-loader
        'dojo-xhr-factory':0,

        // We aren’t loading tests in production
        'dojo-test-sniff':0
    },

    // Resource tags are functions that provide hints to the compiler about a given file. The first argument is the
    // filename of the file, and the second argument is the module ID for the file.
    resourceTags: {
        // Files that contain test code.
        test: function (filename, mid) {
            return false;
        },

        // Files that should be copied as-is without being modified by the build system.
        copyOnly: function (filename, mid) {
            return copyOnly(mid);
        },

        // Files that are AMD modules.
        amd: function (filename, mid) {
            return !copyOnly(mid) && /\.js$/.test(filename);
        },

        // Files that should not be copied when the “mini” compiler flag is set to true.
        miniExclude: function (filename, mid) {
            return mid in {
                'JBrowse/profile': 1
            };
        }
    }
};<commit_msg>remove some cruft in build profile<commit_after>// This function is used to determine whether or not a resource should be tagged as copy-only. See the resourceTags
// property below for more information.
function copyOnly(mid) {
    return mid in {
        // There are no modules right now that are copy-only. If you have some, though, just add
        // them here like this:
        // 'app/module': 1
    };
}

var profile = {
    // basePath is relative to the directory containing this profile file; in this case, it is being set to the
    // src/ directory, which is the same place as the baseUrl directory in the loader configuration. (If you change
    // this, you will also need to update run.js).
    basePath: '..',

    // This is the directory within the release directory where built packages will be placed. The release directory
    // itself is defined by build.sh. You really probably should not use this; it is a legacy option from very old
    // versions of Dojo (like, version 0.1). If you do use it, you will need to update build.sh, too.
    // releaseName: '',

    // Builds a new release.
    action: 'release',

    // Strips all comments from CSS files.
    cssOptimize: 'comments',

    // Excludes tests, demos, and original template files from being included in the built version.
    mini: true,

    // Uses Closure Compiler as the JavaScript minifier. This can also be set to "shrinksafe" to use ShrinkSafe.
    // Note that you will probably get some “errors” with CC; these are generally safe to ignore, and will be
    // fixed in a later version of Dojo. This defaults to "" (no compression) if not provided.
    //optimize: 'closure',

    // We’re building layers, so we need to set the minifier to use for those, too. This defaults to "shrinksafe" if
    // it is not provided.
    layerOptimize: 'closure',

    // Strips all calls to console functions within the code. You can also set this to "warn" to strip everything
    // but console.error, and any other truthy value to strip everything but console.warn and console.error.
    stripConsole: 'all',

    // The default selector engine is not included by default in a dojo.js build in order to make mobile builds
    // smaller. We add it back here to avoid that extra HTTP request. There is also a "lite" selector available; if
    // you use that, you’ll need to set selectorEngine in app/run.js too. (The "lite" engine is only suitable if you
    // are not supporting IE7 and earlier.)
    selectorEngine: 'acme',

    // Builds can be split into multiple different JavaScript files called “layers”. This allows applications to
    // defer loading large sections of code until they are actually required while still allowing multiple modules to
    // be compiled into a single file.
    layers: {
        // This is the main loader module. It is a little special because it is treated like an AMD module even though
        // it is actually just plain JavaScript. There is some extra magic in the build system specifically for this
        // module ID.
        'dojo/dojo': {
            include: [ 'dojo/dojo', 'JBrowse' ],
            boot: true,
            customBase: true
        },

        'JBrowse/View/TrackList/Faceted': {
            include: [ 'JBrowse/View/TrackList/Faceted', 'dojox/data/CsvStore' ],
            exclude: ['JBrowse']
        }
    },

    // Providing hints to the build system allows code to be conditionally removed on a more granular level than
    // simple module dependencies can allow. This is especially useful for creating tiny mobile builds.
    // Keep in mind that dead code removal only happens in minifiers that support it! Currently, ShrinkSafe does not
    // support dead code removal; Closure Compiler and UglifyJS do.
    staticHasFeatures: {
        // The trace & log APIs are used for debugging the loader, so we don’t need them in the build
        'dojo-trace-api':0,
        'dojo-log-api':0,

        // This causes normally private loader data to be exposed for debugging, so we don’t need that either
        'dojo-publish-privates':0,

        // We’re fully async, so get rid of the legacy loader
        'dojo-sync-loader':0,

        // dojo-xhr-factory relies on dojo-sync-loader
        'dojo-xhr-factory':0,

        // We aren’t loading tests in production
        'dojo-test-sniff':0
    },

    // Resource tags are functions that provide hints to the compiler about a given file. The first argument is the
    // filename of the file, and the second argument is the module ID for the file.
    resourceTags: {
        // Files that contain test code.
        test: function (filename, mid) {
            return false;
        },

        // Files that should be copied as-is without being modified by the build system.
        copyOnly: function (filename, mid) {
            return copyOnly(mid);
        },

        // Files that are AMD modules.
        amd: function (filename, mid) {
            return !copyOnly(mid) && /\.js$/.test(filename);
        },

        // Files that should not be copied when the “mini” compiler flag is set to true.
        miniExclude: function (filename, mid) {
            return mid in {
                'JBrowse/profile': 1
            };
        }
    }
};<|endoftext|>


<commit_before>var canonnEd3d_attacks = {

	systemsData:
{"systems": [{"coords": {"z": "0", "x": "0", "y": "0"}, "cat": ["100"], "name": "Sol"}, {"coords": {"z": "-340.531", "x": "-78.5938", "y": "-149.625"}, "cat": ["1401"], "name": "Merope"}, {"coords": {"z": "-354.781", "x": "-41.3125", "y": "-58.9688"}, "cat": ["100"], "name": "HIP 22460"}, {"coords": {"z": "-93.25", "x": "-36.7188", "y": "10.9375"}, "cat": ["1402"], "name": "Madngeri"}, {"coords": {"z": "-20.6562", "x": "-33.6562", "y": "72.4688"}, "cat": ["100"], "name": "Alioth"}, {"coords": {"z": "24.8438", "x": "67.5", "y": "-119.469"}, "cat": ["100"], "name": "Achenar"}, {"coords": {"z": "-107.375", "x": "-77.1875", "y": "-123.844"}, "cat": ["1401"], "name": "Lunguni"}, {"coords": {"z": "-339.281", "x": "-86.5938", "y": "-147.031"}, "cat": ["1401"], "name": "Pleiades Sector KC-V c2-11"}, {"coords": {"z": "-129.5", "x": "-42.0938", "y": "-7.40625"}, "cat": ["1402"], "name": "HIP 21559"}, {"coords": {"z": "-18.9062", "x": "-41.625", "y": "-94.9375"}, "cat": ["1400"], "name": "Jemetani"}, {"coords": {"z": "-338.688", "x": "-72.25", "y": "-152.531"}, "cat": ["1401"], "name": "HIP 17694"}, {"coords": {"z": "-76.375", "x": "-41.6875", "y": "-98.5938"}, "cat": ["1401"], "name": "HIP 9599"}, {"coords": {"z": "-352.844", "x": "-70.75", "y": "-157.938"}, "cat": ["1401"], "name": "HIP 17892"}, {"coords": {"z": "-101.5", "x": "-3.65625", "y": "19.6875"}, "cat": ["1400"], "name": "Chan Mina"}, {"coords": {"z": "-319.094", "x": "-63.5938", "y": "-147.406"}, "cat": ["1401"], "name": "Pleiades Sector IR-W d1-55"}, {"coords": {"z": "-301.844", "x": "-86.4062", "y": "-125.156"}, "cat": ["1401"], "name": "Pleiades Sector HR-W d1-57"}, {"coords": {"z": "-162.188", "x": "-33.5", "y": "-70.1875"}, "cat": ["1401"], "name": "Nauni"}, {"coords": {"z": "-92.6875", "x": "-13.1875", "y": "-1.15625"}, "cat": ["1400"], "name": "Esuvit"}, {"coords": {"z": "-348.844", "x": "-88.3125", "y": "-172.938"}, "cat": ["1401"], "name": "HIP 16753"}, {"coords": {"z": "-343.375", "x": "-81.7812", "y": "-149.438"}, "cat": ["1401"], "name": "Maia"}, {"coords": {"z": "-349.125", "x": "-79.125", "y": "-158.688"}, "cat": ["1401"], "name": "HIP 17497"}, {"coords": {"z": "-134.656", "x": "-87.0312", "y": "-71.6875"}, "cat": ["1401"], "name": "Bhal"}, {"coords": {"z": "0.0", "x": "0.0", "y": "0.0"}, "cat": ["100"], "name": "Sol"}, {"coords": {"z": "-82.7188", "x": "-4.46875", "y": "11.0"}, "cat": ["1400"], "name": "Deriv-Dar"}, {"coords": {"z": "27.1562", "x": "55.7188", "y": "17.5938"}, "cat": ["100"], "name": "Shinrarta Dezhra"}, {"coords": {"z": "-85.5312", "x": "-27.6562", "y": "-3.5"}, "cat": ["1402"], "name": "Mentor"}, {"coords": {"z": "-87.125", "x": "-178.656", "y": "77.125"}, "cat": ["100"], "name": "Varati"}, {"coords": {"z": "-125.062", "x": "-86.375", "y": "-12.4062"}, "cat": ["1401"], "name": "Irandan"}, {"coords": {"z": "-107.062", "x": "-11.4375", "y": "18.0312"}, "cat": ["1401"], "name": "Kunuvii"}, {"coords": {"z": "-366.281", "x": "-88.5", "y": "-159.688"}, "cat": ["1401"], "name": "Taygeta"}, {"coords": {"z": "-114.75", "x": "-40.7188", "y": "-22.8438"}, "cat": ["1402"], "name": "Huveang De"}, {"coords": {"z": "-344.438", "x": "-76.7188", "y": "-147.344"}, "cat": ["1401"], "name": "Atlas"}, {"coords": {"z": "-334.219", "x": "-83.9688", "y": "-146.156"}, "cat": ["1401"], "name": "Pleiades Sector HR-W d1-41"}, {"coords": {"z": "17.9688", "x": "-72.2188", "y": "-55.7188"}, "cat": ["1400"], "name": "Nankul"}, {"coords": {"z": "-324.938", "x": "-78.4688", "y": "-144.938"}, "cat": ["1401"], "name": "Pleiades Sector IH-V c2-7"}, {"coords": {"z": "-224.5", "x": "-91.6562", "y": "-62.5312"}, "cat": ["1401"], "name": "Hyades Sector AB-W b2-2"}, {"coords": {"z": "-17.7188", "x": "-71.3125", "y": "-95.3438"}, "cat": ["1401"], "name": "32 c Piscium"}, {"coords": {"z": "-337.094", "x": "-81.0938", "y": "-148.312"}, "cat": ["1401"], "name": "Celaeno"}, {"coords": {"z": "-244.344", "x": "-83.5625", "y": "-73.4062"}, "cat": ["1401"], "name": "42 n Persei"}, {"coords": {"z": "-361.656", "x": "-86.0625", "y": "-159.938"}, "cat": ["1401"], "name": "Electra"}, {"coords": {"z": "-333.375", "x": "-80.1562", "y": "-144.094"}, "cat": ["1401"], "name": "Asterope"}, {"coords": {"z": "10.125", "x": "-53.4062", "y": "-58.4062"}, "cat": ["1400"], "name": "LP 581-36"}, {"coords": {"z": "-260.594", "x": "-82.1875", "y": "-100.938"}, "cat": ["1401"], "name": "Pleiades Sector JC-V d2-62"}], "categories": {"Attacked Systems": {"1402": {"color": "0000ff", "name": "Defended"}, "1400": {"color": "00ff00", "name": "Targeted"}, "1401": {"color": "ff0000", "name": "Attacked"}}, "POI systems": {"100": {"color": "FF9D00", "name": "Systems - POI"}}}}
	,

	init: function () {

		Ed3d.init({
			container: 'edmap',
			json: canonnEd3d_attacks.systemsData,
			withFullscreenToggle: false,
			withHudPanel: true,
			hudMultipleSelect: true,
			effectScaleSystem: [50, 10000],
			startAnim: false,
			showGalaxyInfos: true,
			cameraPos: [25, 14100, -12900],
			systemColor: '#FF9D00'
		});
	}
};
<commit_msg>Switching camera position to make paths more obvious<commit_after>var canonnEd3d_attacks = {

	systemsData:
{"systems": [{"coords": {"z": "0", "x": "0", "y": "0"}, "cat": ["100"], "name": "Sol"}, {"coords": {"z": "-340.531", "x": "-78.5938", "y": "-149.625"}, "cat": ["1401"], "name": "Merope"}, {"coords": {"z": "-354.781", "x": "-41.3125", "y": "-58.9688"}, "cat": ["100"], "name": "HIP 22460"}, {"coords": {"z": "-93.25", "x": "-36.7188", "y": "10.9375"}, "cat": ["1402"], "name": "Madngeri"}, {"coords": {"z": "-20.6562", "x": "-33.6562", "y": "72.4688"}, "cat": ["100"], "name": "Alioth"}, {"coords": {"z": "24.8438", "x": "67.5", "y": "-119.469"}, "cat": ["100"], "name": "Achenar"}, {"coords": {"z": "-107.375", "x": "-77.1875", "y": "-123.844"}, "cat": ["1401"], "name": "Lunguni"}, {"coords": {"z": "-339.281", "x": "-86.5938", "y": "-147.031"}, "cat": ["1401"], "name": "Pleiades Sector KC-V c2-11"}, {"coords": {"z": "-129.5", "x": "-42.0938", "y": "-7.40625"}, "cat": ["1402"], "name": "HIP 21559"}, {"coords": {"z": "-18.9062", "x": "-41.625", "y": "-94.9375"}, "cat": ["1400"], "name": "Jemetani"}, {"coords": {"z": "-338.688", "x": "-72.25", "y": "-152.531"}, "cat": ["1401"], "name": "HIP 17694"}, {"coords": {"z": "-76.375", "x": "-41.6875", "y": "-98.5938"}, "cat": ["1401"], "name": "HIP 9599"}, {"coords": {"z": "-352.844", "x": "-70.75", "y": "-157.938"}, "cat": ["1401"], "name": "HIP 17892"}, {"coords": {"z": "-101.5", "x": "-3.65625", "y": "19.6875"}, "cat": ["1400"], "name": "Chan Mina"}, {"coords": {"z": "-319.094", "x": "-63.5938", "y": "-147.406"}, "cat": ["1401"], "name": "Pleiades Sector IR-W d1-55"}, {"coords": {"z": "-301.844", "x": "-86.4062", "y": "-125.156"}, "cat": ["1401"], "name": "Pleiades Sector HR-W d1-57"}, {"coords": {"z": "-162.188", "x": "-33.5", "y": "-70.1875"}, "cat": ["1401"], "name": "Nauni"}, {"coords": {"z": "-92.6875", "x": "-13.1875", "y": "-1.15625"}, "cat": ["1400"], "name": "Esuvit"}, {"coords": {"z": "-348.844", "x": "-88.3125", "y": "-172.938"}, "cat": ["1401"], "name": "HIP 16753"}, {"coords": {"z": "-343.375", "x": "-81.7812", "y": "-149.438"}, "cat": ["1401"], "name": "Maia"}, {"coords": {"z": "-349.125", "x": "-79.125", "y": "-158.688"}, "cat": ["1401"], "name": "HIP 17497"}, {"coords": {"z": "-134.656", "x": "-87.0312", "y": "-71.6875"}, "cat": ["1401"], "name": "Bhal"}, {"coords": {"z": "0.0", "x": "0.0", "y": "0.0"}, "cat": ["100"], "name": "Sol"}, {"coords": {"z": "-82.7188", "x": "-4.46875", "y": "11.0"}, "cat": ["1400"], "name": "Deriv-Dar"}, {"coords": {"z": "27.1562", "x": "55.7188", "y": "17.5938"}, "cat": ["100"], "name": "Shinrarta Dezhra"}, {"coords": {"z": "-85.5312", "x": "-27.6562", "y": "-3.5"}, "cat": ["1402"], "name": "Mentor"}, {"coords": {"z": "-87.125", "x": "-178.656", "y": "77.125"}, "cat": ["100"], "name": "Varati"}, {"coords": {"z": "-125.062", "x": "-86.375", "y": "-12.4062"}, "cat": ["1401"], "name": "Irandan"}, {"coords": {"z": "-107.062", "x": "-11.4375", "y": "18.0312"}, "cat": ["1401"], "name": "Kunuvii"}, {"coords": {"z": "-366.281", "x": "-88.5", "y": "-159.688"}, "cat": ["1401"], "name": "Taygeta"}, {"coords": {"z": "-114.75", "x": "-40.7188", "y": "-22.8438"}, "cat": ["1402"], "name": "Huveang De"}, {"coords": {"z": "-344.438", "x": "-76.7188", "y": "-147.344"}, "cat": ["1401"], "name": "Atlas"}, {"coords": {"z": "-334.219", "x": "-83.9688", "y": "-146.156"}, "cat": ["1401"], "name": "Pleiades Sector HR-W d1-41"}, {"coords": {"z": "17.9688", "x": "-72.2188", "y": "-55.7188"}, "cat": ["1400"], "name": "Nankul"}, {"coords": {"z": "-324.938", "x": "-78.4688", "y": "-144.938"}, "cat": ["1401"], "name": "Pleiades Sector IH-V c2-7"}, {"coords": {"z": "-224.5", "x": "-91.6562", "y": "-62.5312"}, "cat": ["1401"], "name": "Hyades Sector AB-W b2-2"}, {"coords": {"z": "-17.7188", "x": "-71.3125", "y": "-95.3438"}, "cat": ["1401"], "name": "32 c Piscium"}, {"coords": {"z": "-337.094", "x": "-81.0938", "y": "-148.312"}, "cat": ["1401"], "name": "Celaeno"}, {"coords": {"z": "-244.344", "x": "-83.5625", "y": "-73.4062"}, "cat": ["1401"], "name": "42 n Persei"}, {"coords": {"z": "-361.656", "x": "-86.0625", "y": "-159.938"}, "cat": ["1401"], "name": "Electra"}, {"coords": {"z": "-333.375", "x": "-80.1562", "y": "-144.094"}, "cat": ["1401"], "name": "Asterope"}, {"coords": {"z": "10.125", "x": "-53.4062", "y": "-58.4062"}, "cat": ["1400"], "name": "LP 581-36"}, {"coords": {"z": "-260.594", "x": "-82.1875", "y": "-100.938"}, "cat": ["1401"], "name": "Pleiades Sector JC-V d2-62"}], "categories": {"Attacked Systems": {"1402": {"color": "0000ff", "name": "Defended"}, "1400": {"color": "00ff00", "name": "Targeted"}, "1401": {"color": "ff0000", "name": "Attacked"}}, "POI systems": {"100": {"color": "FF9D00", "name": "Systems - POI"}}}}
	,

	init: function () {

		Ed3d.init({
			container: 'edmap',
			json: canonnEd3d_attacks.systemsData,
			withFullscreenToggle: false,
			withHudPanel: true,
			hudMultipleSelect: true,
			effectScaleSystem: [50, 10000],
			startAnim: false,
			showGalaxyInfos: true,
			cameraPos: [-400, 300, 45],
			systemColor: '#FF9D00'
		});
	}
};
<|endoftext|>


<commit_before>"use strict";

var uniq = require('uniq');

var printFloat = function printFloat (v) {
    return (v === v|0 ? v.toPrecision(2) : v.toString(10));
};

var generateComment = function generateComment (what, rule, outOfBoundValue) {
    var comments = [
        '/**',
        ' * ' + what + ' generated by cellular-automata-voxel-shader 0.3.0',
        ' * ',
        ' * Rule : ' + rule.ruleString,
        ' * Out of bound value : ' + outOfBoundValue,
        ' */'
    ];

    return comments.join('\n');
};

var generateUniformsAndConstants = function generateUniformsAndConstants () {
    return [
        '// console command',
        '// \'xs [iterations] shadername\' : e.g. \'xs 20 shadername\'',
        '',
        '// shader inputs',
        '// uniform vec3    iVolumeSize;    // volume size [1-126]',
        '// uniform float   iColorIndex;    // current color index [1-255]',
        '// uniform vec3    iMirror;        // current mirror mode [0-1]',
        '// uniform vec3    iAxis;          // current axis mode [0-1]',
        '// uniform float   iFrame;         // current frame',
        '// uniform float   iArgs[8];       // user args',
        '',
        '// built-in functions',
        '// float voxel(vec3 v);'
    ].join('\n')
};

var generateGetVoxelGlsl = function generateGetVoxelGlsl (outOfBoundValue) {
    outOfBoundValue = outOfBoundValue || 0;

    if (outOfBoundValue === 'wrap') {
        return [
            'int getVoxel(const in vec3 currentPos, const in vec3 add) {',
            '  vec3 voxelPos = mod((currentPos + add), iVolumeSize);',
            '  return int(voxel(voxelPos));',
            '}'
        ].join('\n');
    } else if(outOfBoundValue === 'clamp') {
        return [
            'int getVoxel(const in vec3 currentPos, const in vec3 add) {',
            '  vec3 voxelPos = (currentPos + add) ;',
            '  voxelPos = clamp(voxelPos, vec3(0.), iVolumeSize - vec3(1.));',
            '  return int(voxel(voxelPos));',
            '}'
        ].join('\n');
    } else {
        return [
            'int getVoxel(const in vec3 currentPos, const in vec3 add) {',
            '  vec3 voxelPos = (currentPos + add) ;',
            '  if(voxelPos.x < 0. || voxelPos.y < 0. || voxelPos.z < 0. || voxelPos.x >= iVolumeSize.x || voxelPos.y >= iVolumeSize.y || voxelPos.z >= iVolumeSize.z) {',
            '    return ' + outOfBoundValue + ';',
            '  } else {',
            '    return int(voxel(voxelPos));',
            '  }',
            '}'
        ].join('\n');
    }
};

var generateGetNeighbourhood = function generateGetNeighbourhood (neighbourhood) {
    var glsl = [
        'int getNeighbourhood (const in vec3 currentPos) {',
        '  int sum = 0;',
        ''
    ];

    for (var i = 0; i < neighbourhood.length; i++) {
        var neighbour = neighbourhood[i];
        glsl.push('  sum += getVoxel(currentPos, vec3(' + printFloat(neighbour[0]) + ', ' + printFloat(neighbour[1]) + ', ' + printFloat(neighbour[2]) + ')) > 0 ? 1 : 0;');
    }

    glsl.push('', '  return sum;', '}');

    return glsl.join('\n');
};

var generateGetNeighbourhoodCond = function generateGetNeighbourhoodCond (neighbourhood) {
    var glsl = [
        'int getNeighbourhoodCond (const in vec3 currentPos, const in int desiredValue) {',
        '  int sum = 0;',
        ''
    ];

    for (var i = 0; i < neighbourhood.length; i++) {
        var neighbour = neighbourhood[i];
        glsl.push('  sum += getVoxel(currentPos, vec3(' + printFloat(neighbour[0]) + ', ' + printFloat(neighbour[1]) + ', ' + printFloat(neighbour[2]) + ')) == desiredValue ? 1 : 0;');
    }

    glsl.push('', '  return sum;', '}');

    return glsl.join('\n');
};

var generateRandomFunction = function generateRandomFunction () {
    return [
        'float rand(vec3 co, float seed) {',
        '  co = co + vec3(fract(sin(dot(vec2(iFrame * 5.9898, seed * 78.5453), vec2(12.9898,78.233))) * 43758.5453));',
        '  return fract(sin(dot(co.xy + vec2(length(co.yz) * 24.0316), vec2(12.9898,78.233)) + dot(co.yz + vec2(length(co.zx) * 24.0316), vec2(12.9898,78.233)) + dot(co.zx + vec2(length(co.xy) * 24.0316), vec2(12.9898,78.233))) * 43758.5453);',
        '}'
    ].join('\n');
};

var generateEqualityCheck = function generateEqualityCheck (values, variable) {
    var checkString = [],
        groupedValues = [],
        previousValue = null,
        i;

    variable = variable || 'sum';

    if (values && values.length) {
        values.sort(function(a, b) {
            return a - b;
        });

        uniq(values, null, true);

        for (i = 0; i < values.length; i++) {
            if (previousValue === values[i] - 1) {
                groupedValues[groupedValues.length - 1].push(values[i]);
            } else {
                groupedValues.push([values[i]]);
            }

            previousValue = values[i];
        }

        for (i = 0; i < groupedValues.length; i++) {
            if (groupedValues[i].length > 1) {
                checkString.push('(' + variable + ' >= ' + groupedValues[i][0] + ' && ' + variable + ' <= ' + groupedValues[i][groupedValues[i].length - 1] + ')');
            } else {
                checkString.push(variable + ' == ' + groupedValues[i][0]);
            }
        }
    } else {
        checkString.push('false');
    }

    return checkString.length > 1 ? '(' + checkString.join(' || ') + ')' : checkString[0];
};

var generateProbabilityCheck = function generateProbabilityCheck(probabilities, sumVariable, positionVariable) {
    var checkString = [],
        groupedValues = [],
        groupProbabilities = [],
        value = null,
        probability = null,
        previousValue = null,
        previousProbability = null,
        i;

    sumVariable = sumVariable || 'sum';
    positionVariable = positionVariable || 'position';

    for (i in probabilities) {
        value = parseInt(i, 10);
        probability = probabilities[i];

        if (previousValue === value - 1 && previousProbability === probability) {
            groupedValues[groupedValues.length - 1].push(value);
        } else {
            groupedValues.push([value]);
            groupProbabilities.push(probability);
        }

        previousValue = value;
        previousProbability = probability;
    }

    for (i = 0; i < groupProbabilities.length; i++) {
        probability = groupProbabilities[i];

        if (probability === 1) {
            if (groupedValues[i].length > 1) {
                checkString.push('(' + sumVariable + ' >= ' + groupedValues[i][0] + ' && ' + sumVariable + ' <= ' + groupedValues[i][groupedValues[i].length - 1] + ')');
            } else {
                checkString.push(variable + ' == ' + groupedValues[i][0]);
            }
        } else if (probability > 0) {
            if (groupedValues[i].length > 1) {
                checkString.push('(' + sumVariable + ' >= ' + groupedValues[i][0] + ' && ' + sumVariable + ' <= ' + groupedValues[i][groupedValues[i].length - 1] + ' && rand(' + positionVariable + ', 1.) < ' + probability + ')');
            } else {
                checkString.push('(' + sumVariable + ' == ' + groupedValues[i][0] + ' && rand(' + positionVariable + ', 1.) < ' + probability + ')');
            }
        }
    }

    return checkString.length > 1 ? '(' + checkString.join(' || ') + ')' : checkString[0];
};

var generateProcessGlslGenerations = function generateProcessGlslGenerations (neighbourhood, stateCount, survival, birth) {
    var glsl = [
        generateGetNeighbourhoodCond(neighbourhood),
        '',
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhoodCond(position, 1);',
        '  if (currentValue == 0 && ' + generateEqualityCheck(birth) + ') {',
        '    return 1;',
        '  } else if (currentValue == 1 && ' + generateEqualityCheck(survival) + ') {',
        '    return 1;',
        '  } else if (currentValue > 0) {',
        '    return int(mod(float(currentValue + 1), ' + printFloat(stateCount) + '));',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslLife = function generateProcessGlslLife (neighbourhood, survival, birth) {
    var glsl = [
        generateGetNeighbourhood(neighbourhood),
        '',
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhood(position);',
        '  if (currentValue == 0 && ' + generateEqualityCheck(birth) + ') {',
        '    return 1;',
        '  } else if (currentValue > 0 && ' + generateEqualityCheck(survival) + ') {',
        '    return 1;',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslStochastic = function generateProcessGlslStochastic (neighbourhood, survival, birth) {
    var glsl = [
        generateRandomFunction(),
        '',
        generateGetNeighbourhood(neighbourhood),
        '',
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhood(position);',
        '  if (currentValue == 0 && ' + generateProbabilityCheck(birth) + ') {',
        '    return 1;',
        '  } else if (currentValue > 0 && ' + generateProbabilityCheck(survival) + ') {',
        '    return 1;',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslVote = function generateProcessGlslVote (neighbourhood, votes) {
    var glsl = [
        generateGetNeighbourhood(neighbourhood),
        '',
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhood(position) + (currentValue > 0 ? 1 : 0);',
        '  if (' + generateEqualityCheck(votes) + ') {',
        '    return 1;',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslLuky = function generateProcessGlslLuky (neighbourhood, lowSurvival, highSurvival, lowBirth, highBirth) {
    var glsl = [
        generateGetNeighbourhood(neighbourhood),
        '',
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhood(position);',
        '  if (currentValue == 0 && sum >= ' + lowBirth + ' && sum <= ' + highBirth + ') {',
        '    return 1;',
        '  } else if (currentValue > 0 && sum >= ' + lowSurvival + ' && sum <= ' + highSurvival + ') {',
        '    return 1;',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslNluky = function generateProcessGlslNluky (neighbourhood, stateCount, lowSurvival, highSurvival, lowBirth, highBirth) {
    var glsl = [
        generateGetNeighbourhoodCond(neighbourhood),
        '',
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhoodCond(position, 1);',
        '  if (currentValue == 0 && sum >= ' + lowBirth + ' && sum <= ' + highBirth + ') {',
        '    return 1;',
        '  } else if (currentValue == 1 && sum >= ' + lowSurvival + ' && sum <= ' + highSurvival + ') {',
        '    return 1;',
        '  } else if (currentValue == 1) {',
        '    return ' + (2 % (2 + stateCount * 2)) + ';',
        '  } else if (currentValue >= 2) {',
        '    return int(mod(float(currentValue + 2), ' + printFloat(2 + stateCount * 2) + '));',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslCyclic = function generateProcessGlslCyclic (neighbourhood, stateCount, threshold, greenbergHastingsModel) {
    var glsl = [
        generateGetNeighbourhoodCond(neighbourhood),
        '',
        'int process(const in int currentValue, const in vec3 position) {',
        '  int nextValue = int(mod(float(currentValue + 1), ' + printFloat(stateCount) + '));',
        '  int sum = getNeighbourhoodCond(position, nextValue);',
        '  if (sum >= ' + threshold + (greenbergHastingsModel ? ' || currentValue > 0' : '') + ') {',
        '    return nextValue;',
        '  }',
        '  return currentValue;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlsl = function generateProcessGlsl (neighbourhood, rule) {
    if (rule.ruleFormat === 'life' || rule.ruleFormat === 'extended-life') {
        return generateProcessGlslLife(neighbourhood, rule.survival, rule.birth);
    } else if (rule.ruleFormat === 'extended-stochastic') {
        return generateProcessGlslStochastic(neighbourhood, rule.survival, rule.birth);
    } else if (rule.ruleFormat === 'generations' || rule.ruleFormat === 'extended-generations') {
        return generateProcessGlslGenerations(neighbourhood, rule.stateCount, rule.survival, rule.birth);
    } else if (rule.ruleFormat === 'vote') {
        return generateProcessGlslVote(neighbourhood, rule.vote);
    } else if (rule.ruleFormat === 'luky') {
        return generateProcessGlslLuky(neighbourhood, rule.lowSurvival, rule.highSurvival, rule.lowBirth, rule.highBirth);
    } else if (rule.ruleFormat === 'nluky') {
        return generateProcessGlslNluky(neighbourhood, rule.stateCount, rule.lowSurvival, rule.highSurvival, rule.lowBirth, rule.highBirth);
    } else if (rule.ruleFormat === 'cyclic') {
        return generateProcessGlslCyclic(neighbourhood, rule.stateCount, rule.threshold, rule.greenbergHastingsModel);
    }

    throw new Error('Unsupported ruleFormat : ' + rule.ruleFormat);
};

var generateGlsl = function generateGlsl (rule, neighbourhood, outOfBoundValue) {
    var glsl = [
        generateComment('Voxel Shader for MagicaVoxel 0.97.1', rule, outOfBoundValue),
        '',
        generateUniformsAndConstants(),
        '',
        generateGetVoxelGlsl(outOfBoundValue),
        '',
        generateProcessGlsl(neighbourhood, rule),
        '',
        'float map(vec3 v) {',
        '  int currentValue = int(voxel(v));',
        '  return float(process(currentValue, v));',
        '}'
    ];

    return glsl.join('\n')
};

module.exports = generateGlsl;
<commit_msg>fix call to undefined 'variable' variable<commit_after>"use strict";

var uniq = require('uniq');

var printFloat = function printFloat (v) {
    return (v === v|0 ? v.toPrecision(2) : v.toString(10));
};

var generateComment = function generateComment (what, rule, outOfBoundValue) {
    var comments = [
        '/**',
        ' * ' + what + ' generated by cellular-automata-voxel-shader 0.3.0',
        ' * ',
        ' * Rule : ' + rule.ruleString,
        ' * Out of bound value : ' + outOfBoundValue,
        ' */'
    ];

    return comments.join('\n');
};

var generateUniformsAndConstants = function generateUniformsAndConstants () {
    return [
        '// console command',
        '// \'xs [iterations] shadername\' : e.g. \'xs 20 shadername\'',
        '',
        '// shader inputs',
        '// uniform vec3    iVolumeSize;    // volume size [1-126]',
        '// uniform float   iColorIndex;    // current color index [1-255]',
        '// uniform vec3    iMirror;        // current mirror mode [0-1]',
        '// uniform vec3    iAxis;          // current axis mode [0-1]',
        '// uniform float   iFrame;         // current frame',
        '// uniform float   iArgs[8];       // user args',
        '',
        '// built-in functions',
        '// float voxel(vec3 v);'
    ].join('\n')
};

var generateGetVoxelGlsl = function generateGetVoxelGlsl (outOfBoundValue) {
    outOfBoundValue = outOfBoundValue || 0;

    if (outOfBoundValue === 'wrap') {
        return [
            'int getVoxel(const in vec3 currentPos, const in vec3 add) {',
            '  vec3 voxelPos = mod((currentPos + add), iVolumeSize);',
            '  return int(voxel(voxelPos));',
            '}'
        ].join('\n');
    } else if(outOfBoundValue === 'clamp') {
        return [
            'int getVoxel(const in vec3 currentPos, const in vec3 add) {',
            '  vec3 voxelPos = (currentPos + add) ;',
            '  voxelPos = clamp(voxelPos, vec3(0.), iVolumeSize - vec3(1.));',
            '  return int(voxel(voxelPos));',
            '}'
        ].join('\n');
    } else {
        return [
            'int getVoxel(const in vec3 currentPos, const in vec3 add) {',
            '  vec3 voxelPos = (currentPos + add) ;',
            '  if(voxelPos.x < 0. || voxelPos.y < 0. || voxelPos.z < 0. || voxelPos.x >= iVolumeSize.x || voxelPos.y >= iVolumeSize.y || voxelPos.z >= iVolumeSize.z) {',
            '    return ' + outOfBoundValue + ';',
            '  } else {',
            '    return int(voxel(voxelPos));',
            '  }',
            '}'
        ].join('\n');
    }
};

var generateGetNeighbourhood = function generateGetNeighbourhood (neighbourhood) {
    var glsl = [
        'int getNeighbourhood (const in vec3 currentPos) {',
        '  int sum = 0;',
        ''
    ];

    for (var i = 0; i < neighbourhood.length; i++) {
        var neighbour = neighbourhood[i];
        glsl.push('  sum += getVoxel(currentPos, vec3(' + printFloat(neighbour[0]) + ', ' + printFloat(neighbour[1]) + ', ' + printFloat(neighbour[2]) + ')) > 0 ? 1 : 0;');
    }

    glsl.push('', '  return sum;', '}');

    return glsl.join('\n');
};

var generateGetNeighbourhoodCond = function generateGetNeighbourhoodCond (neighbourhood) {
    var glsl = [
        'int getNeighbourhoodCond (const in vec3 currentPos, const in int desiredValue) {',
        '  int sum = 0;',
        ''
    ];

    for (var i = 0; i < neighbourhood.length; i++) {
        var neighbour = neighbourhood[i];
        glsl.push('  sum += getVoxel(currentPos, vec3(' + printFloat(neighbour[0]) + ', ' + printFloat(neighbour[1]) + ', ' + printFloat(neighbour[2]) + ')) == desiredValue ? 1 : 0;');
    }

    glsl.push('', '  return sum;', '}');

    return glsl.join('\n');
};

var generateRandomFunction = function generateRandomFunction () {
    return [
        'float rand(vec3 co, float seed) {',
        '  co = co + vec3(fract(sin(dot(vec2(iFrame * 5.9898, seed * 78.5453), vec2(12.9898,78.233))) * 43758.5453));',
        '  return fract(sin(dot(co.xy + vec2(length(co.yz) * 24.0316), vec2(12.9898,78.233)) + dot(co.yz + vec2(length(co.zx) * 24.0316), vec2(12.9898,78.233)) + dot(co.zx + vec2(length(co.xy) * 24.0316), vec2(12.9898,78.233))) * 43758.5453);',
        '}'
    ].join('\n');
};

var compareNumbers = function compareNumbers (a, b) {
    return a - b;
};

var generateEqualityCheck = function generateEqualityCheck (values, variable) {
    var checkString = [],
        groupedValues = [],
        previousValue = null,
        i;

    variable = variable || 'sum';

    if (values && values.length) {
        uniq(values, compareNumbers, true);

        for (i = 0; i < values.length; i++) {
            if (previousValue === values[i] - 1) {
                groupedValues[groupedValues.length - 1].push(values[i]);
            } else {
                groupedValues.push([values[i]]);
            }

            previousValue = values[i];
        }

        for (i = 0; i < groupedValues.length; i++) {
            if (groupedValues[i].length > 1) {
                checkString.push('(' + variable + ' >= ' + groupedValues[i][0] + ' && ' + variable + ' <= ' + groupedValues[i][groupedValues[i].length - 1] + ')');
            } else {
                checkString.push(variable + ' == ' + groupedValues[i][0]);
            }
        }
    } else {
        checkString.push('false');
    }

    return checkString.length > 1 ? '(' + checkString.join(' || ') + ')' : checkString[0];
};

var generateProbabilityCheck = function generateProbabilityCheck(probabilities, sumVariable, positionVariable) {
    var checkString = [],
        groupedValues = [],
        groupProbabilities = [],
        value = null,
        probability = null,
        previousValue = null,
        previousProbability = null,
        i;

    sumVariable = sumVariable || 'sum';
    positionVariable = positionVariable || 'position';

    for (i in probabilities) {
        value = parseInt(i, 10);
        probability = probabilities[i];

        if (previousValue === value - 1 && previousProbability === probability) {
            groupedValues[groupedValues.length - 1].push(value);
        } else {
            groupedValues.push([value]);
            groupProbabilities.push(probability);
        }

        previousValue = value;
        previousProbability = probability;
    }

    for (i = 0; i < groupProbabilities.length; i++) {
        probability = groupProbabilities[i];

        if (probability === 1) {
            if (groupedValues[i].length > 1) {
                checkString.push('(' + sumVariable + ' >= ' + groupedValues[i][0] + ' && ' + sumVariable + ' <= ' + groupedValues[i][groupedValues[i].length - 1] + ')');
            } else {
                checkString.push(sumVariable + ' == ' + groupedValues[i][0]);
            }
        } else if (probability > 0) {
            if (groupedValues[i].length > 1) {
                checkString.push('(' + sumVariable + ' >= ' + groupedValues[i][0] + ' && ' + sumVariable + ' <= ' + groupedValues[i][groupedValues[i].length - 1] + ' && rand(' + positionVariable + ', 1.) < ' + probability + ')');
            } else {
                checkString.push('(' + sumVariable + ' == ' + groupedValues[i][0] + ' && rand(' + positionVariable + ', 1.) < ' + probability + ')');
            }
        }
    }

    return checkString.length > 1 ? '(' + checkString.join(' || ') + ')' : checkString[0];
};

var generateProcessGlslGenerations = function generateProcessGlslGenerations (neighbourhood, stateCount, survival, birth) {
    var glsl = [
        generateGetNeighbourhoodCond(neighbourhood),
        '',
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhoodCond(position, 1);',
        '  if (currentValue == 0 && ' + generateEqualityCheck(birth) + ') {',
        '    return 1;',
        '  } else if (currentValue == 1 && ' + generateEqualityCheck(survival) + ') {',
        '    return 1;',
        '  } else if (currentValue > 0) {',
        '    return int(mod(float(currentValue + 1), ' + printFloat(stateCount) + '));',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslLife = function generateProcessGlslLife (neighbourhood, survival, birth) {
    var glsl = [
        generateGetNeighbourhood(neighbourhood),
        '',
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhood(position);',
        '  if (currentValue == 0 && ' + generateEqualityCheck(birth) + ') {',
        '    return 1;',
        '  } else if (currentValue > 0 && ' + generateEqualityCheck(survival) + ') {',
        '    return 1;',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslStochastic = function generateProcessGlslStochastic (neighbourhood, survival, birth) {
    var glsl = [
        generateRandomFunction(),
        '',
        generateGetNeighbourhood(neighbourhood),
        '',
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhood(position);',
        '  if (currentValue == 0 && ' + generateProbabilityCheck(birth) + ') {',
        '    return 1;',
        '  } else if (currentValue > 0 && ' + generateProbabilityCheck(survival) + ') {',
        '    return 1;',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslVote = function generateProcessGlslVote (neighbourhood, votes) {
    var glsl = [
        generateGetNeighbourhood(neighbourhood),
        '',
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhood(position) + (currentValue > 0 ? 1 : 0);',
        '  if (' + generateEqualityCheck(votes) + ') {',
        '    return 1;',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslLuky = function generateProcessGlslLuky (neighbourhood, lowSurvival, highSurvival, lowBirth, highBirth) {
    var glsl = [
        generateGetNeighbourhood(neighbourhood),
        '',
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhood(position);',
        '  if (currentValue == 0 && sum >= ' + lowBirth + ' && sum <= ' + highBirth + ') {',
        '    return 1;',
        '  } else if (currentValue > 0 && sum >= ' + lowSurvival + ' && sum <= ' + highSurvival + ') {',
        '    return 1;',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslNluky = function generateProcessGlslNluky (neighbourhood, stateCount, lowSurvival, highSurvival, lowBirth, highBirth) {
    var glsl = [
        generateGetNeighbourhoodCond(neighbourhood),
        '',
        'int process(const in int currentValue, const in vec3 position) {',
        '  int sum = getNeighbourhoodCond(position, 1);',
        '  if (currentValue == 0 && sum >= ' + lowBirth + ' && sum <= ' + highBirth + ') {',
        '    return 1;',
        '  } else if (currentValue == 1 && sum >= ' + lowSurvival + ' && sum <= ' + highSurvival + ') {',
        '    return 1;',
        '  } else if (currentValue == 1) {',
        '    return ' + (2 % (2 + stateCount * 2)) + ';',
        '  } else if (currentValue >= 2) {',
        '    return int(mod(float(currentValue + 2), ' + printFloat(2 + stateCount * 2) + '));',
        '  }',
        '  return 0;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlslCyclic = function generateProcessGlslCyclic (neighbourhood, stateCount, threshold, greenbergHastingsModel) {
    var glsl = [
        generateGetNeighbourhoodCond(neighbourhood),
        '',
        'int process(const in int currentValue, const in vec3 position) {',
        '  int nextValue = int(mod(float(currentValue + 1), ' + printFloat(stateCount) + '));',
        '  int sum = getNeighbourhoodCond(position, nextValue);',
        '  if (sum >= ' + threshold + (greenbergHastingsModel ? ' || currentValue > 0' : '') + ') {',
        '    return nextValue;',
        '  }',
        '  return currentValue;',
        '}'
    ];

    return glsl.join('\n');
};

var generateProcessGlsl = function generateProcessGlsl (neighbourhood, rule) {
    if (rule.ruleFormat === 'life' || rule.ruleFormat === 'extended-life') {
        return generateProcessGlslLife(neighbourhood, rule.survival, rule.birth);
    } else if (rule.ruleFormat === 'extended-stochastic') {
        return generateProcessGlslStochastic(neighbourhood, rule.survival, rule.birth);
    } else if (rule.ruleFormat === 'generations' || rule.ruleFormat === 'extended-generations') {
        return generateProcessGlslGenerations(neighbourhood, rule.stateCount, rule.survival, rule.birth);
    } else if (rule.ruleFormat === 'vote') {
        return generateProcessGlslVote(neighbourhood, rule.vote);
    } else if (rule.ruleFormat === 'luky') {
        return generateProcessGlslLuky(neighbourhood, rule.lowSurvival, rule.highSurvival, rule.lowBirth, rule.highBirth);
    } else if (rule.ruleFormat === 'nluky') {
        return generateProcessGlslNluky(neighbourhood, rule.stateCount, rule.lowSurvival, rule.highSurvival, rule.lowBirth, rule.highBirth);
    } else if (rule.ruleFormat === 'cyclic') {
        return generateProcessGlslCyclic(neighbourhood, rule.stateCount, rule.threshold, rule.greenbergHastingsModel);
    }

    throw new Error('Unsupported ruleFormat : ' + rule.ruleFormat);
};

var generateGlsl = function generateGlsl (rule, neighbourhood, outOfBoundValue) {
    var glsl = [
        generateComment('Voxel Shader for MagicaVoxel 0.97.1', rule, outOfBoundValue),
        '',
        generateUniformsAndConstants(),
        '',
        generateGetVoxelGlsl(outOfBoundValue),
        '',
        generateProcessGlsl(neighbourhood, rule),
        '',
        'float map(vec3 v) {',
        '  int currentValue = int(voxel(v));',
        '  return float(process(currentValue, v));',
        '}'
    ];

    return glsl.join('\n')
};

module.exports = generateGlsl;
<|endoftext|>


<commit_before>Meteor.methods({
	gameDelete: function(game) {
		check(game, {
			_id: String
		});
		Games.remove({
			_id: game._id
		});
	}
});
<commit_msg>Refactor gameDelete method<commit_after>Meteor.methods({
	gameDelete: function(gameId) {
		Games.remove({
			_id: gameId
		});
	}
});
<|endoftext|>