Friday 28 April 2017

no mouse control on three.js spline editor when combined with femgl in node,js

I have no mouse control on three.js spline editor when combined with femgl .

first phrase -my spline editor javascript version codes are these:

    var THREE=require('../build/three.js')


    window.THREE = THREE;

     require('./js/controls/DragControls.js')
     require('./js/controls/OrbitControls.js')
     require('./js/controls/TransformControls.js')


    var Stats=require('./js/libs/stats.min.js');

    var dat=require('./js/libs/dat.gui.min.js')



        String.prototype.format = function () {

            var str = this;
            for ( var i = 0; i < arguments.length; i ++ ) {

                str = str.replace( '{' + i + '}', arguments[ i ] );

            }
            return str;

        };

        var container, stats;
        var camera, scene, renderer;
        var splineHelperObjects = [], splineOutline;
        var splinePointsLength = 4;
        var positions = [];
        var options;

        var geometry = new THREE.BoxGeometry( 20, 20, 20 );

        var ARC_SEGMENTS = 200;
        var splineMesh;

        var splines = {};

        var params = {
            uniform: true,
            tension: 0.5,
            centripetal: true,
            chordal: true,
            addPoint: addPoint,
            removePoint: removePoint,
            exportSpline: exportSpline
        };

        function init() {


            container = document.getElementById( 'container' );

            scene = new THREE.Scene();
            camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 );
            camera.position.set( 0, 250, 1000 );
            scene.add( camera );

            scene.add( new THREE.AmbientLight( 0xf0f0f0 ) );
            var light = new THREE.SpotLight( 0xffffff, 1.5 );
            light.position.set( 0, 1500, 200 );
            light.castShadow = true;
            light.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 70, 1, 200, 2000 ) );
            light.shadow.bias = -0.000222;
            light.shadow.mapSize.width = 1024;
            light.shadow.mapSize.height = 1024;
            scene.add( light );
            spotlight = light;


            var planeGeometry = new THREE.PlaneGeometry( 2000, 2000 );
            planeGeometry.rotateX( - Math.PI / 2 );
            var planeMaterial = new THREE.ShadowMaterial();
            planeMaterial.opacity = 0.2;

            var plane = new THREE.Mesh( planeGeometry, planeMaterial );
            plane.position.y = -200;
            plane.receiveShadow = true;
            scene.add( plane );

            var helper = new THREE.GridHelper( 2000, 100 );
            helper.position.y = - 199;
            helper.material.opacity = 0.25;
            helper.material.transparent = true;
            scene.add( helper );

            var axis = new THREE.AxisHelper();
            axis.position.set( -500, -500, -500 );
            scene.add( axis );



            renderer = new THREE.WebGLRenderer( { antialias: true } );

            renderer.setClearColor( 0xf0f0f0 );
            renderer.setPixelRatio( window.devicePixelRatio );
            renderer.setSize( window.innerWidth, window.innerHeight );
            renderer.shadowMap.enabled = true;


            document.body.appendChild(renderer.domElement );


            stats = new Stats();

            document.body.appendChild( stats.dom );

            var gui = new dat.GUI();
            gui.add( params, 'uniform' );
            gui.add( params, 'tension', 0, 1 ).step( 0.01 ).onChange( function( value ) {
                splines.uniform.tension = value;
                updateSplineOutline();
            });
            gui.add( params, 'centripetal' );
            gui.add( params, 'chordal' );
            gui.add( params, 'addPoint' );
            gui.add( params, 'removePoint' );
            gui.add( params, 'exportSpline' );
            gui.open();


            // Controls
            controls = new THREE.OrbitControls( camera, renderer.domElement );

            controls.damping = 0.2;
            controls.addEventListener( 'change', render );

            transformControl = new THREE.TransformControls( camera, renderer.domElement );

            transformControl.addEventListener( 'change', render );

            scene.add( transformControl );

            // Hiding transform situation is a little in a mess :()
            transformControl.addEventListener( 'change', function( e ) {

                cancelHideTransorm();

            } );

            transformControl.addEventListener( 'mouseDown', function( e ) {

                cancelHideTransorm();

            } );

            transformControl.addEventListener( 'mouseUp', function( e ) {

                delayHideTransform();

            } );

            transformControl.addEventListener( 'objectChange', function( e ) {

                updateSplineOutline();

            } );

            var dragcontrols = new THREE.DragControls( splineHelperObjects, camera, renderer.domElement ); //
            //var dragcontrols = new DragControls( splineHelperObjects, camera, renderer.domElement ); //
            dragcontrols.enabled = false;
            dragcontrols.addEventListener( 'hoveron', function ( event ) {

                transformControl.attach( event.object );
                cancelHideTransorm();

            } );

            dragcontrols.addEventListener( 'hoveroff', function ( event ) {

                delayHideTransform();

            } );


            controls.addEventListener( 'start', function() {

                cancelHideTransorm();

            } );

            controls.addEventListener( 'end', function() {

                delayHideTransform();

            } );

            var hiding;

            function delayHideTransform() {

                cancelHideTransorm();
                hideTransform();

            }

            function hideTransform() {

                hiding = setTimeout( function() {

                    transformControl.detach( transformControl.object );

                }, 2500 )

            }

            function cancelHideTransorm() {

                if ( hiding ) clearTimeout( hiding );

            }




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

                addSplineObject( positions[ i ] );

            }
            positions = [];
            for ( i = 0; i < splinePointsLength; i ++ ) {

                positions.push( splineHelperObjects[ i ].position );

            }

            var geometry = new THREE.Geometry();

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

                geometry.vertices.push( new THREE.Vector3() );

            }

            var curve;


            curve = new THREE.CatmullRomCurve3( positions );
            curve.type = 'catmullrom';
            curve.mesh = new THREE.Line( geometry.clone(), new THREE.LineBasicMaterial( {
                color: 0xff0000,
                opacity: 0.35,
                linewidth: 2
                } ) );
            curve.mesh.castShadow = true;
            splines.uniform = curve;

            curve = new THREE.CatmullRomCurve3( positions );
            curve.type = 'centripetal';
            curve.mesh = new THREE.Line( geometry.clone(), new THREE.LineBasicMaterial( {
                color: 0x00ff00,
                opacity: 0.35,
                linewidth: 2
                } ) );
            curve.mesh.castShadow = true;
            splines.centripetal = curve;

            curve = new THREE.CatmullRomCurve3( positions );
            curve.type = 'chordal';
            curve.mesh = new THREE.Line( geometry.clone(), new THREE.LineBasicMaterial( {
                color: 0x0000ff,
                opacity: 0.35,
                linewidth: 2
                } ) );
            curve.mesh.castShadow = true;
            splines.chordal = curve;

            for ( var k in splines ) {

                var spline = splines[ k ];
                scene.add( spline.mesh );

            }

            load( [ new THREE.Vector3( 289.76843686945404, 452.51481137238443, 56.10018915737797 ),
                    new THREE.Vector3( -53.56300074753207, 171.49711742836848, -14.495472686253045 ),
                    new THREE.Vector3( -91.40118730204415, 176.4306956436485, -6.958271935582161 ),
                    new THREE.Vector3( -383.785318791128, 491.1365363371675, 47.869296953772746 ) ] );

        }



        function addSplineObject( position ) {

            var object = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( {
                color: Math.random() * 0xffffff
                } ) );
            object.material.ambient = object.material.color;
            if ( position ) {

                object.position.copy( position );

            } else {

                object.position.x = Math.random() * 1000 - 500;
                object.position.y = Math.random() * 600;
                object.position.z = Math.random() * 800 - 400;

            }

            object.castShadow = true;
            object.receiveShadow = true;
            scene.add( object );
            splineHelperObjects.push( object );
            return object;

        }

        function addPoint() {

            splinePointsLength ++;
            positions.push( addSplineObject()
                            .position );

            updateSplineOutline();

        }

        function removePoint() {

            if ( splinePointsLength <= 4 ) {

                return;

            }
            splinePointsLength --;
            positions.pop();
            scene.remove( splineHelperObjects.pop() );

            updateSplineOutline();

        }

        function updateSplineOutline() {

            var p;

            for ( var k in splines ) {

                var spline = splines[ k ];

                splineMesh = spline.mesh;

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

                    p = splineMesh.geometry.vertices[ i ];
                    p.copy( spline.getPoint( i /  ( ARC_SEGMENTS - 1 ) ) );

                }

                splineMesh.geometry.verticesNeedUpdate = true;

            }


        }

        function exportSpline() {

            var p;
            var strplace = [];
            for ( i = 0; i < splinePointsLength; i ++ ) {

                p = splineHelperObjects[ i ].position;
                strplace.push( 'new THREE.Vector3({0}, {1}, {2})'.format( p.x, p.y, p.z ) )

            }

            console.log( strplace.join( ',\n' ) );
            var code = '[' + ( strplace.join( ',\n\t' ) ) + ']';
            prompt( 'copy and paste code', code );

        }

        function load( new_positions ) {

            while ( new_positions.length > positions.length ) {

                addPoint();

            }

            while ( new_positions.length < positions.length ) {

                removePoint();

            }

            for ( i = 0; i < positions.length; i ++ ) {

                positions[ i ].copy( new_positions[ i ] );

            }

            updateSplineOutline();

        }

        function animate() {

            requestAnimationFrame( animate );
            render();
            stats.update();
            transformControl.update();

        }

        function render() {

            splines.uniform.mesh.visible = params.uniform;
            splines.centripetal.mesh.visible = params.centripetal;
            splines.chordal.mesh.visible = params.chordal;
            renderer.render( scene, camera );

        }
init();


        animate();

the source is at :https://github.com/mrdoob/three.js/blob/dev/examples/webgl_geometry_spline_editor.html

and second phrase -my femgl javascript codes are these:

const regl = require('regl')({
  extensions: 'OES_element_index_uint'
})



const camerab = require('./camera')({regl})
const createMesh = require('./fem')({regl})

const state = {
  center: [0, 0, 0],
  eye: [0, 0, 0],
  up: [0, 1, 0],
  polar: [Math.PI / 4, Math.PI / 16, 0],
  dpolar: [0, 0, 0],
  displacement: 0,
  lineWidth: 1.25,
  mode: 'stress',
  elements: true,
  lines: true,
  ortho: true,
  subdivisions: 3,
  meshData: require('./mesh.json')
}

let mesh = null

function rebuildMesh () {
  mesh = createMesh(state.meshData, state.subdivisions)
  state.center = mesh.center.slice()
  state.polar[0] = Math.PI / 4
  state.polar[1] = Math.PI / 16
  state.polar[2] = Math.log(2 * mesh.radius)
}


rebuildMesh() 
//
function handleFiles ([file]) {
  const reader = new window.FileReader()
  reader.onload = (data) => {
    try {
      const meshData = JSON.parse(data.target.result)
      mesh = createMesh(meshData, state.subdivisions)
      state.meshData = meshData
      rebuildMesh()
    } catch (e) {
      window.alert('invalid data file')
    }
  }
  reader.readAsText(file)
}

const uploadInput = document.createElement('input')
uploadInput.setAttribute('type', 'file')

uploadInput.addEventListener('change', () => {
  if (uploadInput.files && uploadInput.files.length > 0) {
    handleFiles(uploadInput.files)
  }
})
//

//
require('control-panel')([
  {
    type: 'range',
    label: 'displacement',
    min: 0,
    max: 255,
    initial: state.displacement
  },

  {
    type: 'range',
    label: 'lineWidth',
    min: 0,
    max: 10,
    initial: state.lineWidth
  },

  {
    type: 'select',
    label: 'mode',
    options: [
      'stress',
      'x',
      'y',
      'z',
      'total'
    ],
    initial: state.mode
  },
  {
    type: 'checkbox',
    label: 'ortho',
    initial: state.ortho
  },
  {
    type: 'checkbox',
    label: 'elements',
    initial: state.elements
  },
  {
    type: 'checkbox',
    label: 'lines',
    initial: state.lines
  },
  {
    type: 'range',
    label: 'subdivisions',
    min: 1,
    max: 8,
    step: 1,
    initial: state.subdivisions
  },
  {
    type: 'button',
    label: 'open file',
    action: () => {
      uploadInput.click()
    }
  }
]).on('input', (data) => {
  const psubdiv = state.subdivisions
  Object.assign(state, data)
  if (psubdiv !== data.subdivisions) {
    rebuildMesh()
  }
})
//

//
require('./gesture')({
  canvas: regl._gl.canvas,

  onZoom (dz) {
    state.dpolar[2] += 0.25 * dz
  },

  onRotate (dx, dy) {
    state.dpolar[0] += dx
    state.dpolar[1] -= dy
  }
})

//
//--------------------
require('drag-and-drop-files')(regl._gl.canvas, handleFiles)

regl.frame(({tick}) => {
  camerab.integrate(state)

  regl.clear({
    color: [0, 0, 0, 0],
    depth: 1
  })

  camerab.setup(state, () => {
    mesh.draw(state)
  })
})

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


//----------------
rebuildMesh() 
animate();

the source is at : https://github.com/mikolalysenko/femgl/blob/master/index.js

so my problem is that each of code phrases are working separately correctly . and when combined them it means merge second phrase at the end of first phrase it works,but we have no controls as mouse events in the first pharse - spline editor -.

my gitshell command is :

browserify webgl_geometry_spline_editor_js_test_03.js | indexhtmlify > webgl_geometry_spline_editor_js_test_03.html

so what could I do to have mouse control on both spline editor and femgl ? Regards



via hasanbaghal

No comments:

Post a Comment