Drawing a sine curve in 3D

I would like to draw a sine curve in Java 3D. Is there a way to do that? I am generating points on the fly and putting them in Point3D array. Then I generated the indices and used IndexedLineArray to draw lines on the fly. But they don't show up properly and there is no consistency. Is it because Java 3D is multi-threaded?
Is there a better way to do it? I need some advice. If necessary, I will post some code also.
Thank you,
-Sri :)

Yes, I have set the appearance, but I am not using any color values.
Here's some sample code:
==========================
private IndexedLineArray la;
private Shape3D shape;
Appearance a = new Appearance();
PolygonAttributes attr = new PolygonAttributes();
attr.setCullFace(PolygonAttributes.CULL_NONE);
a.setPolygonAttributes(attr);
shape = new Shape3D(la,a);
shape.setCapability(Shape3D.ALLOW_GEOMETRY_WRITE);
===========================
I think the points are being drawn too fast. Maybe I should reduce the number of frames?
-Sri :)

Similar Messages

  • Errors - drawing a text curve in flex with flex 3 with flex 3.5 framework

    Is that necessary in drawing a text curve in flex we need flex 4 with flash player 10, actually i have flex 3 with flex 3.5 framework but it is showing error like this :
    This is my code:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
    <![CDATA[
    import mx.components.TextView;
    public var myText:String = "Read my blog @ http://www.funnyjokesfunny.com";
    var radius:Number = 125;
    var spacing:Number = 8;    
    var center:Point = new Point(125,125);
    public function drawText():void {
    for (var char:uint=0;char<myText.length;char++) {
    var tempText:TextView = new TextView();
    tempText.x = radius * Math.cos(degrees2radians(char*spacing)) + center.x;
    tempText.y = radius * Math.sin(degrees2radians(char*spacing)) + center.y;
    tempText.rotation = 25;
    tempText.text = myText.charAt(char);
    textContainer.addChild(tempText);
    ]]>
    </mx:Script>
    <mx:Button label="Draw a circle" click="drawText()" />
    <mx:Canvas id="textContainer"  y="50" x="50"  width="400" height="400" />       
    </mx:Application>
    1) call to possibly  undefined method Text View
    2) Type was not found : Text view.                               
    Please help me
    Atishay

    I have now taken import mx.controls.Text;
    instead of textview it works , but in dis example http://blog.shortfusion.com/index.cfm/2009/1/25/Circular-Text-In-Flex-Explained with source code they have taken textview control and it works for them for text curve.

  • Drawing order of curve behind loaded movie

    Hi,
    I'm having an issue with the draw order of curve that's drawn
    using Actionscript. In terms of the order of execution of the
    function call, I have a SWF loaded first using the loadMovie
    function. Then I call the curveTo function with certain parameters
    to try to draw a curve on top of the loaded movie. However, the
    strange behavior is that the line is hidden behind the movie clip.
    I've used swapDepths, but it wasn't working for me. Also tried
    using the createEmptyMovieClip function with a depth number
    assigned, but didn't do the trick. Any suggestion?

    1.  there's no reason for an onEnterFrame loop.
    2. there's no reason to use any setInterval() functions in the code you showed.
    3. you should be using the same function to load your swfs.  if some logic is needed to position, for example, the different swfs in different locations, the logic should be in that function.
    ie, you should be using something like:
    _level0 swf:
    function nextMov(){
    loadF(MovieList[movieQNum]);
    movieQNum=(movieQNum+1)%MovieList.length;
    function loadF(swf:String){
    dep = getNextHighestDepth();
    currLo.removeMovieClip();
    currLo = createEmptyMovieClip("currLo"+dep, dep);
    loadMovie(moviename, currLo);
    //move the loaded movie behind movie frame
    BlackMovieFrame.swapDepths(currLo);
    function endSession(mc:MovieClip){
    mc.removeMovieClip();
    nextMove();
    // in the loaded swfs:
    var tl:MovieClip=this;
    btnArrow.onPress = function() {
    _root.endSession(tl);

  • To generate sine curve using sine pattern.vi

    I tried to generate sine wave to provide sine curve to the motor. I used sine pattern.vi and the vi located before the while loop. I could not put it inside 'while loop' to change the amplitude of the sine curve while the program runs. What do I have to make some changes in the program to provide different values in 'sine pattern.vi' while the program runs?
    Attachments:
    AO_command_sin_input_with_position_info.vi ‏165 KB

    Jae,
    Looking at your VI, it seems that what you want to do is update the sinewave generated on the fly. Try using the Point by Point functions to generate a sinewave, they will give your the most flexibility. I am attaching an example that generates a sinewave point by point. If you change the value of the frequency control, you will see that the frequency of the waveform will change on the fly.
    Attachments:
    Generate_Sinewave_PtByPt.vi ‏32 KB

  • Drawing small, short curves in Photoshop draws straight line between start and end points

    I recently installed Windows 8 Professional, Photoshop and the latest Wacom Bamboo tablet drivers and have been experiencing this issue. I've turned off windows flicks and ink. This only happens in Photoshop with the brush tool and I can't seem to find a setting that this corresponds to.
    Basically, when I draw small, short curves (particularly letters like 'c' and 'h'), when I lift up my pen, Photoshop automatically connects the end and start points together with a straight line ('c' almost becomes 'o' or 'a'). I'm not holding the shift or any modifier keys. I've tried googling this issue, but I have no idea how to phrase it properly to get any results.
    Here's an image of what I'm talking about (the top was drawn with the pencil tool, the bottom with the brush tool which demonstrates the issue. I've highlighted the start and end points with red dots):
    ANy ideas? :/

    Is caps lock on?

  • Animating the drawing of a curve

    Hi folks,
    I have an algorithm which can interpolate a set of control points into a curve. I use the LineStripArray to draw out this curve and it works fine.
    Now, my next task is to draw this same curve using animation. That is, each of the interpolated control point of the curve is added onto the canvas over time.
    The way I did it was to get all the curve's points (each one is time-tagged) up till a specified time, t. Use LineStripArray to draw it, attach it to a BranchGroup in the scene. To draw the next curve point in time, I get all the curve's points up till t+1, detach the previous LineStripArray containing the curve up till t, and attach the new LineStripArray for t+1 to the BranchGroup.
    I do this using Threads and until the end time is reached.
    The resulting animation is not very smooth as you can tell.
    Can someone give some advice on a better way of doing this?
    Thanks very much in advance.

    You've been watching the wrong tutorials. Look up ones that explain how to stroke paths or Video CoPilot's blueprint text one...
    Mylenium

  • How to draw smooth curve in Hyperdraw??

    Okay, I've checked the manual 4x and have been playing with Hyperdraw for 30 minutes and still can't figure out how to draw a smooth bell curve in the Hypereditor... In Cubase, I would take the pencil tool and draw a nice curve but can't seem to figure out how do the same in Logic!
    Could someone pleeeeease lend me a clue...?
    Thanks.

    RealDave wrote:
    "The name on the package may say "Apple," but this is definitely not your typical mac application!"
    Yes, Logic was an acquisition. It has remained to this day "The Redheaded Stepchild". If they ever take
    some engineers off the iOS projects and put them on Logic, the application may shape up. Don't get your hopes too high though. iOS is where they make all the Money. Logic is small potatoes in Apples big picture.
    PS: This message will soon disappear because it contains truth.
    To give them credit, Logic made a HUGE jump in usability when it hit Logic 8.
    I mean, MASSIVE.
    It's actually usable by mortals now.
    Even among professional tools, there are well-designed ones and completely arcane ones with the same functionality.
    Logic grew over decades of adding an extra little limb here, and growing a third chin down there, etc., at the behest of a hundred studio techs missing this or that and calling up the engineers or higher-uppers. It was an extremely powerful, but utterly convoluted MESS.
    The fact that you can now explain the basic structure of Logic 8 in less than three minutes (the fact that it HAS a "basic structure", rather than just a kraken-like reenactment of 80 years of studio development known as "The Environment") makes a huge difference, and, though they've confused people who've whittled the beast into shape over the past twenty years by trying to make the application "Logical" (including key commands), the benefits to users are, IMHO, tremendous.
    I know a number of people who wouldn't have considered working with Logic before (Nuendo users), and now that Logic 9 appears to have fixed many of the most glaring bugs in Logic 8, are adding it to their toolset.

  • Drawing curved lines in Photoshop CS 4

    I'm sure there's a simple way, but I just can't seem to draw a basic curved line in PS CS4.
    I'm designing a simple floor plan- black lines on white background- nothing 3D or fancy. I have so far just used straight black lines, but for the doors I wanted
    to create a curve to show the sweep of the door as it opens.
    I'm new to photoshop, so at first I tried to do so in a shape layer, as I did with all the straight lines. annoyingly, this always resulted in a filled in solid shape- not what I want at all.
    I then found out about paths, so I created my curve as a path, which seemed to be working in that it didn't automatically turn into a solid shape, but remained simply a line.
    However, I found that the path was not actually showing up in my floor plan unless I had it selected and was working on it. I worked out I could link it to a layer by creating a vector mask.
    However, this still meant the curve didn't display within the document when I saved out. If I rasterized the vector mask, it just made everything go black.
    Please can someone explain if there's a simple way of drawing a curved line?

    Hi,
    Thanks for your response.
    I'm a little confused-
    "Paths are not pixels, so unless you
    • use a Path as Vector Masks on Layer/Group that has content
    • apply "stroke Path with …"
    • use the Path as a Clipping Path"
    Does this mean that if I make the path with my curved line on it into a vector mask, apply a stroke path and then use the path as a clipping path, it will show up in my document? I tried doing this and it didn't work- when I saved out a jpeg it was blank. 
    If it makes it any clearer, this is what I'm trying to get to be part of my pixel output:
    I did actually try your suggestion of playing around with Layer Style, and this sort of seems to work in a weird way, but it seems incredibly strange that Photoshop doesn't provide a simpler way of doing something as basic as drawing a line!
    thanks for your help, really appreciated.

  • Pen Tool - Curve drawing under Object Lock

    How do you draw a smoother curved line as described in this tutorial in Steps 6 and 7?
    http://design.tutsplus.com/articles/create-a-glowing-neon-sign-using-the-appearance-palett e--vector-3791

    Thank you - As it turns out, I was using the tutorial here as a guide http://design.tutsplus.com/articles/create-a-glowing-neon-sign-using-the-appearance-palett e--vector-3791
    I was trying to use Steps 6, 7, and 8 to draw lines with the Pen tool that traced the interior of letters to generate a neon sign effect to keep applying new strokes to build up the glowing effect. 
    I am having difficulty recreating smooth lines inside the trace of the letters – my lines look choppy and not at all like the tutorial suggests.
    I was using the Appearance Palette, which stressed using simple paths that can be turned into vector artwork simply by using multiple fills and effects.  The approach was to use the approach outlined to avoid having to use complicated Bezier curves or stacking multiple vector shapes on top of one another.

  • Drawing a squiggly or wavy line between two points?

    I've searched and searched and cannot find a way to draw a
    squiggly or wavy line in the MOUSE_MOVED event as the user clicks
    and moves the mouse.
    How can this be done??

    if you don't want a direct line from one mouse position to
    the next, you won't want to use a mousemove event. use a timer
    event that checks the mouse position periodically and with each
    check start another timer event that executes much more rapidly and
    draws a line with perturbations (say, a sine curve) from one mouse
    position to the next.

  • Last question for today - how to draw with API circle of N pixels radius

    Hi,
    While I'm bit of exhausted while fighting with those paths movement (see my other thread in this forum) - I'd like to ask maybe someone has code snippet, which shows how to draw a circle of N pixels/N mm/inches radius?
    There is one helper function for that inside SDK samples:
    PDEPath DrawCurve(ASFixed x, ASFixed y, ASFixed x1, ASFixed y1, ASFixed x2, ASFixed y2, ASFixed x3, ASFixed y3, int lineWidth, int r, int g, int b)
    but I'm just out of my mind for today what parameters should be provided and how many calls of it I should write.
    Any help would be appreciated.

    You call it four times...
    Here is a snippet that explains the math...
    /* 4/3 * (1-cos 45)/sin 45 = 4/3 * sqrt(2) - 1 */
    #define ARC_MAGIC ((ASFixed) 0.552284749)
    #define PI ((ASFixed)3.141592654)
    void DrawCircle( ASFixed inCenterX, ASFixed inCenterY, ASFixed inRadius )
    /* draw four Bezier curves to approximate a circle */
    MoveTo( inCenterX + inRadius, inCenterY );
    CurveTo( inCenterX + inRadius, inCenterY + inRadius*ARC_MAGIC,
    inCenterX + inRadius*ARC_MAGIC, inCenterY + inRadius,
    inCenterX, inCenterY + inRadius );
    CurveTo( inCenterX - inRadius*ARC_MAGIC, inCenterY + inRadius,
    inCenterX - inRadius, inCenterY + inRadius*ARC_MAGIC,
    inCenterX - inRadius, inCenterY );
    CurveTo( inCenterX - inRadius, inCenterY - inRadius*ARC_MAGIC,
    inCenterX - inRadius*ARC_MAGIC, inCenterY - inRadius,
    inCenterX, inCenterY - inRadius );
    CurveTo( inCenterX + inRadius*ARC_MAGIC, inCenterY - inRadius,
    inCenterX + inRadius, inCenterY - inRadius*ARC_MAGIC,
    inCenterX + inRadius, inCenterY );
    Close();

  • PLEASE HELP!! Drawing Lines

    Hi, I'm new to Java and i need some help with drawing an asymptotic curve.
    I have tried many times experimenting with g.drawline but I have no idea how to do it !!
    here is an example of what i want to draw:
    http://www.iit.edu/~smart/acadyear/fredstof.gif_
    Can someone please help me?
    I need the code urgently!
    I just need the lines, plain black with a white background
    and it should also be able to be stretched to any size by dragging the corner of the window
    THANK YOU VERY, VERY MUCH.

    http://forum.java.sun.com/thread.jspa?threadID=5258979

  • Interacting with sine graph

    HI all Im new to java and was wondering if anyone could help me with this problem.
    Im trying to draw a sine wave that also allows me to click on aont point withing the graph and mark it with a dot or cross of some kind and in a text box display the coordinates of that position. Can anyone help me on what i need and how it can be done please.
    Thank you very much

    hi, here is one way you can get this to work...
    I'm assuming that you'ore drawing the sine points as some sort of Shape object. In that case all you need is to add a MouseMotionListener to your Container (probably a JPanel) where you draw your graph. Shape objects have a contains() method which will tell you if a point (i.e. the cords of the mouse pointer) are within the shape or not. So, in you motion listener, you just need to compare the cords of the pointer with the cords of all the Shapes that you drew. If there is a match, then use some Popup element to display the data values for that point on your graph.
    There are more complicated (and faster) ways of doing this, but this should give you a good start.
    If you trying to draw an image (graph) then look at the java2d tutorials which show you how to draw shapes and lines.

  • AICS3, How to curve a block of text

    I'm still using AICS3, but I hope someone can help me anyway. I'm creating a file that will eventually go to a sign shop to have vinyl letters cut. These letters are being adhered to the surface of a cone (I work in a museum: I'm always doing stuff like this.) My problem is that the entire paragraph of text, about 12 lines, needs to be curved. That way it will conform to the cone surface. I could do a series of concentric arcs, but AI does not draw arcs (by the way, an arc is defined as a set of points equidistant from a reference point arrayed in a measure of arc degrees or some other fraction of a circle circumference. It is not a curved line defined by an x,y box, which is what AICS3 misnames an "arc." So please don't tell me to use the "arc" tool. There isn't one. Sorry for the digression, but this needs to be pointed out so I don't get crazy answers.) I tried using the Envelope tool, but it is really unworkable. The text cannot be selected, the arc cannot be controlled, etc. Would it be better to do this in InDesign CS3? I'm willing to use either ID or AI if I can get it done. Thanks in advance for any help!
    MGuilfoile

    function(){return A.apply(null,[this].concat($A(arguments)))}
    Not being able to, at a minimum, draw an arc or circle by radius is absurd and there can be no debate on this.
    Well, here's the debate that "cannot be":
    This ideal arc tool you envision; tell me, which radius would you expect it to prompt you for when you need to draw a non-circular arc?
    Do you think that just because a software asks you to specify a circle in terms of center coordinates and radius that what it renders is therefore actually a circle, when otherwise it is not? Again, that's nonsense.
    In about 30 minutes, I could create for you a Javascript-based tool that runs in Illustrator and that prompts you for center coordinates and a radius and then draws a circle. Would you then consider the circles it draws to be more "correct" or "accurate"? In fact, for my own purposes, I have a very simple Javascript that lets me define an ellipse in terms of diameter and "angle" (tilt relative to the picture plane), just as ellipses are defined on industry-standard drafting templates.
    Similarly, a plug-in programmer could code an actual real-time interactive tool with which you would mousedown where you want the center of a circle to be, and then drag so as to define the radius. The interface of such a tool could even require you to drag the end of the displayed "radius" in order to change the size of the circle, and display no Bezier control points unless "converted" from a "circle" to a Bezier path. Wanna see one? Canvas. But do you think it doesn't actually draw a Bezier curve?
    Regardless, if either those tools exist in Illustrator (and just about any other program of the same type and purpose) the actual math defining the resulting path would still be cubic Bezier equations, whether you ever saw path handles and height/width values or not. If that bothers you, and you actually think it matters, you just have to use something else. And good luck efficiently doing general-purpose commercial illustration with a CAD program. Bezier math is the curve-rendering math basis of PostScript, and therefore of Illustrator. It is not "sub-standard" or "inferior" to other curve rendering equations. In fact, it is arguably superior.
    Again, if all you're saying is that Illusrtrator's Ellipse interface is sub-standard, I'd be the last to disagree. FreeHand's Elipse tool, for example, allows you to define any circular or eliptical arc or circle or ellipse with the one tool. But that doesn't change the fact that the actual math being used to plot the curve is still the same cubic Bezier equation as used in Illustrator. And you seem to think that a Bezier-described arc is not a "real" arc to any extent that matters one whit to anything.
    We've had this discussion here before. No software on the planet actually "draws a circle." Strictly speaking, you've never even seen an "actual" circle. The only "circle" (or triangle, or any other geometric primitive) you've ever actually seen is a mere physical approximation of an ideal concept. The physical result of all curve-drawing algorithms is a mere approximation, limited by the physical realities of the rendering mechanism. So if you are going to persist in this utter nonsense of making the most extremely huge mountain out of a literally microscopic molehill, you are eventually going to have to speak to the actual degree of inaccuracy that causes you such angst.
    Give me an example of a software that you think draws a "real" circle. A CAD program? How does that work? Do you know? Do you think it actually starts by shining the emitter of a CRT at the point on the screen you specify as the center, moves horizontally the distance you specify as the radius, and then scribes a circular path around the center as if being swung on a string? If that "circle" is exported as a DXF file and is then used to drive to an NC plotter, do you think the path in the DXF file is actually a circle, and not a series of straight-path facets that merely approximate a circle?
    When that DXF drawing is plotted to a pen plotter, do you think the instructions to the plotter actually say "spin the pen around this point at this distance"? No, it says "step the roller motor at these increments (move Y), while stepping the pen holder at these increments (move X)." In fact, it really usually says, "go to this XY coordinate. Then go to this XY coordinate. Then go to this XY coordinate....", in other words, drawing straight-line facets. Does that sound more like "radius and center" or " X and Y" to you?
    So do you consider a set of XY coordinate pairs that merely describe the corners of a multi-sided polygon to be a "truer" circle than that generated by automatically plotting a curve at the highest physical resolution of a marking device according to the resolution independent nature of a cubic Bezier equation?
    Have you ever run a CAD program in which you had to "regenerate the buffer" (i.e.; re-rasterize the screen image) after zooming in on the path that you naively think is being described as an "actual" circle? Have you never zoomed into a 3D model in an interactive video game and seen painfully ugly faceting?
    Now, an NC device (say, a cylinder boring machine) may actually receive commands to "set the cutter arm to this distance, then begin spinning the spindle motor at this RPM while tracking the depth at this rate." But I wouldn't recommend using that NC device or its instructions to render curves to your computer monitor or to a printing press. But if all you want to do is draw circles with a boring bar....
    JET

  • NURBS curve

    Hi,
    I have to draw a NURBS curve in Java, but there's few material in the Internet about it (for C++ there's a lot).
    I have already all the parameters needed: degree of the curve, knots, control points, fit points, weights.
    I'm not asking for the source code already done, but for some good material source.
    Thanks!

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.text.NumberFormat;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class NURBS
        NURBSPanel nurbsPanel;
        JFrame f;
        JPanel south;
        public NURBS()
            south = new JPanel(new GridLayout(0,1));
            f = new JFrame();
            f.setJMenuBar(getMenuBar());
            f.add(south, "South");
            setGUI("circle 1");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(500,650);
            f.setLocation(500,50);
            f.setVisible(true);
        private void setGUI(String id)
            south.removeAll();
            if(nurbsPanel != null)
                f.remove(nurbsPanel);
            nurbsPanel = new NURBSPanel(id);
            PointManager pointManager = new PointManager(nurbsPanel);
            nurbsPanel.addMouseListener(pointManager);
            nurbsPanel.addMouseMotionListener(pointManager);
            KnotDisplay knotDisplay = new KnotDisplay(nurbsPanel);
            WeightsPanel weightsPanel = new WeightsPanel(nurbsPanel);
            south.add(knotDisplay);
            south.add(weightsPanel);
            south.revalidate();
            f.add(nurbsPanel);
            f.validate();
            nurbsPanel.firstTime = true;
        private JMenuBar getMenuBar()
            JMenu menu = new JMenu("demo");
            ActionListener l = new ActionListener()
                public void actionPerformed(ActionEvent e)
                    JMenuItem item = (JMenuItem)e.getSource();
                    String ac = item.getActionCommand();
                    setGUI(ac);
            String[] s = { "weight test", "circle 1", "circle 2" };
            for(int j = 0; j < s.length; j++)
                JMenuItem item = new JMenuItem(s[j]);
                item.setActionCommand(s[j]);
                item.addActionListener(l);
                menu.add(item);
            JMenuBar menuBar = new JMenuBar();
            menuBar.add(menu);
            return menuBar;
        public static void main(String[] args)
            new NURBS();
    class NURBSPanel extends JPanel
        double[][] points;
        double[] knots;
        GeneralPath curve;
        int n,                  // points.length - 1    set in makeCurve
            m,                  // knots.length - 1
            p;                  // degree = m - n - 1
        NumberFormat nf;
        boolean firstTime;
        final int
            PAD    = 30,
            TICK   = 3,
            MARGIN = 2,
            X_MAX  = 8,
            Y_MAX  = 8;
        public NURBSPanel(String dataSet)
            if(dataSet.equals("weight test"))
                setWeightTest();
            else if(dataSet.equals("circle 1"))
                setCircleOne();
            else
                setCircleTwo();
            curve = new GeneralPath();
            nf = NumberFormat.getInstance();
            nf.setMaximumFractionDigits(1);
            addComponentListener(new ComponentAdapter()
                public void componentResized(ComponentEvent e)
                    if(!firstTime)
                        firstTime = true;
                        repaint();
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            drawAxes(g2);
            drawConvexPolyline(g2);
            if(firstTime)
                makeCurve();
            g2.setPaint(Color.green.darker());
            g2.draw(curve);
            drawKnots(g2);
            drawPoints(g2);
        private void makeCurve()
            curve.reset();
            final double STEPS = 20.0;
            boolean firstValue = true;
            n = points.length - 1;
            m = knots.length - 1;
            p = m - n - 1;
            // curve domain is [u[p], u[m-p]]
            // so curve is defined on non-zero intervals from u[p] up to u[m-p]
            for(int j = p; j < m-p; j++)
                double spanInterval = knots[j+1] - knots[j];
                if(spanInterval == 0)       // no interval -> no curve
                    continue;
                double dt = spanInterval / STEPS;
                double u;
                for(int k = 0; k <= STEPS; k++)
                    u = knots[j] + k * dt;
                    //System.out.println("u = " + nf.format(u));
                    Point2D.Double pv = getValue(u, j);
                    if(firstValue)
                        curve.moveTo((float)pv.x, (float)pv.y);
                        firstValue = false;
                    else
                        curve.lineTo((float)pv.x, (float)pv.y);
            firstTime = false;
        private double[] getBasisValues(double u, int k, int p)
            double[] N = new double[points.length];
            for(int j = 0; j < N.length; j++)
                N[j] = 0.0;
            // u is in interval [u[k], u[k+1]]
            // start with 0-degree coefficient, guaranteed to be non-zero
            N[k] = 1.0;
            // and triangulate toward coefficients of degree p
            for(int d = 1; d <= p; d++)
                N[k-d] = ((knots[k+1] - u) / (knots[k+1] - knots[k-d+1])) * N[k-d+1];
                for(int i = k-d+1; i <= k-1; i++)
                    N[i] = ((u - knots) / (knots[i+d] - knots[i])) * N[i] +
    ((knots[i+d+1] - u) / (knots[i+d+1] - knots[i+1])) * N[i+1];
    N[k] = ((u - knots[k]) / (knots[k+d] - knots[k])) * N[k];
    return N;
    private Point2D.Double getValue(double u, int k)
    double[] N = getBasisValues(u, k, p);
    // the curve over knot interval [u[k], u[k+1]] has at most p+1
    // non-zero coefficients: N[k-p][p], N[k-p+1][p], ... N[k][p]
    double x = 0.0, y = 0.0, w = 0.0;
    for(int j = k-p; j <= k; j++)
    if(j < 0)
    continue;
    x += N[j] * points[j][0] * points[j][2];
    y += N[j] * points[j][1] * points[j][2];
    w += N[j] * points[j][2];
    return modelToView(x/w, y/w);
    public void setWeightTest()
    points = new double[][] {
    { 1.5, 0.25, 1.0 }, { 3.5, 1.25, 1.0 }, { 0.75, 1.75, 1.0 },
    { 0.75, 5.0, 1.0 }, { 7.5, 7.5, 2.0 }, { 7.7, 1.0, 1.0 },
    { 4.3, 2.2, 1.0 }, { 5.1, 0.75, 1.0 }, { 7.5, 0.5, 1.0 }
    knots = new double[] {
    // u_0 u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8
    0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1/3.0, 2/3.0,
    // u_9 u_10 u_11 u_12 u_13 u_14 u_15
    1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0
    public void setCircleOne() // circle in triangle
    points = new double[][] {
    { 4.0, 1.0, 1.0 }, { 0.5, 1.0, 0.5 }, { 2.25, 4.03, 1.0 },
    { 4.0, 7.06, 0.5 }, { 5.75, 4.03, 1.0 }, { 7.5, 1.0, 0.5 },
    { 4.0, 1.0, 1.0 }
    knots = new double[] {
    // u_0 u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 u_9
    0.0, 0.0, 0.0, 1/3.0, 1/3.0, 2/3.0, 2/3.0, 1.0, 1.0, 1.0
    public void setCircleTwo() // circle in square
    double w = Math.pow(2, 0.5)/2;
    points = new double[][] {
    { 4.0, 1.0, 1.0 }, { 1.0, 1.0, w }, { 1.0, 4.0, 1.0 },
    { 1.0, 7.0, w }, { 4.0, 7.0, 1.0 }, { 7.0, 7.0, w },
    { 7.0, 4.0, 1.0 }, { 7.0, 1.0, w }, { 4.0, 1.0, 1.0 }
    knots = new double[] {
    // u_0 u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 u_9 u_10 u_11
    0.0, 0.0, 0.0, 1/4.0, 1/4.0, 1/2.0, 1/2.0, 3/4.0, 3/4.0, 1.0, 1.0, 1.0
    private void drawConvexPolyline(Graphics2D g2)
    g2.setPaint(new Color(240,180,180));
    double lastX = 0, lastY = 0;
    Point2D.Double pv;
    for(int j = 0; j < points.length; j++)
    pv = modelToView(points[j][0], points[j][1]);
    if(j > 0)
    g2.draw(new Line2D.Double(pv.x, pv.y, lastX, lastY));
    lastX = pv.x;
    lastY = pv.y;
    private void drawKnots(Graphics2D g2)
    g2.setPaint(Color.blue);
    // show knots only if there are curve segments, ie, only if p > m-p
    if(p > m-p)
    return;
    // curve domain is [u[p], u[m-p]]
    // send all knots within the domain, ie, including endpoints
    // with care to adjust knot interval for last knot to the previous
    // interval, viz, m-p-1 to avoid ArrayIndexOutOfBoundsException
    // in N[k] in getBasisValues method, ie, ensure N[k <= n]
    // in other words, this loop counts valid curve segments plus
    // one for the last knot on the last curve segment
    for(int j = p, k = p; j <= m-p; j++, k++)
    if(j < m-p && knots[j+1] - knots[j] == 0)
    continue;
    if(j == m-p)
    k = m-p-1;
    Point2D.Double pv = getValue(knots[j], k);
    GeneralPath path = new GeneralPath();
    path.moveTo((float)pv.x-4, (float)pv.y);
    path.lineTo((float)pv.x, (float)pv.y-4);
    path.lineTo((float)pv.x+4, (float)pv.y);
    path.lineTo((float)pv.x, (float)pv.y+4);
    g2.fill(path);
    private void drawPoints(Graphics2D g2)
    g2.setPaint(Color.red);
    for(int j = 0; j < points.length; j++)
    Point2D.Double pv = modelToView(points[j][0], points[j][1]);
    g2.fill(new Ellipse2D.Double(pv.x - 2, pv.y - 2, 4, 4));
    public Point2D.Double modelToView(double x, double y)
    double h = getHeight();
    Point2D.Double pView = new Point2D.Double();
    pView.x = PAD + x * (getWidth() - 2*PAD) / X_MAX;
    pView.y = h - PAD - (y * (h - 2*PAD) / Y_MAX);
    return pView;
    private Point2D.Double viewToModel(double x, double y)
    double w = getWidth();
    double h = getHeight();
    Point2D.Double pModel = new Point2D.Double();
    pModel.x = (x - PAD) * X_MAX / (w - 2*PAD);
    pModel.y = (h - PAD - y) * Y_MAX / (h - 2*PAD);
    return pModel;
    private void drawAxes(Graphics2D g2)
    Font font = new Font("lucida sans", Font.PLAIN, 14);
    g2.setFont(font);
    FontRenderContext frc = g2.getFontRenderContext();
    double w = getWidth();
    double h = getHeight();
    double xInc = (w - 2*PAD) / X_MAX;
    double yInc = (h - 2*PAD) / Y_MAX;
    double x1 = PAD, y1 = PAD, x2 = w-PAD, y2 = h-PAD;
    g2.setPaint(new Color(200,220,220));
    // grid lines - vertical lines across
    for(int j = 0; j <= X_MAX; j++)
    g2.draw(new Line2D.Double(x1, y1, x1, y2));
    x1 += xInc;
    // horizontal lines down
    x1 = PAD;
    for(int j = 0; j < Y_MAX; j++)
    g2.draw(new Line2D.Double(x1, y1, x2, y1));
    y1 += yInc;
    g2.setPaint(Color.black);
    // ordinate
    g2.draw(new Line2D.Double(PAD, PAD, PAD, h-PAD));
    // tic marks
    x1 = PAD - TICK; y1 = PAD; x2 = PAD;
    for(int j = 0; j <= Y_MAX; j++)
    g2.draw(new Line2D.Double(x1, y1, x2, y1));
    y1 += yInc;
    // labels
    for(int j = 0; j <= Y_MAX; j++)
    String s = String.valueOf(Y_MAX - j);
    float width = (float)font.getStringBounds(s,frc).getWidth();
    float height = font.getLineMetrics(s, frc).getAscent();
    float sx = PAD - TICK - MARGIN - width;
    float sy = (float)(PAD + j * yInc + height/2);
    g2.drawString(s, sx, sy);
    // abcissa
    g2.draw(new Line2D.Double(PAD, h-PAD, w-PAD, h-PAD));
    // tic marks
    x1 = PAD; y1 = h-PAD; y2 = h-PAD+TICK;
    for(int j = 0; j <= X_MAX; j++)
    g2.draw(new Line2D.Double(x1, y1, x1, y2));
    x1 += xInc;
    // labels
    for(int j = 0; j <= X_MAX; j++)
    String s = String.valueOf(j);
    float width = (float)font.getStringBounds(s,frc).getWidth();
    float height = font.getLineMetrics(s, frc).getAscent();
    float sx = (float)(PAD + j * xInc - width/2);
    float sy = (float)(h - PAD + TICK + MARGIN + height);
    g2.drawString(s, sx, sy);
    public void setPoint(int index, double x, double y)
    Point2D.Double pModel = viewToModel(x, y);
    points[index][0] = pModel.x;
    points[index][1] = pModel.y;
    firstTime = true;
    repaint();
    public void setKnot(int index, double value)
    knots[index] = value;
    firstTime = true;
    repaint();
    public void setWeight(int index, double weight)
    points[index][2] = weight;
    firstTime = true;
    repaint();
    class PointManager extends MouseInputAdapter
    NURBSPanel nurbsPanel;
    double[][] points;
    Point2D.Double offset;
    int selectedIndex;
    boolean dragging;
    public PointManager(NURBSPanel np)
    nurbsPanel = np;
    points = nurbsPanel.points;
    offset = new Point2D.Double();
    dragging = false;
    public void mousePressed(MouseEvent e)
    Point p = e.getPoint();
    Point2D.Double pView;
    for(int j = 0; j < points.length; j++)
    pView = nurbsPanel.modelToView(points[j][0], points[j][1]);
    if(p.distance(pView) < 5)
    selectedIndex = j;
    offset.x = p.x - pView.x;
    offset.y = p.y - pView.y;
    dragging = true;
    break;
    public void mouseReleased(MouseEvent e)
    dragging = false;
    public void mouseDragged(MouseEvent e)
    if(dragging)
    double x = e.getX() - offset.x;
    double y = e.getY() - offset.y;
    nurbsPanel.setPoint(selectedIndex, x, y);
    class KnotDisplay extends JPanel
    NURBSPanel nurbsPanel;
    JTable table;
    JSlider slider;
    double scale;
    boolean valueIsAdjusting;
    int selectedIndex;
    public KnotDisplay(NURBSPanel np)
    nurbsPanel = np;
    valueIsAdjusting = false;
    selectedIndex = 4;
    setBorder(BorderFactory.createTitledBorder("knots"));
    setLayout(new BorderLayout());
    add(getTable(), "North");
    add(getSlider());
    add(getRadioPanel(), "South");
    private void moveKnot(double d)
    nurbsPanel.setKnot(selectedIndex, d);
    table.setValueAt(String.valueOf(d), 0, selectedIndex);
    private void changeSelection()
    // reset slider values
    double lo = nurbsPanel.knots[selectedIndex-1];
    double hi = nurbsPanel.knots[selectedIndex+1];
    scale = Math.rint((hi - lo) * 1000);
    int min = (int)(lo * scale);
    int max = (int)(hi * scale);
    boolean enabled = true;
    if(max - min == 0)
    enabled = false;
    slider.setEnabled(enabled);
    int value = (int)(nurbsPanel.knots[selectedIndex] * scale);
    valueIsAdjusting = true;
    slider.setMinimum(min);
    slider.setMaximum(max);
    slider.setValue(value);
    valueIsAdjusting = false;
    private JTable getTable()
    String[] headers = new String[nurbsPanel.knots.length];
    Object[][]data = new Object[1][nurbsPanel.knots.length];
    for(int col = 0; col < data[0].length; col++)
    headers[col] = "";
    data[0][col] = String.valueOf(nurbsPanel.knots[col]);
    table = new JTable(new DefaultTableModel(data, headers));
    TableCellRenderer renderer = table.getDefaultRenderer(String.class);
    ((JLabel)renderer).setHorizontalAlignment(JLabel.CENTER);
    table.setEnabled(false);
    return table;
    private JSlider getSlider()
    double lo = nurbsPanel.knots[selectedIndex-1];
    double hi = nurbsPanel.knots[selectedIndex+1];
    scale = Math.rint((hi - lo) * 1000);
    int min = (int)(lo * scale);
    int max = (int)(hi * scale);
    int value = (int)(nurbsPanel.knots[selectedIndex] * scale);
    slider = new JSlider(JSlider.HORIZONTAL, min, max, value);
    if(max - min == 0)
    slider.setEnabled(false);
    slider.addChangeListener(new ChangeListener()
    public void stateChanged(ChangeEvent e)
    if(!valueIsAdjusting)
    double value = slider.getValue() / scale;
    moveKnot(value);
    return slider;
    private JPanel getRadioPanel()
    final JRadioButton[] buttons = new JRadioButton[nurbsPanel.knots.length];
    ButtonGroup group = new ButtonGroup();
    ActionListener l = new ActionListener()
    public void actionPerformed(ActionEvent e)
    JRadioButton radio = (JRadioButton)e.getSource();
    int index = -1;
    for(int j = 0; j < buttons.length; j++)
    if(radio == buttons[j])
    selectedIndex = j;
    break;
    changeSelection();
    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weightx = 1.0;
    for(int j = 0; j < nurbsPanel.knots.length; j++)
    buttons[j] = new JRadioButton();
    group.add(buttons[j]);
    buttons[j].addActionListener(l);
    panel.add(buttons[j], gbc);
    buttons[0].setEnabled(false);
    buttons[buttons.length-1].setEnabled(false);
    buttons[selectedIndex].setSelected(true);
    return panel;
    class WeightsPanel extends JPanel
    NURBSPanel nurbsPanel;
    JTable table;
    JSlider slider;
    double scale;
    boolean valueIsAdjusting;
    int selectedIndex;
    public WeightsPanel(NURBSPanel np)
    nurbsPanel = np;
    valueIsAdjusting = false;
    selectedIndex = 2;
    setBorder(BorderFactory.createTitledBorder("weights"));
    setLayout(new BorderLayout());
    add(getTable(), "North");
    add(getSlider());
    add(getRadioPanel(), "South");
    private void changeWeight(double d)
    nurbsPanel.setWeight(selectedIndex, d);
    table.setValueAt(String.valueOf(d), 0, selectedIndex);
    private void changeSelection()
    // reset slider value
    double weight = nurbsPanel.points[selectedIndex][2];
    setScale(weight);
    int value = (int)(weight * scale);
    valueIsAdjusting = true;
    slider.setValue(value);
    valueIsAdjusting = false;
    private void setScale(double weight)
    if(weight < 1.0)
    scale = slider.getMaximum()/5;
    else
    scale = 2.0;
    private JTable getTable()
    String[] headers = new String[nurbsPanel.points.length];
    Object[][]data = new Object[1][nurbsPanel.points.length];
    for(int col = 0; col < data[0].length; col++)
    headers[col] = "";
    data[0][col] = String.valueOf(nurbsPanel.points[col][2]);
    table = new JTable(new DefaultTableModel(data, headers));
    TableCellRenderer renderer = table.getDefaultRenderer(String.class);
    ((JLabel)renderer).setHorizontalAlignment(JLabel.CENTER);
    table.setEnabled(false);
    return table;
    private JSlider getSlider()
    double weight = nurbsPanel.points[selectedIndex][2];
    setScale(weight);
    int value = (int)(weight * scale);
    slider = new JSlider(JSlider.HORIZONTAL, 0, 50, value);
    slider.addChangeListener(new ChangeListener()
    public void stateChanged(ChangeEvent e)
    if(!valueIsAdjusting)
    double value = slider.getValue() / scale;
    changeWeight(value);
    return slider;
    private JPanel getRadioPanel()
    final JRadioButton[] buttons = new JRadioButton[nurbsPanel.points.length];
    ButtonGroup group = new ButtonGroup();
    ActionListener l = new ActionListener()
    public void actionPerformed(ActionEvent e)
    JRadioButton radio = (JRadioButton)e.getSource();
    int index = -1;
    for(int j = 0; j < buttons.length; j++)
    if(radio == buttons[j])
    selectedIndex = j;
    break;
    changeSelection();
    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weightx = 1.0;
    for(int j = 0; j < nurbsPanel.points.length; j++)
    buttons[j] = new JRadioButton();
    group.add(buttons[j]);
    buttons[j].addActionListener(l);
    panel.add(buttons[j], gbc);
    buttons[selectedIndex].setSelected(true);
    return panel;

Maybe you are looking for

  • Having issues on macbook pro with maverick

    Am having issues after downloading Maverick  the system is becoming very slow. The pinwheel keeps spinning. Any suggestions how to deal with this issue

  • Text for ipad,windows and android

    Hi I'll publish a folio for ipad , windows and android. If I have understood correctly, Is the best way to create an iPad version first and use the same folio to the other platforms. I have made a folio of 1024x768 and has 16pt for body text. PDF for

  • Firewire 400 problem

    I bought an external hard drive maxtor, been using it for a few days and it work perfectly under firewire or usb, but.. today I tryed to connect it and it seems that it had something stuck inside... I took it out and it was a small crystal ball but I

  • Question Re. Quicktime 7.04 Software Update

    Hi All, I have a question in regards to the 7.04 software update. I am running QT Pro 7.02. I read the disclaimer: QuickTime 7.0.4 is an important release that delivers numerous bug fixes, support for iLife '06, and H.264 performance improvements. Th

  • After getting Firefox 9.0 my emails are extremely hard to open; it worked fine before I updated.

    Cursor lags and moves in jerks. Email opens very slowly, and only after multiple fast clicks. Impossible to reply to emails.