function m = findVisiblePart( m )
%m = findVisiblePart( m )
%   Set m.visible to a structure having the fields 'nodes', 'edges',
%   'cells', 'borderedges', and 'bordercells'.  Each of the first four is a
%   boolean array. The first three indicate which of the respective objects
%   are visible, and the fourth defines the set of edges bordering the
%   visible region.  The 'bordercells' field is a column vector of cell
%   indexes, listing the visible cell index bordering each border edge.
%   This is used to implement clipping in leaf_plot and writemeshvrml.

    clipmgens = m.plotdefaults.clipmgens;

    if m.plotdefaults.doclip
        clippingDirection = azel2dir( m.plotdefaults.clippingAzimuth, ...
                                      m.plotdefaults.clippingElevation );
        visnodes = (m.nodes * clippingDirection(:)) ...
                         >= m.plotdefaults.clippingDistance;
    else
        visnodes = true( size(m.nodes,1), 1 );
    end
    if m.plotdefaults.clipbymgen && ~isempty(clipmgens)
        if iscell( clipmgens )
            cm = zeros(1,length(clipmgens));
            for i=1:length(clipmgens)
                try cm(i) = m.mgenNameToIndex.(clipmgens{i});
                catch
                end
            end
            clipmgens = cm(cm ~= 0);
        end
        if ~isempty(clipmgens)
            if m.plotdefaults.clipmgenabove
                clipmgenvals = m.morphogens(:,clipmgens) < m.plotdefaults.clipmgenthreshold;
            else
                clipmgenvals = m.morphogens(:,clipmgens) > m.plotdefaults.clipmgenthreshold;
            end
            if m.plotdefaults.clipmgenall
                mgenclipped = sum( double(clipmgenvals), 2 );
            else
                mgenclipped = prod( double(clipmgenvals), 2 ) > 0;
            end
            visnodes = visnodes & ~mgenclipped;
        end
    end

    if size(m.tricellvxs,1)==1  % Workaround for MATLAB quirk.
        viscells = all( visnodes(m.tricellvxs) );
    else
        viscells = all( visnodes(m.tricellvxs), 2 );
    end
    visedgecells = viscells(m.edgecells(:,1));
    visedgecells(:,2) = false;
    ex2 = m.edgecells(:,2) ~= 0;
    visedgecells(ex2,2) = viscells(m.edgecells(ex2,2));
    visedges = any( visedgecells, 2 );
    borderedges = visedgecells(:,1) ~= visedgecells(:,2);
    bordercellpairs = m.edgecells(borderedges,:);
    secondcellvis = visedgecells(borderedges,2);
    bordercells = bordercellpairs(:,1);
    bordercells(secondcellvis) = bordercellpairs(secondcellvis,2);
    bordernodes = false( size(m.nodes,1), 1 );
    bordernodes( unique( m.edgeends( borderedges, : ) ) ) = true;
    m.visible = struct( ...
        'nodes', visnodes, ...
        'cells', viscells, ...
        'edges', visedges, ...
        'bordernodes', bordernodes, ...
        'borderedges', borderedges, ...
        'bordercells', bordercells );
end
