<commit_before>import macro from 'vtk.js/Sources/macro';

import vtkAnnotatedCubeActor from 'vtk.js/Sources/Rendering/Core/AnnotatedCubeActor';
import vtkCornerAnnotation from 'vtk.js/Sources/Interaction/UI/CornerAnnotation';
import vtkInteractorStyleManipulator from 'vtk.js/Sources/Interaction/Style/InteractorStyleManipulator';
import vtkMatrixBuilder from 'vtk.js/Sources/Common/Core/MatrixBuilder';
import vtkOpenGLRenderWindow from 'vtk.js/Sources/Rendering/OpenGL/RenderWindow';
import vtkOrientationMarkerWidget from 'vtk.js/Sources/Interaction/Widgets/OrientationMarkerWidget';
import vtkRenderer from 'vtk.js/Sources/Rendering/Core/Renderer';
import vtkRenderWindow from 'vtk.js/Sources/Rendering/Core/RenderWindow';
import vtkRenderWindowInteractor from 'vtk.js/Sources/Rendering/Core/RenderWindowInteractor';

import InteractionPresets from 'vtk.js/Sources/Interaction/Style/InteractorStyleManipulator/Presets';
import AnnotatedCubePresets from 'vtk.js/Sources/Rendering/Core/AnnotatedCubeActor/Presets';

// ----------------------------------------------------------------------------
// vtkViewProxy methods
// ----------------------------------------------------------------------------

function vtkViewProxy(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkViewProxy');

  // Private --------------------------------------------------------------------

  function updateAnnotationColor() {
    const [r, g, b] = model.renderer.getBackground();
    model.cornerAnnotation.getAnnotationContainer().style.color =
      r + g + b > 1.5 ? 'black' : 'white';
  }

  // Setup --------------------------------------------------------------------
  model.renderWindow = vtkRenderWindow.newInstance();
  model.renderer = vtkRenderer.newInstance({ background: [0, 0, 0] });
  model.renderWindow.addRenderer(model.renderer);

  model.openglRenderWindow = vtkOpenGLRenderWindow.newInstance();
  model.renderWindow.addView(model.openglRenderWindow);

  model.interactor = vtkRenderWindowInteractor.newInstance();
  model.interactor.setView(model.openglRenderWindow);

  model.interactorStyle3D = vtkInteractorStyleManipulator.newInstance();
  model.interactorStyle2D = vtkInteractorStyleManipulator.newInstance();

  // Apply default interaction styles
  InteractionPresets.applyPreset('3D', model.interactorStyle3D);
  InteractionPresets.applyPreset('2D', model.interactorStyle2D);

  model.cornerAnnotation = vtkCornerAnnotation.newInstance();

  // Setup interaction
  model.interactor.setInteractorStyle(
    model.useParallelRendering
      ? model.interactorStyle2D
      : model.interactorStyle3D
  );
  model.camera = model.renderer.getActiveCamera();
  model.camera.setParallelProjection(!!model.useParallelRendering);

  // Orientation a cube setup -------------------------------------------------

  model.orientationAxes = vtkAnnotatedCubeActor.newInstance();
  AnnotatedCubePresets.applyPreset('default', model.orientationAxes);
  model.orientationWidget = vtkOrientationMarkerWidget.newInstance({
    actor: model.orientationAxes,
    interactor: model.renderWindow.getInteractor(),
  });
  model.orientationWidget.setEnabled(true);
  model.orientationWidget.setViewportCorner(
    vtkOrientationMarkerWidget.Corners.BOTTOM_LEFT
  );
  model.orientationWidget.setViewportSize(0.1);

  // API ----------------------------------------------------------------------

  publicAPI.setPresetToInteractor3D = (nameOrDefinitions) => {
    if (Array.isArray(nameOrDefinitions)) {
      return InteractionPresets.applyDefinitions(
        nameOrDefinitions,
        model.interactorStyle3D
      );
    }
    return InteractionPresets.applyPreset(
      nameOrDefinitions,
      model.interactorStyle3D
    );
  };

  // --------------------------------------------------------------------------

  publicAPI.setPresetToInteractor2D = (nameOrDefinitions) => {
    if (Array.isArray(nameOrDefinitions)) {
      return InteractionPresets.applyDefinitions(
        nameOrDefinitions,
        model.interactorStyle2D
      );
    }
    return InteractionPresets.applyPreset(
      nameOrDefinitions,
      model.interactorStyle2D
    );
  };

  // --------------------------------------------------------------------------

  publicAPI.setPresetToOrientationAxes = (nameOrDefinitions) => {
    if (typeof nameOrDefinitions === 'string') {
      return AnnotatedCubePresets.applyPreset(
        nameOrDefinitions,
        model.orientationAxes
      );
    }
    return AnnotatedCubePresets.applyDefinitions(
      nameOrDefinitions,
      model.orientationAxes
    );
  };

  // --------------------------------------------------------------------------

  publicAPI.setContainer = (container) => {
    if (model.container) {
      model.interactor.unbindEvents(model.container);
      model.openglRenderWindow.setContainer(null);
      model.cornerAnnotation.setContainer(null);
    }

    model.container = container;

    if (container) {
      model.openglRenderWindow.setContainer(container);
      model.cornerAnnotation.setContainer(container);
      model.interactor.initialize();
      model.interactor.bindEvents(container);
    }
  };

  // --------------------------------------------------------------------------

  publicAPI.resize = () => {
    if (model.container) {
      const dims = model.container.getBoundingClientRect();
      model.openglRenderWindow.setSize(
        Math.max(10, Math.floor(dims.width)),
        Math.max(10, Math.floor(dims.height))
      );
      publicAPI.renderLater();
    }
  };

  // --------------------------------------------------------------------------

  publicAPI.renderLater = () => {
    if (model.representations.length > 0 && model.resetCameraOnFirstRender) {
      model.resetCameraOnFirstRender = false;
      // console.log('==> resetCamera before renderLater', model.proxyId);
      publicAPI.resetCamera();
    }
    model.orientationWidget.updateMarkerOrientation();
    setTimeout(model.renderWindow.render, 0);
  };

  // --------------------------------------------------------------------------

  publicAPI.addRepresentation = (representation) => {
    if (!representation) {
      return;
    }
    if (model.representations.indexOf(representation) === -1) {
      model.representations.push(representation);
      representation.getActors().forEach(model.renderer.addActor);
      representation.getVolumes().forEach(model.renderer.addVolume);
    }
  };

  // --------------------------------------------------------------------------

  publicAPI.removeRepresentation = (representation) => {
    if (!representation) {
      return;
    }
    if (model.representations.indexOf(representation) !== -1) {
      model.representations = model.representations.filter(
        (r) => r !== representation
      );
      representation.getActors().forEach(model.renderer.removeActor);
      representation.getVolumes().forEach(model.renderer.removeVolume);
    }
  };

  // --------------------------------------------------------------------------

  publicAPI.resetCamera = () => {
    model.renderer.resetCamera();
    model.renderer.resetCameraClippingRange();
    model.interactorStyle2D.setCenterOfRotation(model.camera.getFocalPoint());
    model.interactorStyle3D.setCenterOfRotation(model.camera.getFocalPoint());
    publicAPI.renderLater();
  };

  // --------------------------------------------------------------------------

  publicAPI.captureImage = () => model.renderWindow.captureImages()[0];

  // --------------------------------------------------------------------------

  publicAPI.openCaptureImage = (target = '_blank') => {
    const image = new Image();
    image.src = publicAPI.captureImage();
    const w = window.open('', target);
    w.document.write(image.outerHTML);
    w.document.title = 'vtk.js Image Capture';
    window.focus();
  };

  // --------------------------------------------------------------------------

  publicAPI.setCornerAnnotation = (corner, templateString) => {
    model.cornerAnnotation.updateTemplates({
      [corner]: (meta) =>
        vtkCornerAnnotation.applyTemplate(templateString, meta),
    });
  };

  // --------------------------------------------------------------------------

  publicAPI.setCornerAnnotations = (annotations, useTemplateString = false) => {
    if (useTemplateString) {
      Object.keys(annotations).forEach((key) => {
        publicAPI.setCornerAnnotation(key, annotations[key]);
      });
    } else {
      model.cornerAnnotation.updateTemplates(annotations);
    }
  };

  // --------------------------------------------------------------------------

  publicAPI.updateCornerAnnotation = (meta) =>
    model.cornerAnnotation.updateMetadata(meta);

  // --------------------------------------------------------------------------

  publicAPI.setAnnotationOpacity = (opacity) => {
    if (model.annotationOpacity !== Number(opacity)) {
      model.annotationOpacity = Number(opacity);
      model.cornerAnnotation.getAnnotationContainer().style.opacity = opacity;
      publicAPI.modified();
    }
  };

  // --------------------------------------------------------------------------

  publicAPI.setBackground = macro.chain(
    model.renderer.setBackground,
    updateAnnotationColor
  );

  // --------------------------------------------------------------------------

  publicAPI.getBackground = model.renderer.getBackground;

  // --------------------------------------------------------------------------

  publicAPI.setAnimation = (enable, requester = publicAPI) => {
    if (enable) {
      model.renderWindow.getInteractor().requestAnimation(requester);
    } else {
      model.renderWindow.getInteractor().cancelAnimation(requester);
    }
  };

  // --------------------------------------------------------------------------

  publicAPI.updateOrientation = (axisIndex, orientation, viewUp) => {
    if (axisIndex === undefined) {
      return;
    }
    model.axis = axisIndex;
    model.orientation = orientation;
    model.viewUp = viewUp;
    const position = model.camera.getFocalPoint();
    position[model.axis] += model.orientation;
    model.camera.setPosition(...position);
    model.camera.setViewUp(...viewUp);
  };

  // --------------------------------------------------------------------------

  publicAPI.resetOrientation = () => {
    publicAPI.updateOrientation(model.axis, model.orientation, model.viewUp);
  };

  // --------------------------------------------------------------------------

  publicAPI.rotate = (angle) => {
    const { viewUp, focalPoint, position } = model.camera.get(
      'viewUp',
      'focalPoint',
      'position'
    );
    const axis = [
      focalPoint[0] - position[0],
      focalPoint[1] - position[1],
      focalPoint[2] - position[2],
    ];

    vtkMatrixBuilder
      .buildFromDegree()
      .rotate(Number.isNaN(angle) ? 90 : angle, axis)
      .apply(viewUp);

    model.camera.setViewUp(...viewUp);
    model.camera.modified();
    model.orientationWidget.updateMarkerOrientation();
    model.renderWindow.render();
  };

  // --------------------------------------------------------------------------
  // Initialization from state or input
  // --------------------------------------------------------------------------

  publicAPI.updateOrientation(model.axis, model.orientation, model.viewUp);
  updateAnnotationColor();
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  representations: [],
  sectionName: 'view',
  annotationOpacity: 1,
  resetCameraOnFirstRender: true,
};

// ----------------------------------------------------------------------------

function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  macro.obj(publicAPI, model);
  macro.get(publicAPI, model, [
    'representations',
    'renderer',
    'renderWindow',
    'openglRenderWindow',
    'interactor',
    'interactorStyle2D',
    'interactorStyle3D',
    'container',
    'useParallelRendering',
    'camera',
    'cornerAnnotation',
    'annotationOpacity',
  ]);

  // Object specific methods
  vtkViewProxy(publicAPI, model);

  // Proxy handling
  macro.proxy(publicAPI, model);
  macro.proxyPropertyMapping(publicAPI, model, {
    orientationAxesVisibility: {
      modelKey: 'orientationWidget',
      property: 'enabled',
    },
    orientationAxesCorner: {
      modelKey: 'orientationWidget',
      property: 'viewportCorner',
    },
    orientationAxesSize: {
      modelKey: 'orientationWidget',
      property: 'viewportSize',
    },
    cameraViewUp: { modelKey: 'camera', property: 'viewUp', modified: false },
    cameraPosition: {
      modelKey: 'camera',
      property: 'position',
      modified: false,
    },
    cameraFocalPoint: {
      modelKey: 'camera',
      property: 'focalPoint',
      modified: false,
    },
  });
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend, 'vtkViewProxy');

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<commit_msg>fix(ViewProxy): Allow links and presetToOrientationAxes as prop<commit_after>import macro from 'vtk.js/Sources/macro';

import vtkAnnotatedCubeActor from 'vtk.js/Sources/Rendering/Core/AnnotatedCubeActor';
import vtkCornerAnnotation from 'vtk.js/Sources/Interaction/UI/CornerAnnotation';
import vtkInteractorStyleManipulator from 'vtk.js/Sources/Interaction/Style/InteractorStyleManipulator';
import vtkMatrixBuilder from 'vtk.js/Sources/Common/Core/MatrixBuilder';
import vtkOpenGLRenderWindow from 'vtk.js/Sources/Rendering/OpenGL/RenderWindow';
import vtkOrientationMarkerWidget from 'vtk.js/Sources/Interaction/Widgets/OrientationMarkerWidget';
import vtkRenderer from 'vtk.js/Sources/Rendering/Core/Renderer';
import vtkRenderWindow from 'vtk.js/Sources/Rendering/Core/RenderWindow';
import vtkRenderWindowInteractor from 'vtk.js/Sources/Rendering/Core/RenderWindowInteractor';

import InteractionPresets from 'vtk.js/Sources/Interaction/Style/InteractorStyleManipulator/Presets';
import AnnotatedCubePresets from 'vtk.js/Sources/Rendering/Core/AnnotatedCubeActor/Presets';

// ----------------------------------------------------------------------------
// vtkViewProxy methods
// ----------------------------------------------------------------------------

function vtkViewProxy(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkViewProxy');

  // Private --------------------------------------------------------------------

  function updateAnnotationColor() {
    const [r, g, b] = model.renderer.getBackground();
    model.cornerAnnotation.getAnnotationContainer().style.color =
      r + g + b > 1.5 ? 'black' : 'white';
  }

  // Setup --------------------------------------------------------------------
  model.renderWindow = vtkRenderWindow.newInstance();
  model.renderer = vtkRenderer.newInstance({ background: [0, 0, 0] });
  model.renderWindow.addRenderer(model.renderer);

  model.openglRenderWindow = vtkOpenGLRenderWindow.newInstance();
  model.renderWindow.addView(model.openglRenderWindow);

  model.interactor = vtkRenderWindowInteractor.newInstance();
  model.interactor.setView(model.openglRenderWindow);

  model.interactorStyle3D = vtkInteractorStyleManipulator.newInstance();
  model.interactorStyle2D = vtkInteractorStyleManipulator.newInstance();

  // Apply default interaction styles
  InteractionPresets.applyPreset('3D', model.interactorStyle3D);
  InteractionPresets.applyPreset('2D', model.interactorStyle2D);

  model.cornerAnnotation = vtkCornerAnnotation.newInstance();

  // Setup interaction
  model.interactor.setInteractorStyle(
    model.useParallelRendering
      ? model.interactorStyle2D
      : model.interactorStyle3D
  );
  model.camera = model.renderer.getActiveCamera();
  model.camera.setParallelProjection(!!model.useParallelRendering);

  // Orientation a cube setup -------------------------------------------------

  model.orientationAxes = vtkAnnotatedCubeActor.newInstance();
  AnnotatedCubePresets.applyPreset('default', model.orientationAxes);
  model.orientationWidget = vtkOrientationMarkerWidget.newInstance({
    actor: model.orientationAxes,
    interactor: model.renderWindow.getInteractor(),
  });
  model.orientationWidget.setEnabled(true);
  model.orientationWidget.setViewportCorner(
    vtkOrientationMarkerWidget.Corners.BOTTOM_LEFT
  );
  model.orientationWidget.setViewportSize(0.1);

  // API ----------------------------------------------------------------------

  publicAPI.setPresetToInteractor3D = (nameOrDefinitions) => {
    if (Array.isArray(nameOrDefinitions)) {
      return InteractionPresets.applyDefinitions(
        nameOrDefinitions,
        model.interactorStyle3D
      );
    }
    return InteractionPresets.applyPreset(
      nameOrDefinitions,
      model.interactorStyle3D
    );
  };

  // --------------------------------------------------------------------------

  publicAPI.setPresetToInteractor2D = (nameOrDefinitions) => {
    if (Array.isArray(nameOrDefinitions)) {
      return InteractionPresets.applyDefinitions(
        nameOrDefinitions,
        model.interactorStyle2D
      );
    }
    return InteractionPresets.applyPreset(
      nameOrDefinitions,
      model.interactorStyle2D
    );
  };

  // --------------------------------------------------------------------------

  publicAPI.setPresetToOrientationAxes = (nameOrDefinitions) => {
    let changeDetected = false;
    if (typeof nameOrDefinitions === 'string') {
      if (model.presetToOrientationAxes !== nameOrDefinitions) {
        model.presetToOrientationAxes = nameOrDefinitions;
        changeDetected = AnnotatedCubePresets.applyPreset(
          nameOrDefinitions,
          model.orientationAxes
        );
        publicAPI.modified();
      }
      return changeDetected;
    }
    model.presetToOrientationAxes = 'Custom';
    changeDetected = AnnotatedCubePresets.applyDefinitions(
      nameOrDefinitions,
      model.orientationAxes
    );
    publicAPI.modified();
    return changeDetected;
  };

  // --------------------------------------------------------------------------

  publicAPI.setContainer = (container) => {
    if (model.container) {
      model.interactor.unbindEvents(model.container);
      model.openglRenderWindow.setContainer(null);
      model.cornerAnnotation.setContainer(null);
    }

    model.container = container;

    if (container) {
      model.openglRenderWindow.setContainer(container);
      model.cornerAnnotation.setContainer(container);
      model.interactor.initialize();
      model.interactor.bindEvents(container);
    }
  };

  // --------------------------------------------------------------------------

  publicAPI.resize = () => {
    if (model.container) {
      const dims = model.container.getBoundingClientRect();
      model.openglRenderWindow.setSize(
        Math.max(10, Math.floor(dims.width)),
        Math.max(10, Math.floor(dims.height))
      );
      publicAPI.renderLater();
    }
  };

  // --------------------------------------------------------------------------

  publicAPI.renderLater = () => {
    if (model.representations.length > 0 && model.resetCameraOnFirstRender) {
      model.resetCameraOnFirstRender = false;
      // console.log('==> resetCamera before renderLater', model.proxyId);
      publicAPI.resetCamera();
    }
    model.orientationWidget.updateMarkerOrientation();
    setTimeout(model.renderWindow.render, 0);
  };

  // --------------------------------------------------------------------------

  publicAPI.addRepresentation = (representation) => {
    if (!representation) {
      return;
    }
    if (model.representations.indexOf(representation) === -1) {
      model.representations.push(representation);
      representation.getActors().forEach(model.renderer.addActor);
      representation.getVolumes().forEach(model.renderer.addVolume);
    }
  };

  // --------------------------------------------------------------------------

  publicAPI.removeRepresentation = (representation) => {
    if (!representation) {
      return;
    }
    if (model.representations.indexOf(representation) !== -1) {
      model.representations = model.representations.filter(
        (r) => r !== representation
      );
      representation.getActors().forEach(model.renderer.removeActor);
      representation.getVolumes().forEach(model.renderer.removeVolume);
    }
  };

  // --------------------------------------------------------------------------

  publicAPI.resetCamera = () => {
    model.renderer.resetCamera();
    model.renderer.resetCameraClippingRange();
    model.interactorStyle2D.setCenterOfRotation(model.camera.getFocalPoint());
    model.interactorStyle3D.setCenterOfRotation(model.camera.getFocalPoint());
    publicAPI.renderLater();
  };

  // --------------------------------------------------------------------------

  publicAPI.captureImage = () => model.renderWindow.captureImages()[0];

  // --------------------------------------------------------------------------

  publicAPI.openCaptureImage = (target = '_blank') => {
    const image = new Image();
    image.src = publicAPI.captureImage();
    const w = window.open('', target);
    w.document.write(image.outerHTML);
    w.document.title = 'vtk.js Image Capture';
    window.focus();
  };

  // --------------------------------------------------------------------------

  publicAPI.setCornerAnnotation = (corner, templateString) => {
    model.cornerAnnotation.updateTemplates({
      [corner]: (meta) =>
        vtkCornerAnnotation.applyTemplate(templateString, meta),
    });
  };

  // --------------------------------------------------------------------------

  publicAPI.setCornerAnnotations = (annotations, useTemplateString = false) => {
    if (useTemplateString) {
      Object.keys(annotations).forEach((key) => {
        publicAPI.setCornerAnnotation(key, annotations[key]);
      });
    } else {
      model.cornerAnnotation.updateTemplates(annotations);
    }
  };

  // --------------------------------------------------------------------------

  publicAPI.updateCornerAnnotation = (meta) =>
    model.cornerAnnotation.updateMetadata(meta);

  // --------------------------------------------------------------------------

  publicAPI.setAnnotationOpacity = (opacity) => {
    if (model.annotationOpacity !== Number(opacity)) {
      model.annotationOpacity = Number(opacity);
      model.cornerAnnotation.getAnnotationContainer().style.opacity = opacity;
      publicAPI.modified();
    }
  };

  // --------------------------------------------------------------------------

  publicAPI.setBackground = macro.chain(
    model.renderer.setBackground,
    updateAnnotationColor
  );

  // --------------------------------------------------------------------------

  publicAPI.getBackground = model.renderer.getBackground;

  // --------------------------------------------------------------------------

  publicAPI.setAnimation = (enable, requester = publicAPI) => {
    if (enable) {
      model.renderWindow.getInteractor().requestAnimation(requester);
    } else {
      model.renderWindow.getInteractor().cancelAnimation(requester);
    }
  };

  // --------------------------------------------------------------------------

  publicAPI.updateOrientation = (axisIndex, orientation, viewUp) => {
    if (axisIndex === undefined) {
      return;
    }
    model.axis = axisIndex;
    model.orientation = orientation;
    model.viewUp = viewUp;
    const position = model.camera.getFocalPoint();
    position[model.axis] += model.orientation;
    model.camera.setPosition(...position);
    model.camera.setViewUp(...viewUp);
  };

  // --------------------------------------------------------------------------

  publicAPI.resetOrientation = () => {
    publicAPI.updateOrientation(model.axis, model.orientation, model.viewUp);
  };

  // --------------------------------------------------------------------------

  publicAPI.rotate = (angle) => {
    const { viewUp, focalPoint, position } = model.camera.get(
      'viewUp',
      'focalPoint',
      'position'
    );
    const axis = [
      focalPoint[0] - position[0],
      focalPoint[1] - position[1],
      focalPoint[2] - position[2],
    ];

    vtkMatrixBuilder
      .buildFromDegree()
      .rotate(Number.isNaN(angle) ? 90 : angle, axis)
      .apply(viewUp);

    model.camera.setViewUp(...viewUp);
    model.camera.modified();
    model.orientationWidget.updateMarkerOrientation();
    model.renderWindow.render();
  };

  // --------------------------------------------------------------------------
  // Initialization from state or input
  // --------------------------------------------------------------------------

  publicAPI.updateOrientation(model.axis, model.orientation, model.viewUp);
  updateAnnotationColor();
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  representations: [],
  sectionName: 'view',
  annotationOpacity: 1,
  resetCameraOnFirstRender: true,
  presetToOrientationAxes: 'default',
};

// ----------------------------------------------------------------------------

function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  macro.obj(publicAPI, model);
  macro.get(publicAPI, model, [
    'representations',
    'renderer',
    'renderWindow',
    'openglRenderWindow',
    'interactor',
    'interactorStyle2D',
    'interactorStyle3D',
    'container',
    'useParallelRendering',
    'camera',
    'cornerAnnotation',
    'annotationOpacity',
    'presetToOrientationAxes',
  ]);

  // Object specific methods
  vtkViewProxy(publicAPI, model);

  // Proxy handling
  macro.proxy(publicAPI, model);
  macro.proxyPropertyMapping(publicAPI, model, {
    orientationAxesVisibility: {
      modelKey: 'orientationWidget',
      property: 'enabled',
    },
    orientationAxesCorner: {
      modelKey: 'orientationWidget',
      property: 'viewportCorner',
    },
    orientationAxesSize: {
      modelKey: 'orientationWidget',
      property: 'viewportSize',
    },
    cameraViewUp: { modelKey: 'camera', property: 'viewUp', modified: false },
    cameraPosition: {
      modelKey: 'camera',
      property: 'position',
      modified: false,
    },
    cameraFocalPoint: {
      modelKey: 'camera',
      property: 'focalPoint',
      modified: false,
    },
  });

  // Allow dynamic registration of links
  if (model.links && model.proxyManager) {
    for (let i = 0; i < model.links.length; i++) {
      const { link, property, persistent, updateOnBind } = model.links[i];
      const sLink = model.proxyManager.getPropertyLink(link, persistent);
      publicAPI.registerPropertyLinkForGC(sLink);
      sLink.bind(publicAPI, property, updateOnBind);
    }
  }
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend, 'vtkViewProxy');

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<|endoftext|>


<commit_before>WebVRApplication = ( function () {
    function WebVRApplication(scene, config) {
        this.scene = scene;

        config = config || {};
        var rendererOptions     = config.rendererOptions || {antialias: true, alpha: true};
        var useShadowMap        = config.useShadowMap;
        var onResetVRSensor     = config.onResetVRSensor;
        var useWebVRBoilerplate = config.useWebVRBoilerplate;
        var useDistortionMesh   = config.useDistortionMesh;

        var world = config.world;
        if (!world) {
            var worldConfig = config.worldConfig || {};
            worldConfig.gravity                    = worldConfig.gravity || 9.8;
            worldConfig.contactEquationStiffness   = worldConfig.contactEquationStiffness || 1e6;
            worldConfig.frictionEquationStiffness  = worldConfig.frictionEquationStiffness || 1e6;
            worldConfig.contactEquationRelaxation  = worldConfig.contactEquationRelaxation || 3;
            worldConfig.frictionEquationRelaxation = worldConfig.frictionEquationRelaxation || 3;
            worldConfig.iterations                 = worldConfig.iterations || 8;

            world = new CANNON.World();
            world.gravity.set( 0, -worldConfig.gravity, 0 );
            //world.broadphase = new CANNON.SAPBroadphase( world );
            world.defaultContactMaterial.contactEquationStiffness   = worldConfig.contactEquationStiffness;
            world.defaultContactMaterial.frictionEquationStiffness  = worldConfig.frictionEquationStiffness;
            world.defaultContactMaterial.contactEquationRelaxation  = worldConfig.contactEquationRelaxation;
            world.defaultContactMaterial.frictionEquationRelaxation = worldConfig.frictionEquationRelaxation;
            world.solver.iterations = worldConfig.iterations;
        }
        this.world = world;

        var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        this.camera = camera;

        var renderer = new THREE.WebGLRenderer(rendererOptions);
        this.renderer = renderer;
        this.renderer.setPixelRatio(window.devicePixelRatio);
        if (useShadowMap) {
            this.renderer.shadowMap.enabled = true;
            this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        }
        var domElement = this.renderer.domElement;
        document.body.appendChild(domElement);
        domElement.id = 'renderer';

        var vrEffect = new THREE.VREffect(this.renderer, undefined, useDistortionMesh);
        this.vrEffect = vrEffect;
        this.vrEffect.setSize(window.innerWidth, window.innerHeight);

        this.vrControls = new THREE.VRControls(this.camera);
        this.vrControls.enabled = true;

        if (useWebVRBoilerplate) {

            this.vrManager = new WebVRManager(this.renderer, this.vrEffect, {
                hideButton: false
            });

            this.enterVR = function () {
            };

        } else {

            var vrMode = 0;

            window.addEventListener("resize", function () {
                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();
                vrEffect.setSize(window.innerWidth, window.innerHeight);
            });

            this.enterVR = function () {
                if (vrMode === 0) {
                    this.vrEffect.setFullScreen(true);
                }
            }.bind(this);

            this.vrManager = ( function () {
                var onFullscreenChange = function () {
                    if (vrMode === 0) {
                        vrMode = 1;
                        vrEffect.setSize(window.innerWidth, window.innerHeight);
                    } else {
                        vrMode = 0;
                    }
                };
                document.addEventListener('webkitfullscreenchange', onFullscreenChange);
                document.addEventListener('mozfullscreenchange', onFullscreenChange);
                // window.addEventListener('keydown', function (evt) {
                //     if (evt.keyCode === 70) { // F
                //         this.enterVR();
                //     }
                // });
                return {
                    isVRMode: function () {
                        return vrMode === 1;
                    },
                    render: function (scene, camera, t) {
                        if (vrMode === 1) vrEffect.render(scene, camera);
                        else renderer.render(scene, camera);
                    }
                };
            }.bind(this) )();

            this.enterFullscreen = function () {
                // Primrose function:
                function requestFullScreen ( elem, vrDisplay ) {
                    var fullScreenParam;
                    // if ( window.HMDVRDevice && vrDisplay && vrDisplay instanceof HMDVRDevice) {
                    //     fullScreenParam = {vrDisplay: vrDisplay};
                    // }
                    if ( elem.webkitRequestFullscreen && fullScreenParam ) {
                        elem.webkitRequestFullscreen( fullScreenParam );
                    }
                    else if ( elem.webkitRequestFullscreen && !fullScreenParam ) {
                        elem.webkitRequestFullscreen( window.Element.ALLOW_KEYBOARD_INPUT );
                    }
                    else if ( elem.mozRequestFullScreen && fullScreenParam ) {
                        elem.mozRequestFullScreen( fullScreenParam );
                    }
                    else if ( elem.mozRequestFullScreen && !fullScreenParam ) {
                        elem.mozRequestFullScreen( );
                    }
                    else if ( elem.requestFullscreen ) {
                        elem.requestFullscreen();
                    }
                    else if ( elem.msRequestFullscreen ) {
                        elem.msRequestFullscreen();
                    }
                }
                requestFullScreen(domElement);
            };

        }

        this.toggleVRControls = function () {
            if (this.vrControls.enabled) {
                this.vrControls.enabled = false;
                this.camera.position.set(0, 0, 0);
                this.camera.quaternion.set(0, 0, 0, 1);
            } else {
                this.vrControls.enabled = true;
            }
        }.bind(this);

        var lastPosition = new THREE.Vector3();
        this.resetVRSensor = function () {
            lastPosition.copy(this.camera.position);
            var lastRotation = this.camera.rotation.y;
            this.vrControls.resetSensor();
            this.vrControls.update();
            if (onResetVRSensor) {
                onResetVRSensor(lastRotation, lastPosition);
            }
        }.bind(this);

        var wireframeMaterial = new THREE.MeshBasicMaterial({color: 0xeeddaa, wireframe: true});
        this.toggleWireframe = function () {
            if (this.scene.overrideMaterial) {
                this.scene.overrideMaterial = null;
            } else {
                this.scene.overrideMaterial = wireframeMaterial;
            }
        }.bind(this);

        renderer.domElement.requestPointerLock = renderer.domElement.requestPointerLock || renderer.domElement.mozRequestPointerLock || renderer.domElement.webkitRequestPointerLock;
        function requestPointerLock() {
            if (renderer.domElement.requestPointerLock) {
                renderer.domElement.requestPointerLock();
            }
        }
        function releasePointerLock() {
            document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock;
            if (document.exitPointerLock) {
                document.exitPointerLock();
            }
        }
        var fullscreenchange = this.renderer.domElement.mozRequestFullScreen ? 'mozfullscreenchange' : 'webkitfullscreenchange';
        document.addEventListener(fullscreenchange, function ( event ) {
            if (this.vrManager.isVRMode()) {
                this.vrControls.enabled = true;
            }
            var fullscreen = !(document.webkitFullscreenElement === null || document.mozFullScreenElement === null);
            if (!fullscreen) {
                releasePointerLock();
            } else {
                requestPointerLock();
            }
        }.bind(this));

        this.start = function(animate) {
            function waitForResources(t) {
                if (THREE.py.isLoaded()) {
                    THREE.py.CANNONize(scene, world);
                    for (var i = 0; i < 240*2; i++) {
                        world.step(1/240);
                    }
                    requestAnimationFrame(animate);
                } else {
                    requestAnimationFrame(waitForResources);
                }
            }
            waitForResources(0);
        };

    }

    return WebVRApplication;
} )();
<commit_msg>log vreffect, vrcontrols construction errors<commit_after>WebVRApplication = ( function () {
    function WebVRApplication(scene, config) {
        this.scene = scene;

        config = config || {};
        var rendererOptions     = config.rendererOptions || {antialias: true, alpha: true};
        var useShadowMap        = config.useShadowMap;
        var onResetVRSensor     = config.onResetVRSensor;
        var useWebVRBoilerplate = config.useWebVRBoilerplate;

        var world = config.world;
        if (!world) {
            var worldConfig = config.worldConfig || {};
            worldConfig.gravity                    = worldConfig.gravity || 9.8;
            worldConfig.contactEquationStiffness   = worldConfig.contactEquationStiffness || 1e6;
            worldConfig.frictionEquationStiffness  = worldConfig.frictionEquationStiffness || 1e6;
            worldConfig.contactEquationRelaxation  = worldConfig.contactEquationRelaxation || 3;
            worldConfig.frictionEquationRelaxation = worldConfig.frictionEquationRelaxation || 3;
            worldConfig.iterations                 = worldConfig.iterations || 8;

            world = new CANNON.World();
            world.gravity.set( 0, -worldConfig.gravity, 0 );
            //world.broadphase = new CANNON.SAPBroadphase( world );
            world.defaultContactMaterial.contactEquationStiffness   = worldConfig.contactEquationStiffness;
            world.defaultContactMaterial.frictionEquationStiffness  = worldConfig.frictionEquationStiffness;
            world.defaultContactMaterial.contactEquationRelaxation  = worldConfig.contactEquationRelaxation;
            world.defaultContactMaterial.frictionEquationRelaxation = worldConfig.frictionEquationRelaxation;
            world.solver.iterations = worldConfig.iterations;
        }
        this.world = world;

        var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        this.camera = camera;

        var renderer = new THREE.WebGLRenderer(rendererOptions);
        this.renderer = renderer;
        this.renderer.setPixelRatio(window.devicePixelRatio);
        if (useShadowMap) {
            this.renderer.shadowMap.enabled = true;
            this.renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        }
        var domElement = this.renderer.domElement;
        document.body.appendChild(domElement);
        domElement.id = 'renderer';

        var vrEffect = new THREE.VREffect(this.renderer, pyserver.log);
        this.vrEffect = vrEffect;
        this.vrEffect.setSize(window.innerWidth, window.innerHeight);

        this.vrControls = new THREE.VRControls(this.camera, pyserver.log);
        this.vrControls.enabled = true;

        if (useWebVRBoilerplate) {

            this.vrManager = new WebVRManager(this.renderer, this.vrEffect, {
                hideButton: false
            });

            this.enterVR = function () {};

        } else {

            // bare bones webvr-manager, suitable for desktop VR devices

            var vrMode = 0;

            window.addEventListener("resize", function () {
                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();
                vrEffect.setSize(window.innerWidth, window.innerHeight);
            });

            this.enterVR = function () {
                if (vrMode === 0) {
                    this.vrEffect.setFullScreen(true);
                }
            }.bind(this);

            this.vrManager = ( function () {
                var onFullscreenChange = function () {
                    if (vrMode === 0) {
                        vrMode = 1;
                        vrEffect.setSize(window.innerWidth, window.innerHeight);
                    } else {
                        vrMode = 0;
                    }
                };
                document.addEventListener('webkitfullscreenchange', onFullscreenChange);
                document.addEventListener('mozfullscreenchange', onFullscreenChange);
                return {
                    isVRMode: function () {
                        return vrMode === 1;
                    },
                    render: function (scene, camera, t) {
                        if (vrMode === 1) vrEffect.render(scene, camera);
                        else renderer.render(scene, camera);
                    }
                };
            }.bind(this) )();

            this.enterFullscreen = function () {
                // Primrose function:
                function requestFullScreen ( elem, vrDisplay ) {
                    var fullScreenParam;
                    // if ( window.HMDVRDevice && vrDisplay && vrDisplay instanceof HMDVRDevice) {
                    //     fullScreenParam = {vrDisplay: vrDisplay};
                    // }
                    if ( elem.webkitRequestFullscreen && fullScreenParam ) {
                        elem.webkitRequestFullscreen( fullScreenParam );
                    }
                    else if ( elem.webkitRequestFullscreen && !fullScreenParam ) {
                        elem.webkitRequestFullscreen( window.Element.ALLOW_KEYBOARD_INPUT );
                    }
                    else if ( elem.mozRequestFullScreen && fullScreenParam ) {
                        elem.mozRequestFullScreen( fullScreenParam );
                    }
                    else if ( elem.mozRequestFullScreen && !fullScreenParam ) {
                        elem.mozRequestFullScreen( );
                    }
                    else if ( elem.requestFullscreen ) {
                        elem.requestFullscreen();
                    }
                    else if ( elem.msRequestFullscreen ) {
                        elem.msRequestFullscreen();
                    }
                }
                requestFullScreen(domElement);
            };

        }

        this.toggleVRControls = function () {
            if (this.vrControls.enabled) {
                this.vrControls.enabled = false;
                this.camera.position.set(0, 0, 0);
                this.camera.quaternion.set(0, 0, 0, 1);
            } else {
                this.vrControls.enabled = true;
            }
        }.bind(this);

        var lastPosition = new THREE.Vector3();
        this.resetVRSensor = function () {
            lastPosition.copy(this.camera.position);
            var lastRotation = this.camera.rotation.y;
            this.vrControls.resetSensor();
            this.vrControls.update();
            if (onResetVRSensor) {
                onResetVRSensor(lastRotation, lastPosition);
            }
        }.bind(this);

        var wireframeMaterial = new THREE.MeshBasicMaterial({color: 0xeeddaa, wireframe: true});
        this.toggleWireframe = function () {
            if (this.scene.overrideMaterial) {
                this.scene.overrideMaterial = null;
            } else {
                this.scene.overrideMaterial = wireframeMaterial;
            }
        }.bind(this);

        renderer.domElement.requestPointerLock = renderer.domElement.requestPointerLock || renderer.domElement.mozRequestPointerLock || renderer.domElement.webkitRequestPointerLock;
        function requestPointerLock() {
            if (renderer.domElement.requestPointerLock) {
                renderer.domElement.requestPointerLock();
            }
        }
        function releasePointerLock() {
            document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock;
            if (document.exitPointerLock) {
                document.exitPointerLock();
            }
        }
        var fullscreenchange = this.renderer.domElement.mozRequestFullScreen ? 'mozfullscreenchange' : 'webkitfullscreenchange';
        document.addEventListener(fullscreenchange, function ( event ) {
            if (this.vrManager.isVRMode()) {
                this.vrControls.enabled = true;
            }
            var fullscreen = !(document.webkitFullscreenElement === null || document.mozFullScreenElement === null);
            if (!fullscreen) {
                releasePointerLock();
            } else {
                requestPointerLock();
            }
        }.bind(this));

        this.start = function(animate) {
            function waitForResources(t) {
                if (THREE.py.isLoaded()) {
                    THREE.py.CANNONize(scene, world);
                    for (var i = 0; i < 240*2; i++) {
                        world.step(1/240);
                    }
                    requestAnimationFrame(animate);
                } else {
                    requestAnimationFrame(waitForResources);
                }
            }
            waitForResources(0);
        };

    }

    return WebVRApplication;
} )();
<|endoftext|>


<commit_before>// Expanding Textareas
// https://github.com/bgrins/ExpandingTextareas

(function(factory) {
    // Add jQuery via AMD registration or browser globals
    if (typeof define === 'function' && define.amd) {
        define([ 'jquery' ], factory);
    }
    else {
        factory(jQuery);
    }
}(function ($) {
    $.expandingTextarea = $.extend({
        autoInitialize: true,
        initialSelector: "textarea.expanding",
        opts: {
            resize: function() { }
        }
    }, $.expandingTextarea || {});

    var cloneCSSProperties = [
        'lineHeight', 'textDecoration', 'letterSpacing',
        'fontSize', 'fontFamily', 'fontStyle',
        'fontWeight', 'textTransform', 'textAlign',
        'direction', 'wordSpacing', 'fontSizeAdjust',
        'wordWrap', 'word-break',
        'borderLeftWidth', 'borderRightWidth',
        'borderTopWidth','borderBottomWidth',
        'paddingLeft', 'paddingRight',
        'paddingTop','paddingBottom',
        'marginLeft', 'marginRight',
        'marginTop','marginBottom',
        'boxSizing', 'webkitBoxSizing', 'mozBoxSizing', 'msBoxSizing'
    ];

    var textareaCSS = {
        position: "absolute",
        height: "100%",
        resize: "none"
    };

    var preCSS = {
        visibility: "hidden",
        border: "0 solid"
    };

    var containerCSS = {
        position: "relative"
    };

    function resize() {
        $(this).closest('.expandingText').find("div").text(this.value.replace(/\r\n/g, "\n") + ' ');
        $(this).trigger("resize.expanding");
    }

    $.fn.expandingTextarea = function(o) {

        var opts = $.extend({ }, $.expandingTextarea.opts, o);

        if (o === "resize") {
            return this.trigger("input.expanding");
        }

        if (o === "destroy") {
            this.filter(".expanding-init").each(function() {
                var textarea = $(this).removeClass('expanding-init');
                var container = textarea.closest('.expandingText');

                container.before(textarea).remove();
                textarea
                    .attr('style', textarea.data('expanding-styles') || '')
                    .removeData('expanding-styles');
            });

            return this;
        }

        this.filter("textarea").not(".expanding-init").addClass("expanding-init").each(function() {
            var textarea = $(this);

            textarea.wrap("

");
            textarea.after("

");

            var container = textarea.parent().css(containerCSS);
            var pre = container.find("pre").css(preCSS);

            pre.css(textarea.attr("wrap") === "off" ? {overflowX: "scroll"} : {whiteSpace: "pre-wrap"});

            // Store the original styles in case of destroying.
            textarea.data('expanding-styles', textarea.attr('style'));
            textarea.css(textareaCSS);

            $.each(cloneCSSProperties, function(i, p) {
                var val = textarea.css(p);

                // Only set if different to prevent overriding percentage css values.
                if (pre.css(p) !== val) {
                    pre.css(p, val);
                }
            });
            container.css({"min-height": textarea.outerHeight(true)});

            textarea.bind("input.expanding propertychange.expanding keyup.expanding change.expanding", resize);
            resize.apply(this);

            if (opts.resize) {
                textarea.bind("resize.expanding", opts.resize);
            }
        });

        return this;
    };

    $(function () {
        if ($.expandingTextarea.autoInitialize) {
            $($.expandingTextarea.initialSelector).expandingTextarea();
        }
    });

}));
<commit_msg>whitespace<commit_after>// Expanding Textareas
// https://github.com/bgrins/ExpandingTextareas

(function(factory) {
    // Add jQuery via AMD registration or browser globals
    if (typeof define === 'function' && define.amd) {
        define([ 'jquery' ], factory);
    }
    else {
        factory(jQuery);
    }
}(function ($) {
    $.expandingTextarea = $.extend({
        autoInitialize: true,
        initialSelector: "textarea.expanding",
        opts: {
            resize: function() { }
        }
    }, $.expandingTextarea || {});

    var cloneCSSProperties = [
        'lineHeight', 'textDecoration', 'letterSpacing',
        'fontSize', 'fontFamily', 'fontStyle',
        'fontWeight', 'textTransform', 'textAlign',
        'direction', 'wordSpacing', 'fontSizeAdjust',
        'wordWrap', 'word-break',
        'borderLeftWidth', 'borderRightWidth',
        'borderTopWidth','borderBottomWidth',
        'paddingLeft', 'paddingRight',
        'paddingTop','paddingBottom',
        'marginLeft', 'marginRight',
        'marginTop','marginBottom',
        'boxSizing', 'webkitBoxSizing', 'mozBoxSizing', 'msBoxSizing'
    ];

    var textareaCSS = {
        position: "absolute",
        height: "100%",
        resize: "none"
    };

    var preCSS = {
        visibility: "hidden",
        border: "0 solid"
    };

    var containerCSS = {
        position: "relative"
    };

    function resize() {
        $(this).closest('.expandingText').find("div").text(this.value.replace(/\r\n/g, "\n") + ' ');
        $(this).trigger("resize.expanding");
    }

    $.fn.expandingTextarea = function(o) {

        var opts = $.extend({ }, $.expandingTextarea.opts, o);

        if (o === "resize") {
            return this.trigger("input.expanding");
        }

        if (o === "destroy") {
            this.filter(".expanding-init").each(function() {
                var textarea = $(this).removeClass('expanding-init');
                var container = textarea.closest('.expandingText');

                container.before(textarea).remove();
                textarea
                    .attr('style', textarea.data('expanding-styles') || '')
                    .removeData('expanding-styles');
            });

            return this;
        }

        this.filter("textarea").not(".expanding-init").addClass("expanding-init").each(function() {
            var textarea = $(this);

            textarea.wrap("

");
            textarea.after("

");

            var container = textarea.parent().css(containerCSS);
            var pre = container.find("pre").css(preCSS);

            pre.css(textarea.attr("wrap") === "off" ? {overflowX: "scroll"} : {whiteSpace: "pre-wrap"});

            // Store the original styles in case of destroying.
            textarea.data('expanding-styles', textarea.attr('style'));
            textarea.css(textareaCSS);

            $.each(cloneCSSProperties, function(i, p) {
                var val = textarea.css(p);

                // Only set if different to prevent overriding percentage css values.
                if (pre.css(p) !== val) {
                    pre.css(p, val);
                }
            });
            container.css({"min-height": textarea.outerHeight(true)});

            textarea.bind("input.expanding propertychange.expanding keyup.expanding change.expanding", resize);
            resize.apply(this);

            if (opts.resize) {
                textarea.bind("resize.expanding", opts.resize);
            }
        });

        return this;
    };

    $(function () {
        if ($.expandingTextarea.autoInitialize) {
            $($.expandingTextarea.initialSelector).expandingTextarea();
        }
    });

}));
<|endoftext|>


<commit_before>'use strict';
define(['app/controls', 'app/config'], function(controls, config) {

    // ##############################################
    // # Add event listeners ########################
    // ##############################################

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

    // ##############################################
    // # Private functions ##########################
    // ##############################################

    function onKeyDown(event) {
        switch(event.keyCode) {
            case 87: // W
                controls.up = true;
                break;

            case 65: // A
                controls.left = true;
                break;

            case 83: // S
                controls.down = true;
                break;

            case 68: // D
                controls.right = true;
                break;

            case 81: // Q
                controls.cameraUp = true;
                break;

            case 69: // E
                controls.cameraDown = true;
                break;
        }
    }

    // ##############################################

    function onKeyUp(event) {
        switch(event.keyCode) {
            case 87: // W
                controls.up = false;
                break;

            case 65: // A
                controls.left = false;
                break;

            case 83: // S
                controls.down = false;
                break;

            case 68: // D
                controls.right = false;
                break;

            case 81: // Q
                controls.cameraUp = false;
                break;

            case 69: // E
                controls.cameraDown = false;
                break;
        }
    }

    // ##############################################

    function cameraMovement(camera) {
        if(controls.up && !controls.down) {
            camera.position.y += config.camera.movementSpeed;
        }

        if(controls.down && !controls.up) {
            camera.position.y -= config.camera.movementSpeed;
        }

        if(controls.left && !controls.right) {
            camera.position.x -= config.camera.movementSpeed;
        }

        if(controls.right && !controls.left) {
            camera.position.x += config.camera.movementSpeed;
        }

        if(controls.cameraUp && !controls.cameraDown) {
            camera.position.z += config.camera.movementSpeed;
        }

        if(controls.cameraDown && !controls.cameraUp) {
            camera.position.z -= config.camera.movementSpeed;
        }
    }

    // ##############################################
    // # Public functions ###########################
    // ##############################################

    var single = true;

    function checkInput(camera) {
        if(camera != undefined) cameraMovement(camera);
    }

    // ##############################################

    return {
        checkInput: checkInput
    };
});<commit_msg>Made camera movement speed dependent on "zoom" level<commit_after>'use strict';
define(['app/controls', 'app/config'], function(controls, config) {

    // ##############################################
    // # Add event listeners ########################
    // ##############################################

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

    // ##############################################
    // # Private functions ##########################
    // ##############################################

    function onKeyDown(event) {
        switch(event.keyCode) {
            case 87: // W
                controls.up = true;
                break;

            case 65: // A
                controls.left = true;
                break;

            case 83: // S
                controls.down = true;
                break;

            case 68: // D
                controls.right = true;
                break;

            case 81: // Q
                controls.cameraUp = true;
                break;

            case 69: // E
                controls.cameraDown = true;
                break;
        }
    }

    // ##############################################

    function onKeyUp(event) {
        switch(event.keyCode) {
            case 87: // W
                controls.up = false;
                break;

            case 65: // A
                controls.left = false;
                break;

            case 83: // S
                controls.down = false;
                break;

            case 68: // D
                controls.right = false;
                break;

            case 81: // Q
                controls.cameraUp = false;
                break;

            case 69: // E
                controls.cameraDown = false;
                break;
        }
    }

    // ##############################################

    function cameraMovement(camera) {
        if(controls.up && !controls.down) {
            camera.position.y += (camera.position.z / 50) * config.camera.movementSpeed;
        }

        if(controls.down && !controls.up) {
            camera.position.y -= (camera.position.z / 50) * config.camera.movementSpeed;
        }

        if(controls.left && !controls.right) {
            camera.position.x -= (camera.position.z / 50) * config.camera.movementSpeed;
        }

        if(controls.right && !controls.left) {
            camera.position.x += (camera.position.z / 50) * config.camera.movementSpeed;
        }

        if(controls.cameraUp && !controls.cameraDown) {
            camera.position.z += config.camera.movementSpeed;
        }

        if(controls.cameraDown && !controls.cameraUp) {
            camera.position.z -= config.camera.movementSpeed;
        }
    }

    // ##############################################
    // # Public functions ###########################
    // ##############################################

    var single = true;

    function checkInput(camera) {
        if(camera != undefined) cameraMovement(camera);
    }

    // ##############################################

    return {
        checkInput: checkInput
    };
});<|endoftext|>


<commit_before>define(['./alasqlavanza', './alasqlnordnet', './alasqlstockdata', './alasqlstockdividenddata'], function(alasqlavanza, alasqlnordnet, alasqlstockdata, alasqlstockdividenddata) {

    function getTotalDividend(year, isTaxChecked) {
        var resultNordnetTotal = alasqlnordnet.getTotalDividend(year, isTaxChecked);
        var resultAvanzaTotal = alasqlavanza.getTotalDividend(year, isTaxChecked);
        return resultNordnetTotal + resultAvanzaTotal;
    }

    function getVärdepapperTotalDividend(year, sort, addTaxToSum) {

        var resultNordnetDividend = alasqlnordnet.getVardepapperTotalDividend(year, addTaxToSum);
        var resultAvanzaDividend = alasqlavanza.getVardepapperTotalDividend(year, addTaxToSum);

        alasql('CREATE TABLE IF NOT EXISTS VardepapperTotalDividend \
                (name STRING, [value] NUMBER);');

        alasql('INSERT INTO VardepapperTotalDividend SELECT name, [value] \
                FROM ?', [resultNordnetDividend]);

        alasql('INSERT INTO VardepapperTotalDividend SELECT name, [value] \
                FROM ?', [resultAvanzaDividend]);

        var sortExpression = " ORDER BY name";
        if(sort == "size")
            sortExpression = " ORDER BY SUM([value]) DESC";

        var result = alasql('SELECT FIRST(name) AS name, SUM([value]) AS [value] FROM VardepapperTotalDividend GROUP BY name' + sortExpression);
        alasql('TRUNCATE TABLE VardepapperTotalDividend');

        return result;
    }

    function getVärdepapperForYear(year) {

        alasqlavanza.getBuyTransactionSumBelopp(year);
        alasqlavanza.getSellTransactionSumBelopp(year);

        var avanzaData = alasqlavanza.getVärdepapperForYear(year);
        var nordnetData = alasqlnordnet.getVärdepapperForYear(year);

        alasql('CREATE TABLE IF NOT EXISTS DivStackedCumulativeVardepapper \
                (Vardepapper NVARCHAR(100), ISIN NVARCHAR(100));');

        alasql('INSERT INTO DivStackedCumulativeVardepapper SELECT Vardepapper, ISIN \
                FROM ?', [avanzaData]);

        alasql('INSERT INTO DivStackedCumulativeVardepapper SELECT Vardepapper, ISIN \
                FROM ?', [nordnetData]);

        var resultVärdepapper = alasql('SELECT FIRST(Vardepapper) AS Vardepapper, FIRST(ISIN) AS ISIN FROM DivStackedCumulativeVardepapper GROUP BY ISIN ORDER BY Vardepapper');
        alasql('TRUNCATE TABLE DivStackedCumulativeVardepapper');

        return resultVärdepapper;
    }

    function getVärdepapperDividendData(year, resultVärdepapper, isTaxChecked) {

        var monthNumber = 11;
        alasql('CREATE TABLE IF NOT EXISTS DivStackedCumulativeVardepapperValues \
        ([Värdepapper] NVARCHAR(100), Month INT, Belopp DECIMAL);');
        alasql('TRUNCATE TABLE DivStackedCumulativeVardepapperValues');

        for(var i=0; i <= monthNumber; i++)
        {
            var month = i + 1;

            var resultAvanza = alasqlavanza.getVärdepapperDividend(year, month, isTaxChecked);
            var resultNordnet = alasqlnordnet.getVärdepapperDividend(year,month, isTaxChecked);

            resultVärdepapper.forEach(function(entry) {
                if (entry.Vardepapper == null) { return; }
                var värdepapper = entry.Vardepapper;
                var isin = entry.ISIN;

                var avanzaVärdepapperValueForMonth = alasql('SELECT VALUE Belopp FROM ? WHERE [Värdepapper] = "' + värdepapper + '"', [resultAvanza]);
                var nordnetVärdepapperValueForMonth = alasql('SELECT VALUE Belopp FROM ? WHERE [ISIN] = "' + isin + '"', [resultNordnet]);
                if(isNaN(avanzaVärdepapperValueForMonth))
                    avanzaVärdepapperValueForMonth = 0;

                if(isNaN(nordnetVärdepapperValueForMonth))
                    nordnetVärdepapperValueForMonth = 0;

                var total = avanzaVärdepapperValueForMonth + nordnetVärdepapperValueForMonth;

                alasql('INSERT INTO DivStackedCumulativeVardepapperValues VALUES ("' + värdepapper + '", ' + month + ', ' + total + ')');
            });
        }

        var värdepapperDividendDataValues = [];
        resultVärdepapper.forEach(function(entry) {
            if (entry.Vardepapper == null) { return; }
            var värdepapper = entry.Vardepapper;
            var isin = entry.ISIN;

            var värdepapperNamnStockData = alasqlstockdata.getVärdepapperNamn(isin);
            if(värdepapperNamnStockData.length != 0)
                värdepapper = värdepapperNamnStockData[0].namn;

            var monthDividendDataValues = alasql('SELECT COLUMN Belopp FROM DivStackedCumulativeVardepapperValues WHERE [Värdepapper] = "' + entry.Vardepapper + '"');
            värdepapperDividendDataValues.push({
                name: värdepapper,
                data: monthDividendDataValues
            });
        });

        return värdepapperDividendDataValues;
    }

    function getReceivedDividendCurrentYearToDate(currentYear, today) {
        var avanzaReceivedDividendData = alasqlavanza.getReceivedDividendCurrentYearToDate(currentYear, today);
        var nordnetReceivedDividendData = alasqlnordnet.getReceivedDividendCurrentYearToDate(currentYear, today);

        var avanzaResult = receivedDividendDataForeach(avanzaReceivedDividendData);
        var nordnetResult = receivedDividendDataForeach(nordnetReceivedDividendData);

        var result = avanzaResult.concat(nordnetResult);
        return alasql('SELECT FIRST(ISIN) AS ISIN, FIRST([Månad]) AS [Månad], \
                              FIRST([Värdepapper]) AS [Värdepapper], FIRST(Typ) AS Typ, \
                              FIRST(Utdelningaktiedecimal) AS Utdelningaktiedecimal, FIRST(Utdelningsdag) AS Utdelningsdag, \
                              FIRST(Valuta) AS Valuta, \
                              SUM(Belopp::NUMBER) AS Belopp, SUM(Antal::NUMBER) AS Antal \
                              FROM ? \
                              GROUP BY ISIN, [Månad], [Värdepapper], Typ, Utdelningaktiedecimal, Utdelningsdag, Valuta', [result]);
    }

    function receivedDividendDataForeach(receivedDividendData) {
        var resultForReturn = [];

        receivedDividendData.forEach(function(receivedDividendDataObject) {
            if(receivedDividendDataObject == null) return;
            if(receivedDividendDataObject.Antal == null) return;

            var isin = receivedDividendDataObject.ISIN;
            var värdepapper = receivedDividendDataObject.Värdepapper;
            var värdepapperNamnStockData = alasqlstockdata.getVärdepapperNamn(receivedDividendDataObject.isin);
            if(värdepapperNamnStockData.length != 0)
                värdepapper = värdepapperNamnStockData[0].namn;

            var valuta = alasqlstockdata.getVärdepapperHandlas(isin);

            var typ = alasqlstockdividenddata.getDividendTyp(receivedDividendDataObject.Datum, isin);
            if(typ == null)
                typ = "Utdelning";

            var newObject = createStockDividendObject(värdepapper,
                                                        receivedDividendDataObject.Antal,
                                                        isin,
                                                        typ,
                                                        receivedDividendDataObject.Kurs,
                                                        receivedDividendDataObject.Månad,
                                                        receivedDividendDataObject.Datum,
                                                        valuta,
                                                        receivedDividendDataObject.Belopp);
            resultForReturn.push(newObject);
        });

        return resultForReturn;
    }

    function createStockDividendObject(värdepapper, antal, isin, typ, utdelningaktiedecimal, månad, utdelningsdag, valuta, belopp) {
        var newObject = new Object();
        newObject.Värdepapper = värdepapper;
        newObject.Antal = parseInt(antal);
        newObject.ISIN = isin;
        newObject.Typ = typ;
        newObject.Utdelningaktiedecimal = utdelningaktiedecimal;
        newObject.Månad = månad;
        newObject.Utdelningsdag = utdelningsdag;
        newObject.Valuta = valuta;
        newObject.Belopp = belopp;
        return newObject;
    }

    return {
        getVärdepapperTotalDividend: getVärdepapperTotalDividend,
        getVärdepapperForYear: getVärdepapperForYear,
        getVärdepapperDividendData: getVärdepapperDividendData,
        getTotalDividend: getTotalDividend,
        getReceivedDividendCurrentYearToDate: getReceivedDividendCurrentYearToDate
    };
});<commit_msg>Fixed GROUP BY so we group on one descp<commit_after>define(['./alasqlavanza', './alasqlnordnet', './alasqlstockdata', './alasqlstockdividenddata'], function(alasqlavanza, alasqlnordnet, alasqlstockdata, alasqlstockdividenddata) {

    function getTotalDividend(year, isTaxChecked) {
        var resultNordnetTotal = alasqlnordnet.getTotalDividend(year, isTaxChecked);
        var resultAvanzaTotal = alasqlavanza.getTotalDividend(year, isTaxChecked);
        return resultNordnetTotal + resultAvanzaTotal;
    }

    function getVärdepapperTotalDividend(year, sort, addTaxToSum) {

        var resultNordnetDividend = alasqlnordnet.getVardepapperTotalDividend(year, addTaxToSum);
        var resultAvanzaDividend = alasqlavanza.getVardepapperTotalDividend(year, addTaxToSum);

        alasql('CREATE TABLE IF NOT EXISTS VardepapperTotalDividend \
                (name STRING, [value] NUMBER);');

        alasql('INSERT INTO VardepapperTotalDividend SELECT name, [value] \
                FROM ?', [resultNordnetDividend]);

        alasql('INSERT INTO VardepapperTotalDividend SELECT name, [value] \
                FROM ?', [resultAvanzaDividend]);

        var sortExpression = " ORDER BY name";
        if(sort == "size")
            sortExpression = " ORDER BY SUM([value]) DESC";

        var result = alasql('SELECT FIRST(name) AS name, SUM([value]) AS [value] FROM VardepapperTotalDividend GROUP BY name' + sortExpression);
        alasql('TRUNCATE TABLE VardepapperTotalDividend');

        return result;
    }

    function getVärdepapperForYear(year) {

        alasqlavanza.getBuyTransactionSumBelopp(year);
        alasqlavanza.getSellTransactionSumBelopp(year);

        var avanzaData = alasqlavanza.getVärdepapperForYear(year);
        var nordnetData = alasqlnordnet.getVärdepapperForYear(year);

        alasql('CREATE TABLE IF NOT EXISTS DivStackedCumulativeVardepapper \
                (Vardepapper NVARCHAR(100), ISIN NVARCHAR(100));');

        alasql('INSERT INTO DivStackedCumulativeVardepapper SELECT Vardepapper, ISIN \
                FROM ?', [avanzaData]);

        alasql('INSERT INTO DivStackedCumulativeVardepapper SELECT Vardepapper, ISIN \
                FROM ?', [nordnetData]);

        var resultVärdepapper = alasql('SELECT FIRST(Vardepapper) AS Vardepapper, FIRST(ISIN) AS ISIN FROM DivStackedCumulativeVardepapper GROUP BY ISIN ORDER BY Vardepapper');
        alasql('TRUNCATE TABLE DivStackedCumulativeVardepapper');

        return resultVärdepapper;
    }

    function getVärdepapperDividendData(year, resultVärdepapper, isTaxChecked) {

        var monthNumber = 11;
        alasql('CREATE TABLE IF NOT EXISTS DivStackedCumulativeVardepapperValues \
        ([Värdepapper] NVARCHAR(100), Month INT, Belopp DECIMAL);');
        alasql('TRUNCATE TABLE DivStackedCumulativeVardepapperValues');

        for(var i=0; i <= monthNumber; i++)
        {
            var month = i + 1;

            var resultAvanza = alasqlavanza.getVärdepapperDividend(year, month, isTaxChecked);
            var resultNordnet = alasqlnordnet.getVärdepapperDividend(year,month, isTaxChecked);

            resultVärdepapper.forEach(function(entry) {
                if (entry.Vardepapper == null) { return; }
                var värdepapper = entry.Vardepapper;
                var isin = entry.ISIN;

                var avanzaVärdepapperValueForMonth = alasql('SELECT VALUE Belopp FROM ? WHERE [Värdepapper] = "' + värdepapper + '"', [resultAvanza]);
                var nordnetVärdepapperValueForMonth = alasql('SELECT VALUE Belopp FROM ? WHERE [ISIN] = "' + isin + '"', [resultNordnet]);
                if(isNaN(avanzaVärdepapperValueForMonth))
                    avanzaVärdepapperValueForMonth = 0;

                if(isNaN(nordnetVärdepapperValueForMonth))
                    nordnetVärdepapperValueForMonth = 0;

                var total = avanzaVärdepapperValueForMonth + nordnetVärdepapperValueForMonth;

                alasql('INSERT INTO DivStackedCumulativeVardepapperValues VALUES ("' + värdepapper + '", ' + month + ', ' + total + ')');
            });
        }

        var värdepapperDividendDataValues = [];
        resultVärdepapper.forEach(function(entry) {
            if (entry.Vardepapper == null) { return; }
            var värdepapper = entry.Vardepapper;
            var isin = entry.ISIN;

            var värdepapperNamnStockData = alasqlstockdata.getVärdepapperNamn(isin);
            if(värdepapperNamnStockData.length != 0)
                värdepapper = värdepapperNamnStockData[0].namn;

            var monthDividendDataValues = alasql('SELECT COLUMN Belopp FROM DivStackedCumulativeVardepapperValues WHERE [Värdepapper] = "' + entry.Vardepapper + '"');
            värdepapperDividendDataValues.push({
                name: värdepapper,
                data: monthDividendDataValues
            });
        });

        return värdepapperDividendDataValues;
    }

    function getReceivedDividendCurrentYearToDate(currentYear, today) {
        var avanzaReceivedDividendData = alasqlavanza.getReceivedDividendCurrentYearToDate(currentYear, today);
        var nordnetReceivedDividendData = alasqlnordnet.getReceivedDividendCurrentYearToDate(currentYear, today);

        var avanzaResult = receivedDividendDataForeach(avanzaReceivedDividendData);
        var nordnetResult = receivedDividendDataForeach(nordnetReceivedDividendData);

        var result = avanzaResult.concat(nordnetResult);
        return alasql('SELECT FIRST(ISIN) AS ISIN, FIRST([Månad]) AS [Månad], \
                              FIRST([Värdepapper]) AS [Värdepapper], FIRST(Typ) AS Typ, \
                              FIRST(Utdelningaktiedecimal) AS Utdelningaktiedecimal, FIRST(Utdelningsdag) AS Utdelningsdag, \
                              FIRST(Valuta) AS Valuta, \
                              SUM(Belopp::NUMBER) AS Belopp, SUM(Antal::NUMBER) AS Antal \
                              FROM ? \
                              GROUP BY ISIN, [Månad], Typ', [result]);
    }

    function receivedDividendDataForeach(receivedDividendData) {
        var resultForReturn = [];

        receivedDividendData.forEach(function(receivedDividendDataObject) {
            if(receivedDividendDataObject == null) return;
            if(receivedDividendDataObject.Antal == null) return;

            var isin = receivedDividendDataObject.ISIN;
            var värdepapper = receivedDividendDataObject.Värdepapper;
            var värdepapperNamnStockData = alasqlstockdata.getVärdepapperNamn(receivedDividendDataObject.isin);
            if(värdepapperNamnStockData.length != 0)
                värdepapper = värdepapperNamnStockData[0].namn;

            var valuta = alasqlstockdata.getVärdepapperHandlas(isin);

            var typ = alasqlstockdividenddata.getDividendTyp(receivedDividendDataObject.Datum, isin);
            if(typ == null)
                typ = "Utdelning";

            var newObject = createStockDividendObject(värdepapper,
                                                        receivedDividendDataObject.Antal,
                                                        isin,
                                                        typ,
                                                        receivedDividendDataObject.Kurs,
                                                        receivedDividendDataObject.Månad,
                                                        receivedDividendDataObject.Datum,
                                                        valuta,
                                                        receivedDividendDataObject.Belopp);
            resultForReturn.push(newObject);
        });

        return resultForReturn;
    }

    function createStockDividendObject(värdepapper, antal, isin, typ, utdelningaktiedecimal, månad, utdelningsdag, valuta, belopp) {
        var newObject = new Object();
        newObject.Värdepapper = värdepapper;
        newObject.Antal = parseInt(antal);
        newObject.ISIN = isin;
        newObject.Typ = typ;
        newObject.Utdelningaktiedecimal = utdelningaktiedecimal;
        newObject.Månad = månad;
        newObject.Utdelningsdag = utdelningsdag;
        newObject.Valuta = valuta;
        newObject.Belopp = belopp;
        return newObject;
    }

    return {
        getVärdepapperTotalDividend: getVärdepapperTotalDividend,
        getVärdepapperForYear: getVärdepapperForYear,
        getVärdepapperDividendData: getVärdepapperDividendData,
        getTotalDividend: getTotalDividend,
        getReceivedDividendCurrentYearToDate: getReceivedDividendCurrentYearToDate
    };
});<|endoftext|>


<commit_before>'use strict';

sceneLoader[0] = function() {

  // Iniciando a nova cena
  scene[0] = new Game.Scene();
  // Adicionando musica na cena
  scene[0].setMusic("musicaSalaDeAula.mp3");

  // Adicionando uma imagem de fundo
  var fundoSalaDeAula = new Game.Background("salaDeAula.jpg");
  // Para ajuda no desenvolvimento, colocando um evento de clique no fundo para
  // Mostrar as coordenadas
  var mostraCoordenadasAoClicar = true;
  fundoSalaDeAula.click = function(mouse) {
    if (mostraCoordenadasAoClicar) {
      var mousePosition = mouse.data.getLocalPosition(stage);
      console.log(Math.round(mousePosition.x) + "; " + Math.round(mousePosition.y));
    }
  }

  var carteiras = new Game.Item("salaDeAula_carteiras.png");
  carteiras.setPosition(960, 857);
  carteiras.setZorder(10);

  var mesaProfessor = new Game.Item("salaDeAula_mesaProfessor.png");
  mesaProfessor.setPosition(1400, 550);
  mesaProfessor.setZorder(15);

  // Adiciona uma seta para levar a cena externa
  var setaJanela = new Game.Item("seta.png");
  setaJanela.setPosition(1735, 480);
  setaJanela.setScale(0.5);
  setaJanela.addGlowEffect();
  setaJanela.setZorder(1);
  setaJanela.click = function(mouse) {
    changeScene(1); // Muda para a cena exterior
  }

  // Adiciona uma seta para levar ao armario
  var setaArmario = new Game.Item("seta.png");
  setaArmario.setPosition(210, 480);
  setaArmario.setScale(0.5);
  setaArmario.setRotation(180);
  setaArmario.addGlowEffect();
  setaArmario.setZorder(1);
  setaArmario.click = function(mouse) {
    changeScene(2); // Muda para a cena exterior
  }

  { // Elementos do ciclo da banana

    // Adicionando o aluno
    var estudanteBananaNormal = new Game.Item("estudanteNormal.png");
    estudanteBananaNormal.setPosition(960, 655);
    estudanteBananaNormal.setZorder(11);

    // Adiconando a banana
    var banana = new Game.Item("banana.png");
    banana.setPosition(980, 730);
    banana.setScale(0.2);
    banana.setZorder(9);
    banana.addGlowEffect();
    banana.click = function(mouse) {
      // Eventos que acontecem imediatamente apos clicar na banana
      disableInteractiveness();
      banana.removeGlow();
      fundoSalaDeAula.changeBrightness(100, 600);
      carteiras.changeBrightness(100, 600);
      mesaProfessor.changeBrightness(100, 600);
      setaJanela.fadeout(600);
      setaArmario.fadeout(600);

      // Eventos que acontecem apos 0.8 segundos do clique
      setTimeout(function() {
        setaJanela.disable();
        setaArmario.disable();
      }, 800);

      // Eventos que acontecem apos 1.6 segundos do clique
      setTimeout(function() {
        banana.fadeout(600);
        estudanteBananaNormal.fadeout(600);
      }, 1600);

      // Eventos que acontecem apos 2.4 segundos do clique
      setTimeout(function() {
        sistemaDigestivo.enable();
        sistemaDigestivo.fadein(600);
      }, 2400);

      // Eventos que acontecem apos 3.2 segundos do clique
      setTimeout(function() {
        estudanteBananaNormal.disable();
        bananaInfectada.enable();
        bananaInfectada.fadein(600);
      }, 3200);

      // Eventos que acontecem apos 4 segundos do clique
      setTimeout(function() {
        coliDesencistamento.enable();
        coliDesencistamento.fadein(600);
      }, 4000);

      // Eventos que acontecem apos 4.8 segundos do clique
      setTimeout(function() {
        coliEncistamento.enable();
        coliEncistamento.fadein(600);
      }, 4800);

      // Eventos que acontecem apos 5.6 segundos do clique
      setTimeout(function() {
        coliFezes.enable();
        coliFezes.fadein(600);
      }, 5600);

      // Eventos que acontecem apos 6.4 segundos do clique
      setTimeout(function() {
        coliMosca.enable();
        coliMosca.fadein(600);
      }, 6400);

      // Eventos que acontecem apos 7.2 segundos do clique
      setTimeout(function() {
        enableInteractiveness();
      }, 7200);
    }

    // Adiciona a imagem do sistema digestivo - Ciclo Entamoeba Coli
    var sistemaDigestivo = new Game.Item("sistemaDigestivo.png");
    sistemaDigestivo.setPosition(960, 550);
    sistemaDigestivo.setScale(1.3);
    sistemaDigestivo.setAlpha(0);
    sistemaDigestivo.setZorder(5);
    sistemaDigestivo.disable();

    // Adiciona a primeira imagem do ciclo Entamoeba Coli
    var bananaInfectada = new Game.Item("temp.jpg");
    bananaInfectada.setPosition(335, 255);
    bananaInfectada.setAlpha(0);
    bananaInfectada.setZorder(5);
    bananaInfectada.disable();

    // Adiciona a segunda imagem do ciclo Entamoeba Coli
    var coliDesencistamento = new Game.Item("temp.jpg");
    coliDesencistamento.setPosition(335, 770);
    coliDesencistamento.setAlpha(0);
    coliDesencistamento.setZorder(5);
    coliDesencistamento.disable();

    // Adiciona a terceira imagem do ciclo Entamoeba Coli
    var coliEncistamento = new Game.Item("temp.jpg");
    coliEncistamento.setPosition(1520, 200);
    coliEncistamento.setScale(0.8);
    coliEncistamento.setAlpha(0);
    coliEncistamento.setZorder(5);
    coliEncistamento.disable();

    // Adiciona a quarta imagem do ciclo Entamoeba Coli
    var coliFezes = new Game.Item("fezes.png");
    coliFezes.setPosition(1520, 540);
    coliFezes.setScale(0.8);
    coliFezes.setAlpha(0);
    coliFezes.setZorder(5);
    coliFezes.disable();

    // Adiciona a quinta imagem do ciclo Entamoeba Coli
    var coliMosca = new Game.Item("temp.jpg");
    coliMosca.setPosition(1520, 880);
    coliMosca.setScale(0.8);
    coliMosca.setAlpha(0);
    coliMosca.setZorder(5);
    coliMosca.disable();

    scene[0].addItem(estudanteBananaNormal);
    scene[0].addItem(banana);
    scene[0].addItem(sistemaDigestivo);
    scene[0].addItem(bananaInfectada);
    scene[0].addItem(coliDesencistamento);
    scene[0].addItem(coliEncistamento);
    scene[0].addItem(coliFezes);
    scene[0].addItem(coliMosca);
  }

  // Adicionando o Background e os Itens na cena
  // Background
  scene[0].addBackground(fundoSalaDeAula);
  // Itens
  scene[0].addItem(setaJanela);
  scene[0].addItem(setaArmario);
  scene[0].addItem(carteiras);
  scene[0].addItem(mesaProfessor);
}
<commit_msg>removed code block - it would give problems<commit_after>'use strict';

sceneLoader[0] = function() {

  // Iniciando a nova cena
  scene[0] = new Game.Scene();
  // Adicionando musica na cena
  scene[0].setMusic("musicaSalaDeAula.mp3");

  // Adicionando uma imagem de fundo
  var fundoSalaDeAula = new Game.Background("salaDeAula.jpg");
  // Para ajuda no desenvolvimento, colocando um evento de clique no fundo para
  // Mostrar as coordenadas
  var mostraCoordenadasAoClicar = true;
  fundoSalaDeAula.click = function(mouse) {
    if (mostraCoordenadasAoClicar) {
      var mousePosition = mouse.data.getLocalPosition(stage);
      console.log(Math.round(mousePosition.x) + "; " + Math.round(mousePosition.y));
    }
  }

  var carteiras = new Game.Item("salaDeAula_carteiras.png");
  carteiras.setPosition(960, 857);
  carteiras.setZorder(10);

  var mesaProfessor = new Game.Item("salaDeAula_mesaProfessor.png");
  mesaProfessor.setPosition(1400, 550);
  mesaProfessor.setZorder(15);

  // Adiciona uma seta para levar a cena externa
  var setaJanela = new Game.Item("seta.png");
  setaJanela.setPosition(1735, 480);
  setaJanela.setScale(0.5);
  setaJanela.addGlowEffect();
  setaJanela.setZorder(1);
  setaJanela.click = function(mouse) {
    changeScene(1); // Muda para a cena exterior
  }

  // Adiciona uma seta para levar ao armario
  var setaArmario = new Game.Item("seta.png");
  setaArmario.setPosition(210, 480);
  setaArmario.setScale(0.5);
  setaArmario.setRotation(180);
  setaArmario.addGlowEffect();
  setaArmario.setZorder(1);
  setaArmario.click = function(mouse) {
    changeScene(2); // Muda para a cena exterior
  }

  // Elementos do ciclo da banana

  // Adicionando o aluno
  var estudanteBananaNormal = new Game.Item("estudanteNormal.png");
  estudanteBananaNormal.setPosition(960, 655);
  estudanteBananaNormal.setZorder(11);

  // Adiconando a banana
  var banana = new Game.Item("banana.png");
  banana.setPosition(980, 730);
  banana.setScale(0.2);
  banana.setZorder(9);
  banana.addGlowEffect();
  banana.click = function(mouse) {
    // Eventos que acontecem imediatamente apos clicar na banana
    disableInteractiveness();
    banana.removeGlow();
    fundoSalaDeAula.changeBrightness(100, 600);
    carteiras.changeBrightness(100, 600);
    mesaProfessor.changeBrightness(100, 600);
    setaJanela.fadeout(600);
    setaArmario.fadeout(600);

    // Eventos que acontecem apos 0.8 segundos do clique
    setTimeout(function() {
      setaJanela.disable();
      setaArmario.disable();
    }, 800);

    // Eventos que acontecem apos 1.6 segundos do clique
    setTimeout(function() {
      banana.fadeout(600);
      estudanteBananaNormal.fadeout(600);
    }, 1600);

    // Eventos que acontecem apos 2.4 segundos do clique
    setTimeout(function() {
      sistemaDigestivo.enable();
      sistemaDigestivo.fadein(600);
    }, 2400);

    // Eventos que acontecem apos 3.2 segundos do clique
    setTimeout(function() {
      estudanteBananaNormal.disable();
      bananaInfectada.enable();
      bananaInfectada.fadein(600);
    }, 3200);

    // Eventos que acontecem apos 4 segundos do clique
    setTimeout(function() {
      coliDesencistamento.enable();
      coliDesencistamento.fadein(600);
    }, 4000);

    // Eventos que acontecem apos 4.8 segundos do clique
    setTimeout(function() {
      coliEncistamento.enable();
      coliEncistamento.fadein(600);
    }, 4800);

    // Eventos que acontecem apos 5.6 segundos do clique
    setTimeout(function() {
      coliFezes.enable();
      coliFezes.fadein(600);
    }, 5600);

    // Eventos que acontecem apos 6.4 segundos do clique
    setTimeout(function() {
      coliMosca.enable();
      coliMosca.fadein(600);
    }, 6400);

    // Eventos que acontecem apos 7.2 segundos do clique
    setTimeout(function() {
      enableInteractiveness();
    }, 7200);
  }

  // Adiciona a imagem do sistema digestivo - Ciclo Entamoeba Coli
  var sistemaDigestivo = new Game.Item("sistemaDigestivo.png");
  sistemaDigestivo.setPosition(960, 550);
  sistemaDigestivo.setScale(1.3);
  sistemaDigestivo.setAlpha(0);
  sistemaDigestivo.setZorder(5);
  sistemaDigestivo.disable();

  // Adiciona a primeira imagem do ciclo Entamoeba Coli
  var bananaInfectada = new Game.Item("temp.jpg");
  bananaInfectada.setPosition(335, 255);
  bananaInfectada.setAlpha(0);
  bananaInfectada.setZorder(5);
  bananaInfectada.disable();

  // Adiciona a segunda imagem do ciclo Entamoeba Coli
  var coliDesencistamento = new Game.Item("temp.jpg");
  coliDesencistamento.setPosition(335, 770);
  coliDesencistamento.setAlpha(0);
  coliDesencistamento.setZorder(5);
  coliDesencistamento.disable();

  // Adiciona a terceira imagem do ciclo Entamoeba Coli
  var coliEncistamento = new Game.Item("temp.jpg");
  coliEncistamento.setPosition(1520, 200);
  coliEncistamento.setScale(0.8);
  coliEncistamento.setAlpha(0);
  coliEncistamento.setZorder(5);
  coliEncistamento.disable();

  // Adiciona a quarta imagem do ciclo Entamoeba Coli
  var coliFezes = new Game.Item("fezes.png");
  coliFezes.setPosition(1520, 540);
  coliFezes.setScale(0.8);
  coliFezes.setAlpha(0);
  coliFezes.setZorder(5);
  coliFezes.disable();

  // Adiciona a quinta imagem do ciclo Entamoeba Coli
  var coliMosca = new Game.Item("temp.jpg");
  coliMosca.setPosition(1520, 880);
  coliMosca.setScale(0.8);
  coliMosca.setAlpha(0);
  coliMosca.setZorder(5);
  coliMosca.disable();

  scene[0].addItem(estudanteBananaNormal);
  scene[0].addItem(banana);
  scene[0].addItem(sistemaDigestivo);
  scene[0].addItem(bananaInfectada);
  scene[0].addItem(coliDesencistamento);
  scene[0].addItem(coliEncistamento);
  scene[0].addItem(coliFezes);
  scene[0].addItem(coliMosca);

  // Adicionando o Background e os Itens na cena
  // Background
  scene[0].addBackground(fundoSalaDeAula);
  // Itens
  scene[0].addItem(setaJanela);
  scene[0].addItem(setaArmario);
  scene[0].addItem(carteiras);
  scene[0].addItem(mesaProfessor);
}
<|endoftext|>


<commit_before>function PlaylistsByDate(wrapper) {
    // number of days to display each time we scroll
    this.displayDays = 10;

    // we subtract these so the current day is really the last overlap day
    this.absoluteEnd = moment().endOf('day');

    // TODO: pull this from the database?
    this.absoluteStart = moment("2007-09-07");

    this.loading = false;
    this.wrapper = wrapper;

    // create content divs
    this.cdiv1 = document.createElement('div');
    $(this.wrapper).append(this.cdiv1);
    this.cdiv2 = document.createElement('div');
    $(this.wrapper).append(this.cdiv2);
    this.cdiv3 = document.createElement('div');
    $(this.wrapper).append(this.cdiv3);
}

PlaylistsByDate.prototype.loadDateSet = function(dateToLoad, destDiv, direction) {
    direction = typeof direction !== 'undefined' ? direction : null;

    this.loading = true;
    this.topReached = false;
    this.bottomReached = false;
    var inst = this;
    var start = moment(dateToLoad).subtract(this.displayDays, 'days');

    if(direction == 'up' && dateToLoad > this.absoluteEnd) {
        this.topReached = true;
    }
    else if(direction == 'down' && start < this.absoluteStart) {
        this.bottomReached = true;
    }

    $.ajax({
        'url': '/playlists/date/data?start=' + start.toISOString() + '&end=' + dateToLoad.toISOString(),
        'dataType': 'json',
    }).done(function(data) {
        var sets = data['sets'];
        var days = {};
        var daysLoaded = 0;

        for(i in sets) {
            var key = moment(sets[i]['dtstart']).startOf('day');
            if(key in days) {
                days[key].push(sets[i]);
            }
            else {
                days[key] = [sets[i]];
                daysLoaded++;
            }
        }

        // remove existing data
        $(destDiv).html('');

        for(date in days) {
            var head = document.createElement('header');
            $(head).text(moment(date).format('dddd, MMMM D, YYYY'));

            var list = document.createElement('ul');
            $.each(days[date], function(index, value) {
                var link = document.createElement('a');
                link.href = '/playlists/set/' + value['id'];

                if(value['dtend'] != null) {
                    $(link).text(moment(value['dtstart']).format('HH:mm') + "-" + moment(value['dtend']).format('HH:mm') + ": " + value['dj']['airname']);
                }
                else {
                    $(link).text(moment(value['dtstart']).format('HH:mm') + "-: " + value['dj']['airname']);
                }

                makeAjaxLink(link);

                var li = document.createElement('li');
                $(li).append(link);
                $(list).append(li);
            });

            var section = document.createElement('section');
            $(section).append(head);
            $(section).append(list);
            $(destDiv).append(section);
        }

        if(direction == 'up' || direction == 'jump') {
            $(inst.wrapper).scrollTop($(inst.cdiv2).position().top);
        }

        inst.loading = false;
    });
}

PlaylistsByDate.prototype.jumpToDate = function(dt) {
    if(dt < this.absoluteStart) {
        dt = this.absoluteStart;
    }
    else if(dt > this.absoluteEnd) {
        dt = this.absoluteEnd;
    }

    this.activeDate = moment(dt).endOf('day');

    this.loadDateSet(
        moment(this.activeDate).add(this.displayDays, 'days'), this.cdiv1);
    this.loadDateSet(this.activeDate, this.cdiv2, 'jump');
    this.loadDateSet(
        moment(this.activeDate).subtract(this.displayDays, 'days'), this.cdiv3);
}

PlaylistsByDate.prototype.scrollUp = function() {
    if(this.topReached) {
        return;
    }

    $(this.cdiv3).remove();
    this.cdiv3 = this.cdiv2;
    this.cdiv2 = this.cdiv1;

    this.cdiv1 = document.createElement('div');
    $(this.wrapper).prepend(this.cdiv1);

    // activeDate business
    this.activeDate = moment(this.activeDate).add(this.displayDays, 'days');
    this.loadDateSet(
        moment(this.activeDate).add(this.displayDays, 'days'),
        this.cdiv1, 'up');
}

PlaylistsByDate.prototype.scrollDown = function() {
    if(this.bottomReached) {
        return;
    }

    $(this.cdiv1).remove();
    this.cdiv1 = this.cdiv2;
    this.cdiv2 = this.cdiv3;

    this.cdiv3 = document.createElement('div');
    $(this.wrapper).append(this.cdiv3);

    // activeDate business
    this.activeDate = moment(this.activeDate).subtract(
        this.displayDays, 'days');
    this.loadDateSet(
        moment(this.activeDate).subtract(this.displayDays, 'days'),
        this.cdiv3, 'down');
}

PlaylistsByDate.prototype.handleScroll = function(ev) {
    var newEnd;
    var inst = ev.data.instance;

    // TODO: add a timeout for these bits

    if(!$(this).is(':animated') && !inst.loading) {
        if($(this).scrollTop() <= $(this.cdiv1).height()) {
            inst.scrollUp();
        }
        else if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
            inst.scrollDown();
        }
    }
}

PlaylistsByDate.prototype.init = function() {
    $(this.wrapper).bind('scroll', {'instance': this}, this.handleScroll);
    $('#date_jump_form').bind('submit', {'instance': this}, function(ev) {
        ev.data.instance.jumpToDate(moment($('#date_entry').val()));
        return false;
    });

    this.jumpToDate(this.absoluteEnd);
}
<commit_msg>playlists_by_date: set start date to 2015-03-05<commit_after>function PlaylistsByDate(wrapper) {
    // number of days to display each time we scroll
    this.displayDays = 10;

    // we subtract these so the current day is really the last overlap day
    this.absoluteEnd = moment().endOf('day');

    // start date for playlists by date viewer
    //this.absoluteStart = moment("2007-09-07");
    this.absoluteStart = moment("2015-03-05");

    this.loading = false;
    this.wrapper = wrapper;

    // create content divs
    this.cdiv1 = document.createElement('div');
    $(this.wrapper).append(this.cdiv1);
    this.cdiv2 = document.createElement('div');
    $(this.wrapper).append(this.cdiv2);
    this.cdiv3 = document.createElement('div');
    $(this.wrapper).append(this.cdiv3);
}

PlaylistsByDate.prototype.loadDateSet = function(dateToLoad, destDiv, direction) {
    direction = typeof direction !== 'undefined' ? direction : null;

    this.loading = true;
    this.topReached = false;
    this.bottomReached = false;
    var inst = this;
    var start = moment(dateToLoad).subtract(this.displayDays, 'days');

    if(direction == 'up' && dateToLoad > this.absoluteEnd) {
        this.topReached = true;
    }
    else if(direction == 'down' && start < this.absoluteStart) {
        this.bottomReached = true;
    }

    $.ajax({
        'url': '/playlists/date/data?start=' + start.toISOString() + '&end=' + dateToLoad.toISOString(),
        'dataType': 'json',
    }).done(function(data) {
        var sets = data['sets'];
        var days = {};
        var daysLoaded = 0;

        for(i in sets) {
            var key = moment(sets[i]['dtstart']).startOf('day');
            if(key in days) {
                days[key].push(sets[i]);
            }
            else {
                days[key] = [sets[i]];
                daysLoaded++;
            }
        }

        // remove existing data
        $(destDiv).html('');

        for(date in days) {
            var head = document.createElement('header');
            $(head).text(moment(date).format('dddd, MMMM D, YYYY'));

            var list = document.createElement('ul');
            $.each(days[date], function(index, value) {
                var link = document.createElement('a');
                link.href = '/playlists/set/' + value['id'];

                if(value['dtend'] != null) {
                    $(link).text(moment(value['dtstart']).format('HH:mm') + "-" + moment(value['dtend']).format('HH:mm') + ": " + value['dj']['airname']);
                }
                else {
                    $(link).text(moment(value['dtstart']).format('HH:mm') + "-: " + value['dj']['airname']);
                }

                makeAjaxLink(link);

                var li = document.createElement('li');
                $(li).append(link);
                $(list).append(li);
            });

            var section = document.createElement('section');
            $(section).append(head);
            $(section).append(list);
            $(destDiv).append(section);
        }

        if(direction == 'up' || direction == 'jump') {
            $(inst.wrapper).scrollTop($(inst.cdiv2).position().top);
        }

        inst.loading = false;
    });
}

PlaylistsByDate.prototype.jumpToDate = function(dt) {
    if(dt < this.absoluteStart) {
        dt = this.absoluteStart;
    }
    else if(dt > this.absoluteEnd) {
        dt = this.absoluteEnd;
    }

    this.activeDate = moment(dt).endOf('day');

    this.loadDateSet(
        moment(this.activeDate).add(this.displayDays, 'days'), this.cdiv1);
    this.loadDateSet(this.activeDate, this.cdiv2, 'jump');
    this.loadDateSet(
        moment(this.activeDate).subtract(this.displayDays, 'days'), this.cdiv3);
}

PlaylistsByDate.prototype.scrollUp = function() {
    if(this.topReached) {
        return;
    }

    $(this.cdiv3).remove();
    this.cdiv3 = this.cdiv2;
    this.cdiv2 = this.cdiv1;

    this.cdiv1 = document.createElement('div');
    $(this.wrapper).prepend(this.cdiv1);

    // activeDate business
    this.activeDate = moment(this.activeDate).add(this.displayDays, 'days');
    this.loadDateSet(
        moment(this.activeDate).add(this.displayDays, 'days'),
        this.cdiv1, 'up');
}

PlaylistsByDate.prototype.scrollDown = function() {
    if(this.bottomReached) {
        return;
    }

    $(this.cdiv1).remove();
    this.cdiv1 = this.cdiv2;
    this.cdiv2 = this.cdiv3;

    this.cdiv3 = document.createElement('div');
    $(this.wrapper).append(this.cdiv3);

    // activeDate business
    this.activeDate = moment(this.activeDate).subtract(
        this.displayDays, 'days');
    this.loadDateSet(
        moment(this.activeDate).subtract(this.displayDays, 'days'),
        this.cdiv3, 'down');
}

PlaylistsByDate.prototype.handleScroll = function(ev) {
    var newEnd;
    var inst = ev.data.instance;

    // TODO: add a timeout for these bits

    if(!$(this).is(':animated') && !inst.loading) {
        if($(this).scrollTop() <= $(this.cdiv1).height()) {
            inst.scrollUp();
        }
        else if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
            inst.scrollDown();
        }
    }
}

PlaylistsByDate.prototype.init = function() {
    $(this.wrapper).bind('scroll', {'instance': this}, this.handleScroll);
    $('#date_jump_form').bind('submit', {'instance': this}, function(ev) {
        ev.data.instance.jumpToDate(moment($('#date_entry').val()));
        return false;
    });

    this.jumpToDate(this.absoluteEnd);
}
<|endoftext|>