示例#1
0
void testSkipListNode()
{
	SkipListNode head_bottom;
	SkipListNode head_mid;
	SkipListNode head_roof;

	head_roof.down = &head_mid; head_mid.down = &head_bottom;
	head_bottom.up = &head_mid; head_mid.up = &head_roof;

	SkipListNode b1(1), b2(2), b3(3), b4(4);
	SkipListNode m1(1), m2(2), m4(4);
	SkipListNode r1(1), r4(4);

	r1.down = &m1; m1.down = &b1;
	b1.up = &m1; m1.up = &r1;

	r4.down = &m4; m4.down = &b4;
	b4.up = &m4; m4.up = &r4;

	m2.down = &b2;
	b2.up = &m2;

	head_bottom.next = &b1; b1.next = &b2; b2.next = &b3; b3.next = &b4;
	b4.prev = &b3; b3.prev = &b2; b2.prev = &b1; b1.prev = &head_bottom;

	head_mid.next = &m1; m1.next = &m2; m2.next = &m4;
	m4.prev = &m2; m2.prev = &m1; m1.prev = &head_mid;

	head_roof.next = &r1; r1.next = &r4;
	r4.prev = &r1; r1.prev = &head_roof;

	std::cout<<head_roof;
	std::cout<<head_mid;
	std::cout<<head_bottom;

}
示例#2
0
void *show_yes_no(void *t, void *msg, void *y, void *n)
{
  p_ref r1(t),r2(msg),r3(y),r4(n);
  y=eval(y);
  n=eval(n);
  put_title(lstring_value(eval(t)));

  int x1=0,y1=0,x2=79,y2=25;
  bar(x1,y1+1,x2,y2,176,0x01);  
  center_tbox(eval(msg),0x1f);
  int key;
  char *yes=lstring_value(y);
  char *no=lstring_value(n);
  set_cursor(0,25);
  do
  {
    key=getch();
    set_cursor(0,0);
  } while (toupper(key)!=toupper(yes[0]) && toupper(key)!=toupper(no[0]));
  cls();
  if (toupper(key)==toupper(yes[0]))
    return true_symbol;
  else return NULL;
}
示例#3
0
void test_int_0()
{
    // function
    {
        std::function<int ()> r1(f_int_0);
        assert(r1() == 3);
    }
    // function pointer
    {
        int (*fp)() = f_int_0;
        std::function<int ()> r1(fp);
        assert(r1() == 3);
    }
    // functor
    {
        A_int_0 a0;
        std::function<int ()> r1(a0);
        assert(r1() == 4);
    }
}
示例#4
0
void RoutePoint::DrawGL( ViewPort &vp, bool use_cached_screen_coords )
{
    if( !m_bIsVisible )
        return;

    //    Optimization, especially apparent on tracks in normal cases
    if( m_IconName == _T("empty") && !m_bShowName && !m_bPtIsSelected ) return;

    if(m_wpBBox.GetValid() &&
       vp.view_scale_ppm == m_wpBBox_view_scale_ppm &&
       vp.rotation == m_wpBBox_rotation) {
        /* see if this waypoint can intersect with bounding box */
        LLBBox vpBBox = vp.GetBBox();
        if( vpBBox.IntersectOut( m_wpBBox ) ){
            
            // Are Range Rings enabled?
            if(m_bShowWaypointRangeRings && (m_iWaypointRangeRingsNumber > 0)){
                double factor = 1.00;
                if( m_iWaypointRangeRingsStepUnits == 1 )          // convert kilometers to NMi
                    factor = 1 / 1.852;
            
                double radius = factor * m_iWaypointRangeRingsNumber * m_fWaypointRangeRingsStep  / 60.;

                LLBBox radar_box = m_wpBBox;
                radar_box.EnLarge(radius * 2 );
                if( vpBBox.IntersectOut( radar_box ) ){
                    return;
                }
            }
            else
                return;
        }
    }

    wxPoint r;
    wxRect hilitebox;
    unsigned char transparency = 150;
    double platform_pen_width = wxRound(wxMax(1.0, g_Platform->GetDisplayDPmm() / 2));             // 0.5 mm nominal, but not less than 1 pixel
    
    if(use_cached_screen_coords && m_pos_on_screen)
        r.x = m_screen_pos.m_x, r.y = m_screen_pos.m_y;
    else
        cc1->GetCanvasPointPix( m_lat, m_lon, &r );

    if(r.x == INVALID_COORD)
        return;

//    Substitute icon?
    wxBitmap *pbm;
    if( ( m_bIsActive ) && ( m_IconName != _T("mob") ) )
        pbm = pWayPointMan->GetIconBitmap(  _T ( "activepoint" ) );
    else
        pbm = m_pbmIcon;

    //  If icon is corrupt, there is really nothing else to do...
    if(!pbm->IsOk())
        return;
    
    int sx2 = pbm->GetWidth() / 2;
    int sy2 = pbm->GetHeight() / 2;

//    Calculate the mark drawing extents
    wxRect r1( r.x - sx2, r.y - sy2, sx2 * 2, sy2 * 2 );           // the bitmap extents

    wxRect r3 = r1;
    if( m_bShowName ) {
        if( !m_pMarkFont ) {
            m_pMarkFont = FontMgr::Get().GetFont( _( "Marks" ) );
            m_FontColor = FontMgr::Get().GetFontColor( _( "Marks" ) );
            CalculateNameExtents();
        }

        if( m_pMarkFont ) {
            wxRect r2( r.x + m_NameLocationOffsetX, r.y + m_NameLocationOffsetY,
                       m_NameExtents.x, m_NameExtents.y );
            r3.Union( r2 );
        }
    }

    hilitebox = r3;
    hilitebox.x -= r.x;
    hilitebox.y -= r.y;
    
    hilitebox.x *= g_ChartScaleFactorExp;
    hilitebox.y *= g_ChartScaleFactorExp;
    hilitebox.width  *= g_ChartScaleFactorExp;
    hilitebox.height *= g_ChartScaleFactorExp;
    
    float radius;
    if( g_btouch ){
        hilitebox.Inflate( 20 );
        radius = 20.0f;
    }
    else{
        hilitebox.Inflate( 4 );
        radius = 4.0f;
    }
    
    /* update bounding box */
    if(!m_wpBBox.GetValid() || vp.view_scale_ppm != m_wpBBox_view_scale_ppm || vp.rotation != m_wpBBox_rotation) {
        double lat1, lon1, lat2, lon2;
        cc1->GetCanvasPixPoint(r.x+hilitebox.x, r.y+hilitebox.y+hilitebox.height, lat1, lon1);
        cc1->GetCanvasPixPoint(r.x+hilitebox.x+hilitebox.width, r.y+hilitebox.y, lat2, lon2);

        if(lon1 > lon2)
            m_wpBBox.Set(lat1, lon1, lat2, lon2+360);
        else
            m_wpBBox.Set(lat1, lon1, lat2, lon2);

        m_wpBBox_view_scale_ppm = vp.view_scale_ppm;
        m_wpBBox_rotation = vp.rotation;
    }

//    if(region.Contains(r3) == wxOutRegion)
//        return;
    

    ocpnDC dc;

    //  Highlite any selected point
    if( m_bPtIsSelected ) {
        wxColour hi_colour;
        if( m_bBlink ){
            wxPen *pen = g_pRouteMan->GetActiveRoutePointPen();
            hi_colour = pen->GetColour();
        }
        else{
            hi_colour = GetGlobalColor( _T ( "YELO1" ) );
        }
        
        AlphaBlending( dc, r.x + hilitebox.x, r.y + hilitebox.y, hilitebox.width, hilitebox.height, radius,
                       hi_colour, transparency );
    }
    
    bool bDrawHL = false;

    if( m_bBlink && ( gFrame->nBlinkerTick & 1 ) ) bDrawHL = true;

    if( ( !bDrawHL ) && ( NULL != m_pbmIcon ) ) {
        int glw, glh;
        unsigned int IconTexture = pWayPointMan->GetIconTexture( pbm, glw, glh );
        
        glBindTexture(GL_TEXTURE_2D, IconTexture);
        
        glEnable(GL_TEXTURE_2D);
        glEnable(GL_BLEND);
        glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
        
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        
        glColor3f(1, 1, 1);
        
        int x = r1.x, y = r1.y, w = r1.width, h = r1.height;
        
        float scale = 1.0;
 //       if(g_bresponsive){
            scale =  g_ChartScaleFactorExp;
//        }
            
        float ws = r1.width * scale;
        float hs = r1.height * scale;
        float xs = r.x - ws/2.;
        float ys = r.y - hs/2.;
        float u = (float)w/glw, v = (float)h/glh;
        
        glBegin(GL_QUADS);
        glTexCoord2f(0, 0); glVertex2f(xs, ys);
        glTexCoord2f(u, 0); glVertex2f(xs+ws, ys);
        glTexCoord2f(u, v); glVertex2f(xs+ws, ys+hs);
        glTexCoord2f(0, v); glVertex2f(xs, ys+hs);
        glEnd();
        
//         glBegin(GL_QUADS);
//         glTexCoord2f(0, 0); glVertex2f(x, y);
//         glTexCoord2f(u, 0); glVertex2f(x+w, y);
//         glTexCoord2f(u, v); glVertex2f(x+w, y+h);
//         glTexCoord2f(0, v); glVertex2f(x, y+h);
//         glEnd();

        glDisable(GL_BLEND);
        glDisable(GL_TEXTURE_2D);
    }

    if( m_bShowName && m_pMarkFont ) {
        int w = m_NameExtents.x, h = m_NameExtents.y;
        if(!m_iTextTexture && w && h) {
            wxBitmap tbm(w, h); /* render text on dc */
            wxMemoryDC dc;
            dc.SelectObject( tbm );               
            dc.SetBackground( wxBrush( *wxBLACK ) );
            dc.Clear();
            dc.SetFont( *m_pMarkFont );
            dc.SetTextForeground( *wxWHITE );
            dc.DrawText( m_MarkName, 0, 0);
            dc.SelectObject( wxNullBitmap );
            
            /* make alpha texture for text */
            wxImage image = tbm.ConvertToImage();
            unsigned char *d = image.GetData();
            unsigned char *e = new unsigned char[w * h];
            if(d && e){
                for( int p = 0; p < w*h; p++)
                    e[p] = d[3*p + 0];
            }
            
            /* create texture for rendered text */
            glGenTextures(1, &m_iTextTexture);
            glBindTexture(GL_TEXTURE_2D, m_iTextTexture);
            
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );

            m_iTextTextureWidth = NextPow2(w);
            m_iTextTextureHeight = NextPow2(h);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, m_iTextTextureWidth, m_iTextTextureHeight,
                         0, GL_ALPHA, GL_UNSIGNED_BYTE, NULL);
            glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h,
                            GL_ALPHA, GL_UNSIGNED_BYTE, e);
            delete [] e;
        }

        if(m_iTextTexture) {
            /* draw texture with text */
            glBindTexture(GL_TEXTURE_2D, m_iTextTexture);
            
            glEnable(GL_TEXTURE_2D);
            glEnable(GL_BLEND);
        
            glColor3ub(m_FontColor.Red(), m_FontColor.Green(), m_FontColor.Blue());
            
            int x = r.x + m_NameLocationOffsetX, y = r.y + m_NameLocationOffsetY;
            float u = (float)w/m_iTextTextureWidth, v = (float)h/m_iTextTextureHeight;
            glBegin(GL_QUADS);
            glTexCoord2f(0, 0); glVertex2f(x, y);
            glTexCoord2f(u, 0); glVertex2f(x+w, y);
            glTexCoord2f(u, v); glVertex2f(x+w, y+h);
            glTexCoord2f(0, v); glVertex2f(x, y+h);
            glEnd();

            glDisable(GL_BLEND);
            glDisable(GL_TEXTURE_2D);
        }
    }
    
    // Draw waypoint radar rings if activated
    if( m_iWaypointRangeRingsNumber && m_bShowWaypointRangeRings ) {
        double factor = 1.00;
        if( m_iWaypointRangeRingsStepUnits == 1 )          // nautical miles
            factor = 1 / 1.852;
        
        factor *= m_fWaypointRangeRingsStep;
        
        double tlat, tlon;
        wxPoint r1;
        ll_gc_ll( m_lat, m_lon, 0, factor, &tlat, &tlon );
        cc1->GetCanvasPointPix( tlat, tlon, &r1 );
        
        double lpp = sqrt( pow( (double) (r.x - r1.x), 2) +
        pow( (double) (r.y - r1.y), 2 ) );
        int pix_radius = (int) lpp;
        
        wxPen ppPen1( m_wxcWaypointRangeRingsColour, platform_pen_width );
        wxBrush saveBrush = dc.GetBrush();
        wxPen savePen = dc.GetPen();
        dc.SetPen( ppPen1 );
        dc.SetBrush( wxBrush( m_wxcWaypointRangeRingsColour, wxBRUSHSTYLE_TRANSPARENT ) );
        
        for( int i = 1; i <= m_iWaypointRangeRingsNumber; i++ )
            dc.StrokeCircle( r.x, r.y, i * pix_radius );
        dc.SetPen( savePen );
        dc.SetBrush( saveBrush );
    }
    
    if( m_bBlink ) g_blink_rect = CurrentRect_in_DC;               // also save for global blinker
    
    //    This will be useful for fast icon redraws
    CurrentRect_in_DC.x = r.x + hilitebox.x;
    CurrentRect_in_DC.y = r.y + hilitebox.y;
    CurrentRect_in_DC.width = hilitebox.width;
    CurrentRect_in_DC.height = hilitebox.height;

    if( m_bBlink ) g_blink_rect = CurrentRect_in_DC;               // also save for global blinker
}
示例#5
0
void test01()
{
    {
        String on1;
        on1 = "//atp:77/root/cimv25:"
              "TennisPlayer.last=\"Rafter\",first=\"Patrick\"";

        String on2;
        on2 = "//atp:77/root/cimv25:"
              "TennisPlayer.first=\"Patrick\",last=\"Rafter\"";

        CIMObjectPath r = on1;
        PEGASUS_TEST_ASSERT(r.toString() != on1);
        PEGASUS_TEST_ASSERT(r.toString() == on2);

        CIMObjectPath r2 = r;
        CIMObjectPath r3 = CIMObjectPath
            ("//atp:77/root/cimv25:"
            "TennisPlayer.first=\"Chris\",last=\"Evert\"");

        if (verbose)
        {
            XmlWriter::printValueReferenceElement(r, false);
            cout << r.toString() << endl;
        }

        Buffer mofOut;
        MofWriter::appendValueReferenceElement(mofOut, r);
        r.clear();
    }

    {
        CIMObjectPath r1 = CIMObjectPath
            ("MyClass.z=true,y=1234,x=\"Hello World\"");
        CIMObjectPath r2 = CIMObjectPath
            ("myclass.X=\"Hello World\",Z=true,Y=1234");
        CIMObjectPath r3 = CIMObjectPath ("myclass.X=\"Hello\",Z=true,Y=1234");
        // cout << r1.toString() << endl;
        // cout << r2.toString() << endl;
        PEGASUS_TEST_ASSERT(r1 == r2);
        PEGASUS_TEST_ASSERT(r1 != r3);
    }

    // Test case independence and order independence of parameters.
    {
        CIMObjectPath r1 = CIMObjectPath ("X.a=123,b=true");
        CIMObjectPath r2 = CIMObjectPath ("x.B=TRUE,A=123");
        PEGASUS_TEST_ASSERT(r1 == r2);
        PEGASUS_TEST_ASSERT(r1.makeHashCode() == r2.makeHashCode());

        CIMObjectPath r3 = CIMObjectPath ("x.B=TRUE,A=123,c=FALSE");
        PEGASUS_TEST_ASSERT(r1 != r3);
        String keyValue;

        Array<CIMKeyBinding> kbArray;
        {
            Boolean found = false;
            kbArray = r3.getKeyBindings();
            for (Uint32 i = 0; i < kbArray.size(); i++)
            {
                if (verbose)
                {
                    cout << "keyName= " <<  kbArray[i].getName().getString()
                         << " Value= " << kbArray[i].getValue() << endl;
                }
                if ( kbArray[i].getName() == CIMName ("B") )
                {
                    keyValue = kbArray[i].getValue();
                    if(keyValue == "TRUE")
                    found = true;
                }
            }
            if(!found)
            {
                cerr << "Key Binding Test error " << endl;
                exit(1);
            }
            //ATTN: KS 12 May 2002 P3 DEFER - keybinding manipulation. too
            // simplistic.
            // This code demonstrates that it is not easy to manipulate and
            // test keybindings.  Needs better tool both in CIMObjectPath and
            // separate.
        }
    }


    // Test building from component parts of CIM Reference.
    {
        CIMObjectPath r1 ("atp:77", CIMNamespaceName ("root/cimv25"),
            CIMName ("TennisPlayer"));
        CIMObjectPath r2 ("//atp:77/root/cimv25:TennisPlayer.");
        //cout << "r1 " << r1.toString() << endl;
        //cout << "r2 " << r2.toString() << endl;

        PEGASUS_TEST_ASSERT(r1 == r2);
        PEGASUS_TEST_ASSERT(r1.toString() == r2.toString());

    }


    {
        String hostName = "atp:77";
        String nameSpace = "root/cimv2";
        String className = "tennisplayer";

        CIMObjectPath r1;
        r1.setHost(hostName);
        r1.setNameSpace(nameSpace);
        r1.setClassName(className);
        PEGASUS_TEST_ASSERT(r1.getClassName().equal(CIMName ("TENNISPLAYER")));
        PEGASUS_TEST_ASSERT(!r1.getClassName().equal(CIMName ("blob")));


        String newHostName = r1.getHost();
        //cout << "HostName = " << newHostName << endl;

        CIMObjectPath r2 (hostName, nameSpace, className);
        PEGASUS_TEST_ASSERT(r1 == r2);
    }

    // Test cases for the Hostname.  CIMObjectPaths allows the
    // host to include the domain. Eg. xyz.company.com

    // First, try a good hostname
    CIMObjectPath h0("//usoPen-9.ustA-1-a.org:77/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    CIMObjectPath h1("//usoPen-9:77/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    CIMObjectPath h2("//usoPen-9/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    CIMObjectPath h3("//usoPen-9.ustA-1-a.org:0/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    CIMObjectPath h4("//usoPen-9.ustA-1-a.org:9876/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    CIMObjectPath h5("//usoPen-9.ustA-1-a.org:65535/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    CIMObjectPath h6("//usopen-9.usta-1-a.1org:77/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    CIMObjectPath h7("//192.168.1.com:77/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    CIMObjectPath h8("//192.168.0.org/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    CIMObjectPath h9("//192.168.1.80.com:77/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    CIMObjectPath h10("//192.168.0.80.org/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    CIMObjectPath h11("//192.168.1.80.255.com:77/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    CIMObjectPath h12("//192.168.0.80.254.org/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    CIMObjectPath h13("//192.168.257.80.com:77/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    CIMObjectPath h14("//192.256.0.80.org/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");

    CIMObjectPath h15("//localhost/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    CIMObjectPath h16("//ou812/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    CIMObjectPath h17("//u812/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");

    // Hostname with '_' character support checks, see bug#2556.
    CIMObjectPath h18("//_atp:9999/_root/_cimv25:_TennisPlayer");
    CIMObjectPath h19("//a_tp/_root/_cimv25:_TennisPlayer");
    CIMObjectPath h20("//atp_:9999/_root/_cimv25:_TennisPlayer");
    CIMObjectPath h21("//atp_-9:9999/_root/_cimv25:_TennisPlayer");
    CIMObjectPath h22(
        "//_a_t_p_-9.ustA-1-a.org:9999/_root/_cimv25:_TennisPlayer");
    CIMObjectPath h23("//_/root/cimv25:_TennisPlayer");
    CIMObjectPath h24("//_______/root/cimv25:_TennisPlayer");

    // try IPAddress as hostname which should be good
    CIMObjectPath h_ip0("//192.168.1.80:77/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    CIMObjectPath h_ip1("//192.168.0.255/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");

    // Try IPv6 Addresses.
    CIMObjectPath ip6_1("//[::1]:77/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");

    CIMObjectPath ip6_2("//[::ffff:192.1.2.3]:77/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");

    CIMObjectPath ip6_3("//[fffe:233:321:234d:e45:fad4:78:12]:77/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");

    CIMObjectPath ip6_4("//[fffe::]:77/root/cimv25:"
        "TennisPlayer.first=\"Chris\",last=\"Evert\"");


    Boolean errorDetected = false;

    // Invalid IPV6 Addresses
    try
    { // IPv6 addresses must be enclosed in brackets
        CIMObjectPath ip6_mb("//fffe::12ef:127/root/cimv25:"
            "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    }
    catch (const Exception&)
    {
       errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    { // IPv6 address invalid
        CIMObjectPath ip6_invalid("//[fffe::sd:77]/root/cimv25:"
            "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    }
    catch (const Exception&)
    {
       errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    {
       //Port number out of range.
       CIMObjectPath h_Port("//usoPen-9.ustA-1-a.org:9876543210/root/cimv25:"
           "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    }
    catch (const Exception&)
    {
       errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    {
       //Port number out of range.
       CIMObjectPath h_Port("//usoPen-9.ustA-1-a.org:65536/root/cimv25:"
           "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    }
    catch (const Exception&)
    {
       errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    {
       //Port number out of range.
       CIMObjectPath h_Port("//usoPen-9.ustA-1-a.org:100000/root/cimv25:"
           "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    }
    catch (const Exception&)
    {
       errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    {
        //more than three digits in an octect
        CIMObjectPath h_ErrIp0("//192.1600008.1.80:77/root/cimv25:"
            "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    }
    catch (const Exception&)
    {
        errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    {
        // Octet out of range
        CIMObjectPath op("//192.168.256.80:77/root/cimv25:"
            "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    }
    catch (const Exception&)
    {
        errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    {
        // Missing port is okay, needs be ignored
        CIMObjectPath op("//192.168.1.80:/root/cimv25:"
            "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    }
    catch (const Exception&)
    {
        errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(!errorDetected);

    errorDetected = false;
    try
    {
        // Too many octets
        CIMObjectPath op("//192.168.1.80.12/root/cimv25:"
            "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    }
    catch (const Exception&)
    {
        errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    {
        // Too few octets
        CIMObjectPath op("//192.168.80:77/root/cimv25:"
            "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    }
    catch (const Exception&)
    {
        errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    {
        // Missing port is okay, needs be ignored
        CIMObjectPath op("//usopen-9.usta-1-a.org:/root/cimv25:"
            "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    }
    catch (Exception&)
    {
        errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(!errorDetected);

    errorDetected = false;
    try
    {
        // Hostname (IP) without trailing '/' (with port)
        CIMObjectPath op("//192.168.256.80:77");
    }
    catch (const Exception&)
    {
        errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    {
        // Hostname (IP) without trailing '/' (without port)
        CIMObjectPath op("//192.168.256.80");
    }
    catch (const Exception&)
    {
        errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    {
        // Hostname without trailing '/' (with port)
        CIMObjectPath op("//usopen-9.usta-1-a.org:77");
    }
    catch (const Exception&)
    {
        errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    {
        // Hostname without trailing '/' (without port)
        CIMObjectPath op("//usopen-9.usta-1-a.org");
    }
    catch (const Exception&)
    {
        errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    {
        // Invalid first character
        CIMObjectPath op("//+usopen-9.usta-1-a.1org:77/root/cimv25:"
            "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    }
    catch (Exception&)
    {
        errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    {
        // Non-alphanum char (?)
        CIMObjectPath op("//usopen-9.usta?-1-a.org:77/root/cimv25:"
            "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    }
    catch (Exception&)
    {
        errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    {
        // Leading dot
        CIMObjectPath op("//.usopen-9.usta-1-a.org:77/root/cimv25:"
            "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    }
    catch (Exception&)
    {
        errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    {
        // Dot in the wrong spot (before a -)
        CIMObjectPath op("//usopen.-9.usta-1-a.org:77/root/cimv25:"
            "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    }
    catch (Exception&)
    {
        errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    {
        // Two dots in a row
        CIMObjectPath op("//usopen-9.usta-1-a..org:77/root/cimv25:"
            "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    }
    catch (Exception&)
    {
        errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);

    errorDetected = false;
    try
    {
        // Trailing dot
        CIMObjectPath op("//usopen-9.usta-1-a.org.:77/root/cimv25:"
            "TennisPlayer.first=\"Chris\",last=\"Evert\"");
    }
    catch (Exception&)
    {
        errorDetected = true;
    }
    PEGASUS_TEST_ASSERT(errorDetected);
}
示例#6
0
void Planet::DrawAtmosphere(const vector3d &camPos)
{
	Color col;
	double density;
	GetSBody()->GetAtmosphereFlavor(&col, &density);
	
	const double rad1 = 0.999;
	const double rad2 = 1.05;

	glPushMatrix();

	// face the camera dammit
	vector3d zaxis = (-camPos).Normalized();
	vector3d xaxis = vector3d(0,1,0).Cross(zaxis).Normalized();
	vector3d yaxis = zaxis.Cross(xaxis);
	matrix4x4d rot = matrix4x4d::MakeInvRotMatrix(xaxis, yaxis, zaxis);
	glMultMatrixd(&rot[0]);

	matrix4x4f invViewRot;
	glGetFloatv(GL_MODELVIEW_MATRIX, &invViewRot[0]);
	invViewRot.ClearToRotOnly();
	invViewRot = invViewRot.InverseOf();

	const int numLights = Pi::worldView->GetNumLights();
	assert(numLights < 4);
	vector3f lightDir[4];
	float lightCol[4][4];
	// only 
	for (int i=0; i<numLights; i++) {
		float temp[4];
		glGetLightfv(GL_LIGHT0 + i, GL_DIFFUSE, lightCol[i]);
		glGetLightfv(GL_LIGHT0 + i, GL_POSITION, temp);
		lightDir[i] = (invViewRot * vector3f(temp[0], temp[1], temp[2])).Normalized();
	}

	const double angStep = M_PI/32;
	// find angle player -> centre -> tangent point
	// tangent is from player to surface of sphere
	float tanAng = float(acos(rad1 / camPos.Length()));

	// then we can put the fucking atmosphere on the horizon
	vector3d r1(0.0, 0.0, rad1);
	vector3d r2(0.0, 0.0, rad2);
	rot = matrix4x4d::RotateYMatrix(tanAng);
	r1 = rot * r1;
	r2 = rot * r2;

	rot = matrix4x4d::RotateZMatrix(angStep);

	glDisable(GL_LIGHTING);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE);	
	glEnable(GL_BLEND);
	glDisable(GL_CULL_FACE);
	glBegin(GL_TRIANGLE_STRIP);
	for (float ang=0; ang<2*M_PI; ang+=float(angStep)) {
		vector3d norm = r1.Normalized();
		glNormal3dv(&norm.x);
		float _col[4] = { 0,0,0,0 };
		for (int lnum=0; lnum<numLights; lnum++) {
			const float dot = norm.x*lightDir[lnum].x + norm.y*lightDir[lnum].y + norm.z*lightDir[lnum].z;
			_col[0] += dot*lightCol[lnum][0];
			_col[1] += dot*lightCol[lnum][1];
			_col[2] += dot*lightCol[lnum][2];
		}
		for (int i=0; i<3; i++) _col[i] = _col[i] * col[i];
		_col[3] = col[3];
		glColor4fv(_col);
		glVertex3dv(&r1.x);
		glColor4f(0,0,0,0);
		glVertex3dv(&r2.x);
		r1 = rot * r1;
		r2 = rot * r2;
	}
	
	glEnd();
	glEnable(GL_CULL_FACE);
	glDisable(GL_BLEND);
	glEnable(GL_LIGHTING);
	glPopMatrix();
}
示例#7
0
int main()
{
//char buf[80];
ifstream fin("cis.log");
int ln= 1, gotit= 0;
Assoc<int> tot("", 0);
Regexp reet("(..):(..):(..)"), remnth("^(..)/../..");
Regexp r1("^(../../..) (..:..).. (.*)");
PerlString s;

    fin >> s;   // eat first line

    while(fin >> s){
        ln++;
//      cout << "line " << ln << ": <" << s << ">" << endl;

        PerlStringList l;

//05/20/92 10:48PM CIS 2400 988-5366
//05/21/92 09:24PM OFFLINE                                   00:00:06
        if(s.m(r1, l)){
            if(l.scalar() < 4){
                cerr << "Didn't match all expressions" << endl;
                exit(1);
            }
//            cout << "Expressions matched: " << endl << l << endl;
            PerlString a= l[3];
            if(a.m("^CIS")) gotit= 1;
            else if(a.m("^OFFLINE") && gotit){ // extract Elapsed time
                PerlStringList et, mnth;
                int hr, mn, sc, tm;

                if(a.m(reet, et) != 4){
                    cerr << "Failed to extract Elapsed time" << endl;
                    exit(1);
                }
                hr= atoi(et[1]); mn= atoi(et[2]); sc= atoi(et[3]);
                tm= (hr*60) + mn + ((sc >= 30) ? 1 : 0);

                gotit= 0;
                // extract month
                if(l[1].m(remnth, mnth) != 2){
                    cerr << "Failed to extract Month" << endl;
                    exit(1);
                }

//                cout << "Month: " << mnth[1] << " Elapsed Time = " << tm << " mins" << endl;
                tot(mnth[1]) += tm;
                                                
            }else gotit= 0;
                
        }else{
            cerr << "Didn't match any expressions" << endl;
            exit(1);
        }

    };
//    cout << "tot = " << endl << tot << endl;
    Assoc<PerlString> months;
    months("01")= "January"; months("02")= "February"; months("03")= "March";
    months("04")= "April"; months("05")= "May"; months("06")= "June";
    months("07")= "July"; months("08")= "August"; months("09")= "September";
    months("10")= "October"; months("11")= "November"; months("12")= "December";

    for(int i=0;i<tot.scalar();i++)
        cout << months(tot[i].key()) << ": " << tot[i].value() << " mins $"
             << tot[i].value() * (12.50/60.0) << endl;
    exit(0);
}
示例#8
0
static int kbic_read_regr( PIA *pi, int cont, int regr )

{   int     a, b, s;

    s = cont_map[cont];

    switch (pi->mode) {

    case 0:
        w0(regr|0x18|s);
        w2(4);
        w2(6);
        w2(4);
        w2(1);
        w0(8);
        a = r1();
        w0(0x28);
        b = r1();
        w2(4);
        return j44(a,b);

    case 1:
        w0(regr|0x38|s);
        w2(4);
        w2(6);
        w2(4);
        w2(5);
        w0(8);
        a = r12w();
        w2(4);
        return j53(a);

    case 2:
        w0(regr|0x08|s);
        w2(4);
        w2(6);
        w2(4);
        w2(0xa5);
        w2(0xa1);
        a = r0();
        w2(4);
        return a;

    case 3:
    case 4:
    case 5:
        w0(0x20|s);
        w2(4);
        w2(6);
        w2(4);
        w3(regr);
        a = r4();
        b = r4();
        w2(4);
        w2(0);
        w2(4);
        return a;

    }
    return -1;
}
dgUnsigned32 dgSlidingConstraint::JacobianDerivative (dgContraintDescritor& params)
{
	dgMatrix matrix0;
	dgMatrix matrix1;

	//dgVector angle (CalculateGlobalMatrixAndAngle (matrix0, matrix1));
	CalculateGlobalMatrixAndAngle (matrix0, matrix1);
	m_posit = (matrix0.m_posit - matrix1.m_posit) % matrix0.m_front;
	matrix1.m_posit += matrix1.m_front.Scale3 (m_posit);

	dgAssert (dgAbsf (dgFloat32 (1.0f) - (matrix0.m_front % matrix0.m_front)) < dgFloat32 (1.0e-5f)); 
	dgAssert (dgAbsf (dgFloat32 (1.0f) - (matrix0.m_up % matrix0.m_up)) < dgFloat32 (1.0e-5f)); 
	dgAssert (dgAbsf (dgFloat32 (1.0f) - (matrix0.m_right % matrix0.m_right)) < dgFloat32 (1.0e-5f)); 

	const dgVector& dir1 = matrix0.m_up;
	const dgVector& dir2 = matrix0.m_right;

	dgVector p0 (matrix0.m_posit);
	dgVector p1 (matrix1.m_posit + matrix1.m_front.Scale3 ((p0 - matrix1.m_posit) % matrix1.m_front));

	dgVector q0 (p0 + matrix0.m_front.Scale3(MIN_JOINT_PIN_LENGTH));
	dgVector q1 (p1 + matrix1.m_front.Scale3(MIN_JOINT_PIN_LENGTH));

	dgVector r0 (p0 + matrix0.m_up.Scale3(MIN_JOINT_PIN_LENGTH));
	dgVector r1 (p1 + matrix1.m_up.Scale3(MIN_JOINT_PIN_LENGTH));

	dgPointParam pointDataP;
	dgPointParam pointDataQ;
	dgPointParam pointDataR;
	InitPointParam (pointDataP, m_stiffness, p0, p1);
	InitPointParam (pointDataQ, m_stiffness, q0, q1);
	InitPointParam (pointDataR, m_stiffness, r0, r1);

	CalculatePointDerivative (0, params, dir1, pointDataP, &m_jointForce[0]); 
	CalculatePointDerivative (1, params, dir2, pointDataP, &m_jointForce[1]); 
	CalculatePointDerivative (2, params, dir1, pointDataQ, &m_jointForce[2]); 
	CalculatePointDerivative (3, params, dir2, pointDataQ, &m_jointForce[3]); 
	CalculatePointDerivative (4, params, dir2, pointDataR, &m_jointForce[4]); 

	dgInt32 ret = 5;
	if (m_jointAccelFnt) {
		dgJointCallbackParam axisParam;
		axisParam.m_accel = dgFloat32 (0.0f);
		axisParam.m_timestep = params.m_timestep;
		axisParam.m_minFriction = DG_MIN_BOUND;
		axisParam.m_maxFriction = DG_MAX_BOUND;

		if (m_jointAccelFnt (*this, &axisParam)) {
			if ((axisParam.m_minFriction > DG_MIN_BOUND) || (axisParam.m_maxFriction < DG_MAX_BOUND)) {
				params.m_forceBounds[5].m_low = axisParam.m_minFriction;
				params.m_forceBounds[5].m_upper = axisParam.m_maxFriction;
				params.m_forceBounds[5].m_normalIndex = DG_BILATERAL_FRICTION_CONSTRAINT;
			}

			CalculatePointDerivative (5, params, matrix0.m_front, pointDataP, &m_jointForce[5]); 
			//params.m_jointAccel[5] = axisParam.m_accel;
			SetMotorAcceleration (5, axisParam.m_accel, params);
			ret = 6;
		}
	}

	return dgUnsigned32 (ret);
}
示例#10
0
int main( int argc, char* argv[] )
{
    // Initialise window
    pangolin::View& container = SetupPangoGLWithCuda(1024, 768);
    size_t cu_mem_start, cu_mem_end, cu_mem_total;
    cudaMemGetInfo( &cu_mem_start, &cu_mem_total );
    glClearColor(1,1,1,0);

    // Open video device
    hal::Camera video = OpenRpgCamera(argc,argv);

    // Capture first image
    pb::ImageArray images;

    // N cameras, each w*h in dimension, greyscale
    const size_t N = video.NumChannels();
    if( N != 2 ) {
        std::cerr << "Two images are required to run this program!" << std::endl;
        exit(1);
    }
    const size_t nw = video.Width();
    const size_t nh = video.Height();

    // Capture first image
    video.Capture(images);

    // Downsample this image to process less pixels
    const int max_levels = 6;
    const int level = roo::GetLevelFromMaxPixels( nw, nh, 640*480 );
//    const int level = 4;
    assert(level <= max_levels);

    // Find centered image crop which aligns to 16 pixels at given level
    const NppiRect roi = roo::GetCenteredAlignedRegion(nw,nh,16 << level,16 << level);

    // Load Camera intrinsics from file
    GetPot clArgs( argc, argv );
    const std::string filename = clArgs.follow("","-cmod");
    if( filename.empty() ) {
        std::cerr << "Camera models file is required!" << std::endl;
        exit(1);
    }
    const calibu::CameraRig rig = calibu::ReadXmlRig(filename);

    if( rig.cameras.size() != 2 ) {
        std::cerr << "Two camera models are required to run this program!" << std::endl;
        exit(1);
    }

    Eigen::Matrix3f CamModel0 = rig.cameras[0].camera.K().cast<float>();
    Eigen::Matrix3f CamModel1 = rig.cameras[1].camera.K().cast<float>();

    roo::ImageIntrinsics camMod[] = {
        {CamModel0(0,0),CamModel0(1,1),CamModel0(0,2),CamModel0(1,2)},
        {CamModel1(0,0),CamModel1(1,1),CamModel1(0,2),CamModel1(1,2)}
    };

    for(int i=0; i<2; ++i ) {
        // Adjust to match camera image dimensions
        const double scale = nw / rig.cameras[i].camera.Width();
        roo::ImageIntrinsics camModel = camMod[i].Scale( scale );

        // Adjust to match cropped aligned image
        camModel = camModel.CropToROI( roi );

        camMod[i] = camModel;
    }

    const unsigned int w = roi.width;
    const unsigned int h = roi.height;
    const unsigned int lw = w >> level;
    const unsigned int lh = h >> level;

    const Eigen::Matrix3d& K0 = camMod[0].Matrix();
    const Eigen::Matrix3d& Kl = camMod[0][level].Matrix();

    std::cout << "K Matrix: " << std::endl << K0 << std::endl;
    std::cout << "K Matrix - Level: " << std::endl << Kl << std::endl;

    std::cout << "Video stream dimensions: " << nw << "x" << nh << std::endl;
    std::cout << "Chosen Level: " << level << std::endl;
    std::cout << "Processing dimensions: " << lw << "x" << lh << std::endl;
    std::cout << "Offset: " << roi.x << "x" << roi.y << std::endl;

    // print selected camera model
    std::cout << "Camera Model used: " << std::endl << camMod[0][level].Matrix() << std::endl;

    Eigen::Matrix3d RDFvision;RDFvision<< 1,0,0,  0,1,0,  0,0,1;
    Eigen::Matrix3d RDFrobot; RDFrobot << 0,1,0,  0,0, 1,  1,0,0;
    Eigen::Matrix4d T_vis_ro = Eigen::Matrix4d::Identity();
    T_vis_ro.block<3,3>(0,0) = RDFvision.transpose() * RDFrobot;
    Eigen::Matrix4d T_ro_vis = Eigen::Matrix4d::Identity();
    T_ro_vis.block<3,3>(0,0) = RDFrobot.transpose() * RDFvision;

    const Sophus::SE3d T_rl_orig = T_rlFromCamModelRDF(rig.cameras[0], rig.cameras[1], RDFvision);

    // TODO(jmf): For now, assume cameras are rectified. Later allow unrectified cameras.
    /*
    double k1 = 0;
    double k2 = 0;

    if(cam[0].Type() == MVL_CAMERA_WARPED)
    {
        k1 = cam[0].GetModel()->warped.kappa1;
        k2 = cam[0].GetModel()->warped.kappa2;
    }
    */

    const bool rectify = false;
    if(!rectify) {
        std::cout << "Using pre-rectified images" << std::endl;
    }

    // Check we received at least two images
    if(images.Size() < 2) {
        std::cerr << "Failed to capture first stereo pair from camera" << std::endl;
        return -1;
    }

    // Define Camera Render Object (for view / scene browsing)
    pangolin::OpenGlRenderState s_cam(
        pangolin::ProjectionMatrixRDF_TopLeft(w,h,K0(0,0),K0(1,1),K0(0,2),K0(1,2),0.1,10000),
        pangolin::IdentityMatrix(pangolin::GlModelViewStack)
    );

    pangolin::GlBufferCudaPtr vbo(pangolin::GlArrayBuffer, lw*lh,GL_FLOAT, 4, cudaGraphicsMapFlagsWriteDiscard, GL_STREAM_DRAW );
    pangolin::GlBufferCudaPtr cbo(pangolin::GlArrayBuffer, lw*lh,GL_UNSIGNED_BYTE, 4, cudaGraphicsMapFlagsWriteDiscard, GL_STREAM_DRAW );
    pangolin::GlBuffer ibo = pangolin::MakeTriangleStripIboForVbo(lw,lh);

    // Allocate Camera Images on device for processing
    roo::Image<unsigned char, roo::TargetHost, roo::DontManage> hCamImg[] = {{0,nw,nh},{0,nw,nh}};
    roo::Image<float2, roo::TargetDevice, roo::Manage> dLookup[] = {{w,h},{w,h}};

    roo::Image<unsigned char, roo::TargetDevice, roo::Manage> upload(w,h);
    roo::Pyramid<unsigned char, max_levels, roo::TargetDevice, roo::Manage> img_pyr[] = {{w,h},{w,h}};

    roo::Image<float, roo::TargetDevice, roo::Manage> img[] = {{lw,lh},{lw,lh}};
    roo::Volume<float, roo::TargetDevice, roo::Manage> vol[] = {{lw,lh,MAXD},{lw,lh,MAXD}};
    roo::Image<float, roo::TargetDevice, roo::Manage>  disp[] = {{lw,lh},{lw,lh}};
    roo::Image<float, roo::TargetDevice, roo::Manage> meanI(lw,lh);
    roo::Image<float, roo::TargetDevice, roo::Manage> varI(lw,lh);
    roo::Image<float, roo::TargetDevice, roo::Manage> temp[] = {{lw,lh},{lw,lh},{lw,lh},{lw,lh},{lw,lh}};

    roo::Image<float,roo::TargetDevice, roo::Manage>& imgd = disp[0];
    roo::Image<float,roo::TargetDevice, roo::Manage> depthmap(lw,lh);
    roo::Image<float,roo::TargetDevice, roo::Manage> imga(lw,lh);
    roo::Image<float2,roo::TargetDevice, roo::Manage> imgq(lw,lh);
    roo::Image<float,roo::TargetDevice, roo::Manage> imgw(lw,lh);

    roo::Image<float4, roo::TargetDevice, roo::Manage>  d3d(lw,lh);
    roo::Image<unsigned char, roo::TargetDevice,roo::Manage> Scratch(lw*sizeof(roo::LeastSquaresSystem<float,6>),lh);

    typedef ulong4 census_t;
    roo::Image<census_t, roo::TargetDevice, roo::Manage> census[] = {{lw,lh},{lw,lh}};

    // Stereo transformation (post-rectification)
    Sophus::SE3d T_rl = T_rl_orig;

    const double baseline = T_rl.translation().norm();
    std::cout << "Baseline: " << baseline << std::endl;

    cudaMemGetInfo( &cu_mem_end, &cu_mem_total );
    std::cout << "CuTotal: " << cu_mem_total/(1024*1024) << ", Available: " << cu_mem_end/(1024*1024) << ", Used: " << (cu_mem_start-cu_mem_end)/(1024*1024) << std::endl;

    pangolin::Var<bool> step("ui.step", false, false);
    pangolin::Var<bool> run("ui.run", false, true);
    pangolin::Var<bool> lockToCam("ui.Lock to cam", false, true);
    pangolin::Var<int> show_slice("ui.show slice",MAXD/2, 0, MAXD-1);

    pangolin::Var<int> maxdisp("ui.maxdisp",MAXD, 0, MAXD);
    pangolin::Var<bool> subpix("ui.subpix", true, true);

    pangolin::Var<bool> use_census("ui.use census", true, true);
    pangolin::Var<int> avg_rad("ui.avg_rad",0, 0, 100);

    pangolin::Var<bool> do_dtam("ui.do dtam", false, true);
    pangolin::Var<bool> dtam_reset("ui.reset", false, false);

    pangolin::Var<float> g_alpha("ui.g alpha", 14, 0,4);
    pangolin::Var<float> g_beta("ui.g beta", 2.5, 0,2);


    pangolin::Var<float> theta("ui.theta", 100, 0,100);
    pangolin::Var<float> lambda("ui.lambda", 20, 0,20);
    pangolin::Var<float> sigma_q("ui.sigma q", 0.7, 0, 1);
    pangolin::Var<float> sigma_d("ui.sigma d", 0.7, 0, 1);
    pangolin::Var<float> huber_alpha("ui.huber alpha", 0.002, 0, 0.01);
    pangolin::Var<float> beta("ui.beta", 0.00001, 0, 0.01);

    pangolin::Var<float> alpha("ui.alpha", 0.9, 0,1);
    pangolin::Var<float> r1("ui.r1", 100, 0,0.01);
    pangolin::Var<float> r2("ui.r2", 100, 0,0.01);

    pangolin::Var<bool> filter("ui.filter", false, true);
    pangolin::Var<float> eps("ui.eps",0.01*0.01, 0, 0.01);
    pangolin::Var<int> rad("ui.radius",9, 1, 20);

    pangolin::Var<bool> leftrightcheck("ui.left-right check", false, true);
    pangolin::Var<float> maxdispdiff("ui.maxdispdiff",1, 0, 5);

    pangolin::Var<int> domedits("ui.median its",1, 1, 10);
    pangolin::Var<bool> domed9x9("ui.median 9x9", false, true);
    pangolin::Var<bool> domed7x7("ui.median 7x7", false, true);
    pangolin::Var<bool> domed5x5("ui.median 5x5", false, true);
    pangolin::Var<int> medi("ui.medi",12, 0, 24);

    pangolin::Var<float> filtgradthresh("ui.filt grad thresh", 0, 0, 20);

    pangolin::Var<bool> save_depthmaps("ui.save_depthmaps", false, true);

    int jump_frames = 0;

    pangolin::RegisterKeyPressCallback(' ', [&run](){run = !run;} );
    pangolin::RegisterKeyPressCallback('l', [&lockToCam](){lockToCam = !lockToCam;} );
    pangolin::RegisterKeyPressCallback(pangolin::PANGO_SPECIAL + GLUT_KEY_RIGHT, [&step](){step=true;} );
    pangolin::RegisterKeyPressCallback(']', [&jump_frames](){jump_frames=100;} );
    pangolin::RegisterKeyPressCallback('}', [&jump_frames](){jump_frames=1000;} );

    pangolin::Handler2dImageSelect handler2d(lw,lh,level);
//    ActivateDrawPyramid<unsigned char,max_levels> adleft(img_pyr[0],GL_LUMINANCE8, false, true);
//    ActivateDrawPyramid<unsigned char,max_levels> adright(img_pyr[1],GL_LUMINANCE8, false, true);
    pangolin::ActivateDrawImage<float> adleft(img[0],GL_LUMINANCE32F_ARB, false, true);
    pangolin::ActivateDrawImage<float> adright(img[1],GL_LUMINANCE32F_ARB, false, true);
    pangolin::ActivateDrawImage<float> adisp(disp[0],GL_LUMINANCE32F_ARB, false, true);
    pangolin::ActivateDrawImage<float> adw(imgw,GL_LUMINANCE32F_ARB, false, true);
//    ActivateDrawImage<float> adCrossSection(dCrossSection,GL_RGBA_FLOAT32_APPLE, false, true);
    pangolin::ActivateDrawImage<float> adVol(vol[0].ImageXY(show_slice),GL_LUMINANCE32F_ARB, false, true);

    SceneGraph::GLSceneGraph graph;
    SceneGraph::GLVbo glvbo(&vbo,&ibo,&cbo);
    graph.AddChild(&glvbo);

    SetupContainer(container, 6, (float)w/h);
    container[0].SetDrawFunction(boost::ref(adleft)).SetHandler(&handler2d);
    container[1].SetDrawFunction(boost::ref(adright)).SetHandler(&handler2d);
    container[2].SetDrawFunction(boost::ref(adisp)).SetHandler(&handler2d);
    container[3].SetDrawFunction(boost::ref(adVol)).SetHandler(&handler2d);
    container[4].SetDrawFunction(SceneGraph::ActivateDrawFunctor(graph, s_cam))
                .SetHandler( new pangolin::Handler3D(s_cam, pangolin::AxisNone) );
    container[5].SetDrawFunction(boost::ref(adw)).SetHandler(&handler2d);

    for(unsigned long frame=0; !pangolin::ShouldQuit();)
    {
        bool go = frame==0 || jump_frames > 0 || run || Pushed(step);

        for(; jump_frames > 0; jump_frames--) {
            video.Capture(images);
        }

        if(go) {
            if(frame>0) {
                if( video.Capture(images) == false) {
                    exit(1);
                }
            }

            frame++;

            /////////////////////////////////////////////////////////////
            // Upload images to device (Warp / Decimate if necessery)
            for(int i=0; i<2; ++i ) {
                hCamImg[i].ptr = images[i].data();

                if(rectify) {
                    upload.CopyFrom(hCamImg[i].SubImage(roi));
                    Warp(img_pyr[i][0], upload, dLookup[i]);
                }else{
                    img_pyr[i][0].CopyFrom(hCamImg[i].SubImage(roi));
                }

                roo::BoxReduce<unsigned char, max_levels, unsigned int>(img_pyr[i]);
            }
        }

        go |= avg_rad.GuiChanged() | use_census.GuiChanged();
        if( go ) {
            for(int i=0; i<2; ++i ) {
                roo::ElementwiseScaleBias<float,unsigned char,float>(img[i], img_pyr[i][level],1.0f/255.0f);
                if(avg_rad > 0 ) {
                    roo::BoxFilter<float,float,float>(temp[0],img[i],Scratch,avg_rad);
                    roo::ElementwiseAdd<float,float,float,float>(img[i], img[i], temp[0], 1, -1, 0.5);
                }
                if(use_census) {
                    Census(census[i], img[i]);
                }
            }
        }

        if( go | g_alpha.GuiChanged() || g_beta.GuiChanged() ) {
            ExponentialEdgeWeight(imgw, img[0], g_alpha, g_beta);
        }

        go |= filter.GuiChanged() | leftrightcheck.GuiChanged() | rad.GuiChanged() | eps.GuiChanged() | alpha.GuiChanged() | r1.GuiChanged() | r2.GuiChanged();
        if(go) {
            if(use_census) {
                roo::CensusStereoVolume<float, census_t>(vol[0], census[0], census[1], maxdisp, -1);
                if(leftrightcheck) roo::CensusStereoVolume<float, census_t>(vol[1], census[1], census[0], maxdisp, +1);
            }else{
                CostVolumeFromStereoTruncatedAbsAndGrad(vol[0], img[0], img[1], -1, alpha, r1, r2);
                if(leftrightcheck) CostVolumeFromStereoTruncatedAbsAndGrad(vol[1], img[1], img[0], +1, alpha, r1, r2);
            }

            if(filter) {
                // Filter Cost volume
                for(int v=0; v<(leftrightcheck?2:1); ++v)
                {
                    roo::Image<float, roo::TargetDevice, roo::Manage>& I = img[v];
                    roo::ComputeMeanVarience<float,float,float>(varI, temp[0], meanI, I, Scratch, rad);

                    for(int d=0; d<maxdisp; ++d)
                    {
                        roo::Image<float> P = vol[v].ImageXY(d);
                        roo::ComputeCovariance(temp[0],temp[2],temp[1],P,meanI,I,Scratch,rad);
                        GuidedFilter(P,temp[0],varI,temp[1],meanI,I,Scratch,temp[2],temp[3],temp[4],rad,eps);
                    }
                }
            }
        }

        static int n = 0;
//        static float theta = 0;
//        go |= Pushed(dtam_reset);
//        if(go )
        if(Pushed(dtam_reset))
        {
            n = 0;
            theta.Reset();

            // Initialise primal and auxillary variables
            CostVolMinimumSubpix(imgd,vol[0], maxdisp,-1);
            imga.CopyFrom(imgd);

            // Initialise dual variable
            imgq.Memset(0);
        }

        const double min_theta = 1E-0;
        if(do_dtam && theta > min_theta)
        {
            for(int i=0; i<5; ++i ) {
                // Auxillary exhaustive search
                CostVolMinimumSquarePenaltySubpix(imga, vol[0], imgd, maxdisp, -1, lambda, (theta) );

                // Dual Ascent
                roo::WeightedHuberGradU_DualAscentP(imgq, imgd, imgw, sigma_q, huber_alpha);

                // Primal Descent
                roo::WeightedL2_u_minus_g_PrimalDescent(imgd, imgq, imga, imgw, sigma_d, 1.0f / (theta) );

                theta= theta * (1-beta*n);
                ++n;
            }
            if( theta <= min_theta && save_depthmaps ) {
                cv::Mat dmap = cv::Mat( lh, lw, CV_32FC1 );
                // convert disparity to depth
                roo::Disp2Depth(imgd, depthmap, Kl(0,0), baseline );
                depthmap.MemcpyToHost( dmap.data );

                // save depth image
                char            Index[10];
                sprintf( Index, "%05d", frame );
                std::string DepthPrefix = "SDepth-";
                std::string DepthFile;
                DepthFile = DepthPrefix + Index + ".pdm";
                std::cout << "Depth File: " << DepthFile << std::endl;
                std::ofstream pDFile( DepthFile.c_str(), std::ios::out | std::ios::binary );
                pDFile << "P7" << std::endl;
                pDFile << dmap.cols << " " << dmap.rows << std::endl;
                unsigned int Size = dmap.elemSize1() * dmap.rows * dmap.cols;
                pDFile << 4294967295 << std::endl;
                pDFile.write( (const char*)dmap.data, Size );
                pDFile.close();

                // save grey image
                std::string GreyPrefix = "Left-";
                std::string GreyFile;
                GreyFile = GreyPrefix + Index + ".pgm";
                std::cout << "Grey File: " << GreyFile << std::endl;
                cv::Mat gimg = cv::Mat( lh, lw, CV_8UC1 );
                img_pyr[0][level].MemcpyToHost( gimg.data );
                cv::imwrite( GreyFile, gimg );

                 // reset
                step = true;
                dtam_reset = true;
            }
        }

        go |= pangolin::GuiVarHasChanged();
//        if(go) {
//            if(subpix) {
//                CostVolMinimumSubpix(disp[0],vol[0], maxdisp,-1);
//                if(leftrightcheck) CostVolMinimumSubpix(disp[1],vol[1], maxdisp,+1);
//            }else{
//                CostVolMinimum<float,float>(disp[0],vol[0], maxdisp);
//                if(leftrightcheck) CostVolMinimum<float,float>(disp[1],vol[1], maxdisp);
//            }

//        }

        if(go) {
            for(int di=0; di<(leftrightcheck?2:1); ++di) {
                for(int i=0; i < domedits; ++i ) {
                    if(domed9x9) MedianFilterRejectNegative9x9(disp[di],disp[di], medi);
                    if(domed7x7) MedianFilterRejectNegative7x7(disp[di],disp[di], medi);
                    if(domed5x5) MedianFilterRejectNegative5x5(disp[di],disp[di], medi);
                }
            }

            if(leftrightcheck ) {
                LeftRightCheck(disp[1], disp[0], +1, maxdispdiff);
                LeftRightCheck(disp[0], disp[1], -1, maxdispdiff);
            }

            if(filtgradthresh > 0) {
                FilterDispGrad(disp[0], disp[0], filtgradthresh);
            }
        }

//        if(go)
        {
            // Generate point cloud from disparity image
            DisparityImageToVbo(d3d, disp[0], baseline, Kl(0,0), Kl(1,1), Kl(0,2), Kl(1,2) );

//            if(container[3].IsShown())
            {
                // Copy point cloud into VBO
                {
                    pangolin::CudaScopedMappedPtr var(vbo);
                    roo::Image<float4> dVbo((float4*)*var,lw,lh);
                    dVbo.CopyFrom(d3d);
                }

                // Generate CBO
                {
                    pangolin::CudaScopedMappedPtr var(cbo);
                    roo::Image<uchar4> dCbo((uchar4*)*var,lw,lh);
                    roo::ConvertImage<uchar4,unsigned char>(dCbo, img_pyr[0][level]);
                }
            }

            // Update texture views
            adisp.SetImageScale(1.0f/maxdisp);
//            adleft.SetLevel(show_level);
//            adright.SetLevel(show_level);
            adVol.SetImage(vol[0].ImageXY(show_slice));
        }

        /////////////////////////////////////////////////////////////
        // Draw

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glColor3f(1,1,1);

        pangolin::FinishFrame();
    }
}
示例#11
0
Foam::cylindricalCS Foam::arcEdge::calcAngle()
{
    vector a = p2_ - p1_;
    vector b = p3_ - p1_;

    // find centre of arcEdge
    scalar asqr = a & a;
    scalar bsqr = b & b;
    scalar adotb = a & b;

    scalar denom = asqr*bsqr - adotb*adotb;

    if (mag(denom) < VSMALL)
    {
        FatalErrorIn("cylindricalCS arcEdge::calcAngle()")
            << "Invalid arc definition - are the points co-linear?  Denom ="
            << denom
            << abort(FatalError);
    }

    scalar fact = 0.5*(bsqr - adotb)/denom;

    point centre = 0.5*a + fact*((a ^ b) ^ a);

    centre += p1_;

    // find position vectors w.r.t. the arcEdge centre
    vector r1(p1_ - centre);
    vector r2(p2_ - centre);
    vector r3(p3_ - centre);

    // find angles
    angle_ = radToDeg(acos((r3 & r1)/(mag(r3) * mag(r1))));

    // check if the vectors define an exterior or an interior arcEdge
    if (((r1 ^ r2) & (r1 ^ r3)) < 0.0)
    {
        angle_ = 360.0 - angle_;
    }

    vector tempAxis;

    if (angle_ <= 180.0)
    {
        tempAxis = r1 ^ r3;

        if (mag(tempAxis)/(mag(r1)*mag(r3)) < 0.001)
        {
            tempAxis = r1 ^ r2;
        }
    }
    else
    {
        tempAxis = r3 ^ r1;
    }

    radius_ = mag(r3);

    // set up and return the local coordinate system
    return cylindricalCS("arcEdgeCS", centre, tempAxis, r1);
}
示例#12
0
// ** Temporary version
int
ClpPdco::pdco( ClpPdcoBase * stuff, Options &options, Info &info, Outfo &outfo)
{
//    D1, D2 are positive-definite diagonal matrices defined from d1, d2.
//           In particular, d2 indicates the accuracy required for
//           satisfying each row of Ax = b.
//
// D1 and D2 (via d1 and d2) provide primal and dual regularization
// respectively.  They ensure that the primal and dual solutions
// (x,r) and (y,z) are unique and bounded.
//
// A scalar d1 is equivalent to d1 = ones(n,1), D1 = diag(d1).
// A scalar d2 is equivalent to d2 = ones(m,1), D2 = diag(d2).
// Typically, d1 = d2 = 1e-4.
// These values perturb phi(x) only slightly  (by about 1e-8) and request
// that A*x = b be satisfied quite accurately (to about 1e-8).
// Set d1 = 1e-4, d2 = 1 for least-squares problems with bound constraints.
// The problem is then
//
//    minimize    phi(x) + 1/2 norm(d1*x)^2 + 1/2 norm(A*x - b)^2
//    subject to  bl <= x <= bu.
//
// More generally, d1 and d2 may be n and m vectors containing any positive
// values (preferably not too small, and typically no larger than 1).
// Bigger elements of d1 and d2 improve the stability of the solver.
//
// At an optimal solution, if x(j) is on its lower or upper bound,
// the corresponding z(j) is positive or negative respectively.
// If x(j) is between its bounds, z(j) = 0.
// If bl(j) = bu(j), x(j) is fixed at that value and z(j) may have
// either sign.
//
// Also, r and y satisfy r = D2 y, so that Ax + D2^2 y = b.
// Thus if d2(i) = 1e-4, the i-th row of Ax = b will be satisfied to
// approximately 1e-8.  This determines how large d2(i) can safely be.
//
//
// EXTERNAL FUNCTIONS:
// options         = pdcoSet;                  provided with pdco.m
// [obj,grad,hess] = pdObj( x );               provided by user
//               y = pdMat( name,mode,m,n,x ); provided by user if pdMat
//                                             is a string, not a matrix
//
// INPUT ARGUMENTS:
// pdObj      is a string containing the name of a function pdObj.m
//            or a function_handle for such a function
//            such that [obj,grad,hess] = pdObj(x) defines
//            obj  = phi(x)              : a scalar,
//            grad = gradient of phi(x)  : an n-vector,
//            hess = diag(Hessian of phi): an n-vector.
//         Examples:
//            If phi(x) is the linear function c"x, pdObj should return
//               [obj,grad,hess] = [c"*x, c, zeros(n,1)].
//            If phi(x) is the entropy function E(x) = sum x(j) log x(j),
//               [obj,grad,hess] = [E(x), log(x)+1, 1./x].
// pdMat      may be an ifexplicit m x n matrix A (preferably sparse!),
//            or a string containing the name of a function pdMat.m
//            or a function_handle for such a function
//            such that y = pdMat( name,mode,m,n,x )
//            returns   y = A*x (mode=1)  or  y = A"*x (mode=2).
//            The input parameter "name" will be the string pdMat.
// b          is an m-vector.
// bl         is an n-vector of lower bounds.  Non-existent bounds
//            may be represented by bl(j) = -Inf or bl(j) <= -1e+20.
// bu         is an n-vector of upper bounds.  Non-existent bounds
//            may be represented by bu(j) =  Inf or bu(j) >=  1e+20.
// d1, d2     may be positive scalars or positive vectors (see above).
// options    is a structure that may be set and altered by pdcoSet
//            (type help pdcoSet).
// x0, y0, z0 provide an initial solution.
// xsize, zsize are estimates of the biggest x and z at the solution.
//            They are used to scale (x,y,z).  Good estimates
//            should improve the performance of the barrier method.
//
//
// OUTPUT ARGUMENTS:
// x          is the primal solution.
// y          is the dual solution associated with Ax + D2 r = b.
// z          is the dual solution associated with bl <= x <= bu.
// inform = 0 if a solution is found;
//        = 1 if too many iterations were required;
//        = 2 if the linesearch failed too often.
// PDitns     is the number of Primal-Dual Barrier iterations required.
// CGitns     is the number of Conjugate-Gradient  iterations required
//            if an iterative solver is used (LSQR).
// time       is the cpu time used.
//----------------------------------------------------------------------

// PRIVATE FUNCTIONS:
//    pdxxxbounds
//    pdxxxdistrib
//    pdxxxlsqr
//    pdxxxlsqrmat
//    pdxxxmat
//    pdxxxmerit
//    pdxxxresid1
//    pdxxxresid2
//    pdxxxstep
//
// GLOBAL VARIABLES:
//    global pdDDD1 pdDDD2 pdDDD3
//
//
// NOTES:
// The matrix A should be reasonably well scaled: norm(A,inf) =~ 1.
// The vector b and objective phi(x) may be of any size, but ensure that
// xsize and zsize are reasonably close to norm(x,inf) and norm(z,inf)
// at the solution.
//
// The files defining pdObj  and pdMat
// must not be called Fname.m or Aname.m!!
//
//
// AUTHOR:
//    Michael Saunders, Systems Optimization Laboratory (SOL),
//    Stanford University, Stanford, California, USA.
//    [email protected]
//
// CONTRIBUTORS:
//    Byunggyoo Kim, SOL, Stanford University.
//    [email protected]
//
// DEVELOPMENT:
// 20 Jun 1997: Original version of pdsco.m derived from pdlp0.m.
// 29 Sep 2002: Original version of pdco.m  derived from pdsco.m.
//              Introduced D1, D2 in place of gamma*I, delta*I
//              and allowed for general bounds bl <= x <= bu.
// 06 Oct 2002: Allowed for fixed variabes: bl(j) = bu(j) for any j.
// 15 Oct 2002: Eliminated some work vectors (since m, n might be LARGE).
//              Modularized residuals, linesearch
// 16 Oct 2002: pdxxx..., pdDDD... names rationalized.
//              pdAAA eliminated (global copy of A).
//              Aname is now used directly as an ifexplicit A or a function.
//              NOTE: If Aname is a function, it now has an extra parameter.
// 23 Oct 2002: Fname and Aname can now be function handles.
// 01 Nov 2002: Bug fixed in feval in pdxxxmat.
//-----------------------------------------------------------------------

//  global pdDDD1 pdDDD2 pdDDD3
     double inf = 1.0e30;
     double eps = 1.0e-15;
     double atolold = -1.0, r3ratio = -1.0, Pinf, Dinf, Cinf, Cinf0;

     printf("\n   --------------------------------------------------------");
     printf("\n   pdco.m                            Version of 01 Nov 2002");
     printf("\n   Primal-dual barrier method to minimize a convex function");
     printf("\n   subject to linear constraints Ax + r = b,  bl <= x <= bu");
     printf("\n   --------------------------------------------------------\n");

     int m = numberRows_;
     int n = numberColumns_;
     bool ifexplicit = true;

     CoinDenseVector<double> b(m, rhs_);
     CoinDenseVector<double> x(n, x_);
     CoinDenseVector<double> y(m, y_);
     CoinDenseVector<double> z(n, dj_);
     //delete old arrays
     delete [] rhs_;
     delete [] x_;
     delete [] y_;
     delete [] dj_;
     rhs_ = NULL;
     x_ = NULL;
     y_ = NULL;
     dj_ = NULL;

     // Save stuff so available elsewhere
     pdcoStuff_ = stuff;

     double normb  = b.infNorm();
     double normx0 = x.infNorm();
     double normy0 = y.infNorm();
     double normz0 = z.infNorm();

     printf("\nmax |b | = %8g     max |x0| = %8g", normb , normx0);
     printf(                "      xsize   = %8g", xsize_);
     printf("\nmax |y0| = %8g     max |z0| = %8g", normy0, normz0);
     printf(                "      zsize   = %8g", zsize_);

     //---------------------------------------------------------------------
     // Initialize.
     //---------------------------------------------------------------------
     //true   = 1;
     //false  = 0;
     //zn     = zeros(n,1);
     //int nb     = n + m;
     int CGitns = 0;
     int inform = 0;
     //---------------------------------------------------------------------
     //  Only allow scalar d1, d2 for now
     //---------------------------------------------------------------------
     /*
     if (d1_->size()==1)
         d1_->resize(n, d1_->getElements()[0]);  // Allow scalar d1, d2
     if (d2_->size()==1)
         d2->resize(m, d2->getElements()[0]);  // to mean dk * unit vector
      */
     assert (stuff->sizeD1() == 1);
     double d1 = stuff->getD1();
     double d2 = stuff->getD2();

     //---------------------------------------------------------------------
     // Grab input options.
     //---------------------------------------------------------------------
     int  maxitn    = options.MaxIter;
     double featol    = options.FeaTol;
     double opttol    = options.OptTol;
     double steptol   = options.StepTol;
     int  stepSame  = 1;  /* options.StepSame;   // 1 means stepx == stepz */
     double x0min     = options.x0min;
     double z0min     = options.z0min;
     double mu0       = options.mu0;
     int  LSproblem = options.LSproblem;  // See below
     int  LSmethod  = options.LSmethod;   // 1=Cholesky    2=QR    3=LSQR
     int  itnlim    = options.LSQRMaxIter * CoinMin(m, n);
     double atol1     = options.LSQRatol1;  // Initial  atol
     double atol2     = options.LSQRatol2;  // Smallest atol,unless atol1 is smaller
     double conlim    = options.LSQRconlim;
     //int  wait      = options.wait;

     // LSproblem:
     //  1 = dy          2 = dy shifted, DLS
     // 11 = s          12 =  s shifted, DLS    (dx = Ds)
     // 21 = dx
     // 31 = 3x3 system, symmetrized by Z^{1/2}
     // 32 = 2x2 system, symmetrized by X^{1/2}

     //---------------------------------------------------------------------
     // Set other parameters.
     //---------------------------------------------------------------------
     int  kminor    = 0;      // 1 stops after each iteration
     double eta       = 1e-4;   // Linesearch tolerance for "sufficient descent"
     double maxf      = 10;     // Linesearch backtrack limit (function evaluations)
     double maxfail   = 1;      // Linesearch failure limit (consecutive iterations)
     double bigcenter = 1e+3;   // mu is reduced if center < bigcenter.

     // Parameters for LSQR.
     double atolmin   = eps;    // Smallest atol if linesearch back-tracks
     double btol      = 0;      // Should be small (zero is ok)
     double show      = false;  // Controls lsqr iteration log
     /*
     double gamma     = d1->infNorm();
     double delta     = d2->infNorm();
     */
     double gamma = d1;
     double delta = d2;

     printf("\n\nx0min    = %8g     featol   = %8.1e", x0min, featol);
     printf(                  "      d1max   = %8.1e", gamma);
     printf(  "\nz0min    = %8g     opttol   = %8.1e", z0min, opttol);
     printf(                  "      d2max   = %8.1e", delta);
     printf(  "\nmu0      = %8.1e     steptol  = %8g", mu0  , steptol);
     printf(                  "     bigcenter= %8g"  , bigcenter);

     printf("\n\nLSQR:");
     printf("\natol1    = %8.1e     atol2    = %8.1e", atol1 , atol2 );
     printf(                  "      btol    = %8.1e", btol );
     printf("\nconlim   = %8.1e     itnlim   = %8d"  , conlim, itnlim);
     printf(                  "      show    = %8g"  , show );

// LSmethod  = 3;  ////// Hardwire LSQR
// LSproblem = 1;  ////// and LS problem defining "dy".
     /*
       if wait
         printf("\n\nReview parameters... then type "return"\n")
         keyboard
       end
     */
     if (eta < 0)
          printf("\n\nLinesearch disabled by eta < 0");

     //---------------------------------------------------------------------
     // All parameters have now been set.
     //---------------------------------------------------------------------
     double time    = CoinCpuTime();
     //bool useChol = (LSmethod == 1);
     //bool useQR   = (LSmethod == 2);
     bool direct  = (LSmethod <= 2 && ifexplicit);
     char solver[7];
     strncpy(solver, "  LSQR", 7);

     //---------------------------------------------------------------------
     // Categorize bounds and allow for fixed variables by modifying b.
     //---------------------------------------------------------------------

     int nlow, nupp, nfix;
     int *bptrs[3] = {0};
     getBoundTypes(&nlow, &nupp, &nfix, bptrs );
     int *low = bptrs[0];
     int *upp = bptrs[1];
     int *fix = bptrs[2];

     int nU = n;
     if (nupp == 0) nU = 1;  //Make dummy vectors if no Upper bounds

     //---------------------------------------------------------------------
     //  Get pointers to local copy of model bounds
     //---------------------------------------------------------------------

     CoinDenseVector<double> bl(n, columnLower_);
     double *bl_elts = bl.getElements();
     CoinDenseVector<double> bu(nU, columnUpper_);  // this is dummy if no UB
     double *bu_elts = bu.getElements();

     CoinDenseVector<double> r1(m, 0.0);
     double *r1_elts = r1.getElements();
     CoinDenseVector<double> x1(n, 0.0);
     double *x1_elts = x1.getElements();

     if (nfix > 0) {
          for (int k = 0; k < nfix; k++)
               x1_elts[fix[k]] = bl[fix[k]];
          matVecMult(1, r1, x1);
          b = b - r1;
          // At some stage, might want to look at normfix = norm(r1,inf);
     }

     //---------------------------------------------------------------------
     // Scale the input data.
     // The scaled variables are
     //    xbar     = x/beta,
     //    ybar     = y/zeta,
     //    zbar     = z/zeta.
     // Define
     //    theta    = beta*zeta;
     // The scaled function is
     //    phibar   = ( 1   /theta) fbar(beta*xbar),
     //    gradient = (beta /theta) grad,
     //    Hessian  = (beta2/theta) hess.
     //---------------------------------------------------------------------
     double beta = xsize_;
     if (beta == 0) beta = 1; // beta scales b, x.
     double zeta = zsize_;
     if (zeta == 0) zeta = 1; // zeta scales y, z.
     double theta  = beta * zeta;                          // theta scales obj.
     // (theta could be anything, but theta = beta*zeta makes
     // scaled grad = grad/zeta = 1 approximately if zeta is chosen right.)

     for (int k = 0; k < nlow; k++)
          bl_elts[low[k]] = bl_elts[low[k]] / beta;
     for (int k = 0; k < nupp; k++)
          bu_elts[upp[k]] = bu_elts[upp[k]] / beta;
     d1     = d1 * ( beta / sqrt(theta) );
     d2     = d2 * ( sqrt(theta) / beta );

     double beta2  = beta * beta;
     b.scale( (1.0 / beta) );
     y.scale( (1.0 / zeta) );
     x.scale( (1.0 / beta) );
     z.scale( (1.0 / zeta) );

     //---------------------------------------------------------------------
     // Initialize vectors that are not fully used if bounds are missing.
     //---------------------------------------------------------------------
     CoinDenseVector<double> rL(n, 0.0);
     CoinDenseVector<double> cL(n, 0.0);
     CoinDenseVector<double> z1(n, 0.0);
     CoinDenseVector<double> dx1(n, 0.0);
     CoinDenseVector<double> dz1(n, 0.0);
     CoinDenseVector<double> r2(n, 0.0);

     // Assign upper bd regions (dummy if no UBs)

     CoinDenseVector<double> rU(nU, 0.0);
     CoinDenseVector<double> cU(nU, 0.0);
     CoinDenseVector<double> x2(nU, 0.0);
     CoinDenseVector<double> z2(nU, 0.0);
     CoinDenseVector<double> dx2(nU, 0.0);
     CoinDenseVector<double> dz2(nU, 0.0);

     //---------------------------------------------------------------------
     // Initialize x, y, z, objective, etc.
     //---------------------------------------------------------------------
     CoinDenseVector<double> dx(n, 0.0);
     CoinDenseVector<double> dy(m, 0.0);
     CoinDenseVector<double> Pr(m);
     CoinDenseVector<double> D(n);
     double *D_elts = D.getElements();
     CoinDenseVector<double> w(n);
     double *w_elts = w.getElements();
     CoinDenseVector<double> rhs(m + n);


     //---------------------------------------------------------------------
     // Pull out the element array pointers for efficiency
     //---------------------------------------------------------------------
     double *x_elts  = x.getElements();
     double *x2_elts = x2.getElements();
     double *z_elts  = z.getElements();
     double *z1_elts = z1.getElements();
     double *z2_elts = z2.getElements();

     for (int k = 0; k < nlow; k++) {
          x_elts[low[k]]  = CoinMax( x_elts[low[k]], bl[low[k]]);
          x1_elts[low[k]] = CoinMax( x_elts[low[k]] - bl[low[k]], x0min  );
          z1_elts[low[k]] = CoinMax( z_elts[low[k]], z0min  );
     }
     for (int k = 0; k < nupp; k++) {
          x_elts[upp[k]]  = CoinMin( x_elts[upp[k]], bu[upp[k]]);
          x2_elts[upp[k]] = CoinMax(bu[upp[k]] -  x_elts[upp[k]], x0min  );
          z2_elts[upp[k]] = CoinMax(-z_elts[upp[k]], z0min  );
     }
     //////////////////// Assume hessian is diagonal. //////////////////////

//  [obj,grad,hess] = feval( Fname, (x*beta) );
     x.scale(beta);
     double obj = getObj(x);
     CoinDenseVector<double> grad(n);
     getGrad(x, grad);
     CoinDenseVector<double> H(n);
     getHessian(x , H);
     x.scale((1.0 / beta));

     //double * g_elts = grad.getElements();
     double * H_elts = H.getElements();

     obj /= theta;                       // Scaled obj.
     grad = grad * (beta / theta) + (d1 * d1) * x; // grad includes x regularization.
     H  = H * (beta2 / theta) + (d1 * d1)      ; // H    includes x regularization.


     /*---------------------------------------------------------------------
     // Compute primal and dual residuals:
     // r1 =  b - Aprod(x) - d2*d2*y;
     // r2 =  grad - Atprod(y) + z2 - z1;
     //  rL =  bl - x + x1;
     //  rU =  x + x2 - bu; */
     //---------------------------------------------------------------------
     //  [r1,r2,rL,rU,Pinf,Dinf] = ...
     //      pdxxxresid1( Aname,fix,low,upp, ...
     //                   b,bl,bu,d1,d2,grad,rL,rU,x,x1,x2,y,z1,z2 );
     pdxxxresid1( this, nlow, nupp, nfix, low, upp, fix,
                  b, bl_elts, bu_elts, d1, d2, grad, rL, rU, x, x1, x2, y, z1, z2,
                  r1, r2, &Pinf, &Dinf);
     //---------------------------------------------------------------------
     // Initialize mu and complementarity residuals:
     //    cL   = mu*e - X1*z1.
     //    cU   = mu*e - X2*z2.
     //
     // 25 Jan 2001: Now that b and obj are scaled (and hence x,y,z),
     //              we should be able to use mufirst = mu0 (absolute value).
     //              0.1 worked poorly on StarTest1 with x0min = z0min = 0.1.
     // 29 Jan 2001: We might as well use mu0 = x0min * z0min;
     //              so that most variables are centered after a warm start.
     // 29 Sep 2002: Use mufirst = mu0*(x0min * z0min),
     //              regarding mu0 as a scaling of the initial center.
     //---------------------------------------------------------------------
     //  double mufirst = mu0*(x0min * z0min);
     double mufirst = mu0;   // revert to absolute value
     double mulast  = 0.1 * opttol;
     mulast  = CoinMin( mulast, mufirst );
     double mu      = mufirst;
     double center,  fmerit;
     pdxxxresid2( mu, nlow, nupp, low, upp, cL, cU, x1, x2,
                  z1, z2, &center, &Cinf, &Cinf0 );
     fmerit = pdxxxmerit(nlow, nupp, low, upp, r1, r2, rL, rU, cL, cU );

     // Initialize other things.

     bool  precon   = true;
     double PDitns    = 0;
     //bool converged = false;
     double atol      = atol1;
     atol2     = CoinMax( atol2, atolmin );
     atolmin   = atol2;
     //  pdDDD2    = d2;    // Global vector for diagonal matrix D2

     //  Iteration log.

     int nf      = 0;
     int itncg   = 0;
     int nfail   = 0;

     printf("\n\nItn   mu   stepx   stepz  Pinf  Dinf");
     printf("  Cinf   Objective    nf  center");
     if (direct) {
          printf("\n");
     } else {
          printf("  atol   solver   Inexact\n");
     }

     double regx = (d1 * x).twoNorm();
     double regy = (d2 * y).twoNorm();
     //  regterm = twoNorm(d1.*x)^2  +  norm(d2.*y)^2;
     double regterm = regx * regx + regy * regy;
     double objreg  = obj  +  0.5 * regterm;
     double objtrue = objreg * theta;

     printf("\n%3g                     ", PDitns        );
     printf("%6.1f%6.1f" , log10(Pinf ), log10(Dinf));
     printf("%6.1f%15.7e", log10(Cinf0), objtrue    );
     printf("   %8.1f\n"   , center                   );
     /*
     if kminor
       printf("\n\nStart of first minor itn...\n");
       keyboard
     end
     */
     //---------------------------------------------------------------------
     // Main loop.
     //---------------------------------------------------------------------
     // Lsqr
     ClpLsqr  thisLsqr(this);
     //  while (converged) {
     while(PDitns < maxitn) {
          PDitns = PDitns + 1;

          // 31 Jan 2001: Set atol according to progress, a la Inexact Newton.
          // 07 Feb 2001: 0.1 not small enough for Satellite problem.  Try 0.01.
          // 25 Apr 2001: 0.01 seems wasteful for Star problem.
          //              Now that starting conditions are better, go back to 0.1.

          double r3norm = CoinMax(Pinf,   CoinMax(Dinf,  Cinf));
          atol   = CoinMin(atol,  r3norm * 0.1);
          atol   = CoinMax(atol,  atolmin   );
          info.r3norm = r3norm;

          //-------------------------------------------------------------------
          //  Define a damped Newton iteration for solving f = 0,
          //  keeping  x1, x2, z1, z2 > 0.  We eliminate dx1, dx2, dz1, dz2
          //  to obtain the system
          //
          //     [-H2  A"  ] [ dx ] = [ w ],   H2 = H + D1^2 + X1inv Z1 + X2inv Z2,
          //     [ A   D2^2] [ dy ] = [ r1]    w  = r2 - X1inv(cL + Z1 rL)
          //                                           + X2inv(cU + Z2 rU),
          //
          //  which is equivalent to the least-squares problem
          //
          //     min || [ D A"]dy  -  [  D w   ] ||,   D = H2^{-1/2}.         (*)
          //         || [  D2 ]       [D2inv r1] ||
          //-------------------------------------------------------------------
          for (int k = 0; k < nlow; k++)
               H_elts[low[k]]  = H_elts[low[k]] + z1[low[k]] / x1[low[k]];
          for (int k = 0; k < nupp; k++)
               H[upp[k]]  = H[upp[k]] + z2[upp[k]] / x2[upp[k]];
          w = r2;
          for (int k = 0; k < nlow; k++)
               w[low[k]]  = w[low[k]] - (cL[low[k]] + z1[low[k]] * rL[low[k]]) / x1[low[k]];
          for (int k = 0; k < nupp; k++)
               w[upp[k]]  = w[upp[k]] + (cU[upp[k]] + z2[upp[k]] * rU[upp[k]]) / x2[upp[k]];

          if (LSproblem == 1) {
               //-----------------------------------------------------------------
               //  Solve (*) for dy.
               //-----------------------------------------------------------------
               H      = 1.0 / H;  // H is now Hinv (NOTE!)
               for (int k = 0; k < nfix; k++)
                    H[fix[k]] = 0;
               for (int k = 0; k < n; k++)
                    D_elts[k] = sqrt(H_elts[k]);
               thisLsqr.borrowDiag1(D_elts);
               thisLsqr.diag2_ = d2;

               if (direct) {
                    // Omit direct option for now
               } else {// Iterative solve using LSQR.
                    //rhs     = [ D.*w; r1./d2 ];
                    for (int k = 0; k < n; k++)
                         rhs[k] = D_elts[k] * w_elts[k];
                    for (int k = 0; k < m; k++)
                         rhs[n+k] = r1_elts[k] * (1.0 / d2);
                    double damp    = 0;

                    if (precon) {   // Construct diagonal preconditioner for LSQR
                         matPrecon(d2, Pr, D);
                    }
                    /*
                    	rw(7)        = precon;
                            info.atolmin = atolmin;
                            info.r3norm  = fmerit;  // Must be the 2-norm here.

                            [ dy, istop, itncg, outfo ] = ...
                       pdxxxlsqr( nb,m,"pdxxxlsqrmat",Aname,rw,rhs,damp, ...
                                  atol,btol,conlim,itnlim,show,info );


                    	thisLsqr.input->rhs_vec = &rhs;
                    	thisLsqr.input->sol_vec = &dy;
                    	thisLsqr.input->rel_mat_err = atol;
                    	thisLsqr.do_lsqr(this);
                    	*/
                    //  New version of lsqr

                    int istop;
                    dy.clear();
                    show = false;
                    info.atolmin = atolmin;
                    info.r3norm  = fmerit;  // Must be the 2-norm here.

                    thisLsqr.do_lsqr( rhs, damp, atol, btol, conlim, itnlim,
                                      show, info, dy , &istop, &itncg, &outfo, precon, Pr);
                    if (precon)
                         dy = dy * Pr;

                    if (!precon && itncg > 999999)
                         precon = true;

                    if (istop == 3  ||  istop == 7 )  // conlim or itnlim
                         printf("\n    LSQR stopped early:  istop = //%d", istop);


                    atolold   = outfo.atolold;
                    atol      = outfo.atolnew;
                    r3ratio   = outfo.r3ratio;
               }// LSproblem 1

               //      grad      = pdxxxmat( Aname,2,m,n,dy );   // grad = A"dy
               grad.clear();
               matVecMult(2, grad, dy);
               for (int k = 0; k < nfix; k++)
                    grad[fix[k]] = 0;                            // grad is a work vector
               dx = H * (grad - w);

          } else {
               perror( "This LSproblem not yet implemented\n" );
          }
          //-------------------------------------------------------------------

          CGitns += itncg;

          //-------------------------------------------------------------------
          // dx and dy are now known.  Get dx1, dx2, dz1, dz2.
          //-------------------------------------------------------------------
          for (int k = 0; k < nlow; k++) {
               dx1[low[k]] = - rL[low[k]] + dx[low[k]];
               dz1[low[k]] =  (cL[low[k]] - z1[low[k]] * dx1[low[k]]) / x1[low[k]];
          }
          for (int k = 0; k < nupp; k++) {
               dx2[upp[k]] = - rU[upp[k]] - dx[upp[k]];
               dz2[upp[k]] =  (cU[upp[k]] - z2[upp[k]] * dx2[upp[k]]) / x2[upp[k]];
          }
          //-------------------------------------------------------------------
          // Find the maximum step.
          //--------------------------------------------------------------------
          double stepx1 = pdxxxstep(nlow, low, x1, dx1 );
          double stepx2 = inf;
          if (nupp > 0)
               stepx2 = pdxxxstep(nupp, upp, x2, dx2 );
          double stepz1 = pdxxxstep( z1     , dz1      );
          double stepz2 = inf;
          if (nupp > 0)
               stepz2 = pdxxxstep( z2     , dz2      );
          double stepx  = CoinMin( stepx1, stepx2 );
          double stepz  = CoinMin( stepz1, stepz2 );
          stepx  = CoinMin( steptol * stepx, 1.0 );
          stepz  = CoinMin( steptol * stepz, 1.0 );
          if (stepSame) {                  // For NLPs, force same step
               stepx = CoinMin( stepx, stepz );   // (true Newton method)
               stepz = stepx;
          }

          //-------------------------------------------------------------------
          // Backtracking linesearch.
          //-------------------------------------------------------------------
          bool fail     =  true;
          nf       =  0;

          while (nf < maxf) {
               nf      = nf + 1;
               x       = x        +  stepx * dx;
               y       = y        +  stepz * dy;
               for (int k = 0; k < nlow; k++) {
                    x1[low[k]] = x1[low[k]]  +  stepx * dx1[low[k]];
                    z1[low[k]] = z1[low[k]]  +  stepz * dz1[low[k]];
               }
               for (int k = 0; k < nupp; k++) {
                    x2[upp[k]] = x2[upp[k]]  +  stepx * dx2[upp[k]];
                    z2[upp[k]] = z2[upp[k]]  +  stepz * dz2[upp[k]];
               }
               //      [obj,grad,hess] = feval( Fname, (x*beta) );
               x.scale(beta);
               obj = getObj(x);
               getGrad(x, grad);
               getHessian(x, H);
               x.scale((1.0 / beta));

               obj        /= theta;
               grad       = grad * (beta / theta)  +  d1 * d1 * x;
               H          = H * (beta2 / theta)  +  d1 * d1;

               //      [r1,r2,rL,rU,Pinf,Dinf] = ...
               pdxxxresid1( this, nlow, nupp, nfix, low, upp, fix,
                            b, bl_elts, bu_elts, d1, d2, grad, rL, rU, x, x1, x2,
                            y, z1, z2, r1, r2, &Pinf, &Dinf );
               //double center, Cinf, Cinf0;
               //      [cL,cU,center,Cinf,Cinf0] = ...
               pdxxxresid2( mu, nlow, nupp, low, upp, cL, cU, x1, x2, z1, z2,
                            &center, &Cinf, &Cinf0);
               double fmeritnew = pdxxxmerit(nlow, nupp, low, upp, r1, r2, rL, rU, cL, cU );
               double step      = CoinMin( stepx, stepz );

               if (fmeritnew <= (1 - eta * step)*fmerit) {
                    fail = false;
                    break;
               }

               // Merit function didn"t decrease.
               // Restore variables to previous values.
               // (This introduces a little error, but save lots of space.)

               x       = x        -  stepx * dx;
               y       = y        -  stepz * dy;
               for (int k = 0; k < nlow; k++) {
                    x1[low[k]] = x1[low[k]]  -  stepx * dx1[low[k]];
                    z1[low[k]] = z1[low[k]]  -  stepz * dz1[low[k]];
               }
               for (int k = 0; k < nupp; k++) {
                    x2[upp[k]] = x2[upp[k]]  -  stepx * dx2[upp[k]];
                    z2[upp[k]] = z2[upp[k]]  -  stepz * dz2[upp[k]];
               }
               // Back-track.
               // If it"s the first time,
               // make stepx and stepz the same.

               if (nf == 1 && stepx != stepz) {
                    stepx = step;
               } else if (nf < maxf) {
                    stepx = stepx / 2;
               }
               stepz = stepx;
          }

          if (fail) {
               printf("\n     Linesearch failed (nf too big)");
               nfail += 1;
          } else {
               nfail = 0;
          }

          //-------------------------------------------------------------------
          // Set convergence measures.
          //--------------------------------------------------------------------
          regx = (d1 * x).twoNorm();
          regy = (d2 * y).twoNorm();
          regterm = regx * regx + regy * regy;
          objreg  = obj  +  0.5 * regterm;
          objtrue = objreg * theta;

          bool primalfeas    = Pinf  <=  featol;
          bool dualfeas      = Dinf  <=  featol;
          bool complementary = Cinf0 <=  opttol;
          bool enough        = PDitns >=       4; // Prevent premature termination.
          bool converged     = primalfeas  &  dualfeas  &  complementary  &  enough;

          //-------------------------------------------------------------------
          // Iteration log.
          //-------------------------------------------------------------------
          char str1[100], str2[100], str3[100], str4[100], str5[100];
          sprintf(str1, "\n%3g%5.1f" , PDitns      , log10(mu)   );
          sprintf(str2, "%8.5f%8.5f" , stepx       , stepz       );
          if (stepx < 0.0001 || stepz < 0.0001) {
               sprintf(str2, " %6.1e %6.1e" , stepx       , stepz       );
          }

          sprintf(str3, "%6.1f%6.1f" , log10(Pinf) , log10(Dinf));
          sprintf(str4, "%6.1f%15.7e", log10(Cinf0), objtrue     );
          sprintf(str5, "%3d%8.1f"   , nf          , center      );
          if (center > 99999) {
               sprintf(str5, "%3d%8.1e"   , nf          , center      );
          }
          printf("%s%s%s%s%s", str1, str2, str3, str4, str5);
          if (direct) {
               // relax
          } else {
               printf(" %5.1f%7d%7.3f", log10(atolold), itncg, r3ratio);
          }
          //-------------------------------------------------------------------
          // Test for termination.
          //-------------------------------------------------------------------
          if (kminor) {
               printf( "\nStart of next minor itn...\n");
               //      keyboard;
          }

          if (converged) {
               printf("\n   Converged");
               break;
          } else if (PDitns >= maxitn) {
               printf("\n   Too many iterations");
               inform = 1;
               break;
          } else if (nfail  >= maxfail) {
               printf("\n   Too many linesearch failures");
               inform = 2;
               break;
          } else {

               // Reduce mu, and reset certain residuals.

               double stepmu  = CoinMin( stepx , stepz   );
               stepmu  = CoinMin( stepmu, steptol );
               double muold   = mu;
               mu      = mu   -  stepmu * mu;
               if (center >= bigcenter)
                    mu = muold;

               // mutrad = mu0*(sum(Xz)/n); // 24 May 1998: Traditional value, but
               // mu     = CoinMin(mu,mutrad ); // it seemed to decrease mu too much.

               mu      = CoinMax(mu, mulast); // 13 Jun 1998: No need for smaller mu.
               //      [cL,cU,center,Cinf,Cinf0] = ...
               pdxxxresid2( mu, nlow, nupp, low, upp, cL, cU, x1, x2, z1, z2,
                            &center, &Cinf, &Cinf0 );
               fmerit = pdxxxmerit( nlow, nupp, low, upp, r1, r2, rL, rU, cL, cU );

               // Reduce atol for LSQR (and SYMMLQ).
               // NOW DONE AT TOP OF LOOP.

               atolold = atol;
               // if atol > atol2
               //   atolfac = (mu/mufirst)^0.25;
               //   atol    = CoinMax( atol*atolfac, atol2 );
               // end

               // atol = CoinMin( atol, mu );     // 22 Jan 2001: a la Inexact Newton.
               // atol = CoinMin( atol, 0.5*mu ); // 30 Jan 2001: A bit tighter

               // If the linesearch took more than one function (nf > 1),
               // we assume the search direction needed more accuracy
               // (though this may be true only for LPs).
               // 12 Jun 1998: Ask for more accuracy if nf > 2.
               // 24 Nov 2000: Also if the steps are small.
               // 30 Jan 2001: Small steps might be ok with warm start.
               // 06 Feb 2001: Not necessarily.  Reinstated tests in next line.

               if (nf > 2  ||  CoinMin( stepx, stepz ) <= 0.01)
                    atol = atolold * 0.1;
          }
          //---------------------------------------------------------------------
          // End of main loop.
          //---------------------------------------------------------------------
     }


     for (int k = 0; k < nfix; k++)
          x[fix[k]] = bl[fix[k]];
     z      = z1;
     if (nupp > 0)
          z = z - z2;
     printf("\n\nmax |x| =%10.3f", x.infNorm() );
     printf("    max |y| =%10.3f", y.infNorm() );
     printf("    max |z| =%10.3f", z.infNorm() );
     printf("   scaled");

     x.scale(beta);
     y.scale(zeta);
     z.scale(zeta);   // Unscale x, y, z.

     printf(  "\nmax |x| =%10.3f", x.infNorm() );
     printf("    max |y| =%10.3f", y.infNorm() );
     printf("    max |z| =%10.3f", z.infNorm() );
     printf(" unscaled\n");

     time   = CoinCpuTime() - time;
     char str1[100], str2[100];
     sprintf(str1, "\nPDitns  =%10g", PDitns );
     sprintf(str2, "itns =%10d", CGitns );
     //  printf( [str1 " " solver str2] );
     printf("    time    =%10.1f\n", time);
     /*
     pdxxxdistrib( abs(x),abs(z) );   // Private function

     if (wait)
       keyboard;
     */
//-----------------------------------------------------------------------
// End function pdco.m
//-----------------------------------------------------------------------
     /*  printf("Solution x values:\n\n");
       for (int k=0; k<n; k++)
         printf(" %d   %e\n", k, x[k]);
     */
// Print distribution
     double thresh[9] = { 0.00000001, 0.0000001, 0.000001, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1.00001};
     int counts[9] = {0};
     for (int ij = 0; ij < n; ij++) {
          for (int j = 0; j < 9; j++) {
               if(x[ij] < thresh[j]) {
                    counts[j] += 1;
                    break;
               }
          }
     }
     printf ("Distribution of Solution Values\n");
     for (int j = 8; j > 1; j--)
          printf(" %g  to  %g %d\n", thresh[j-1], thresh[j], counts[j]);
     printf("   Less than   %g %d\n", thresh[2], counts[0]);

     return inform;
}
示例#13
0
int main(int argc, char **argv)
{
char c, *infn;
ifstream ini("\\win3\\win.ini");
ofstream fout("t.sty");
int ln= 0;
SPString w;
SPStringList l;
SPStringList ttfonts;
Assoc<SPString> repfnts("", "");  // saves font replacement names

    if(argc < 2) infn= "test.sty";
    else infn= argv[1];

    ifstream fin(infn);

    if(!ini){
        cerr << "Can't open \\win3\\win.ini" << endl;
        exit(1);
    }

    if(!fin){
        cerr << "Can't open " << infn << endl;
        exit(1);
    }

    if(!fout){
        cerr << "Can't open t.sty for write" << endl;
        exit(1);
    }

    cout << "Reading in truetype fonts" << endl;

    while(ini >> w){ // find the [fonts] section
        if(w.m("\\[fonts\\]")) break;
    }

//    cout << buf << endl;

    if(!ini.good()){ // checks all file state
        cerr << "Couldn't find [fonts] section in win.ini" << endl;
        exit(1);
    }

    // make a list of truetype fonts
    Regexp r1("^([a-zA-Z ]+) \\(([a-zA-Z ]+)\\)=");
    Regexp r2("^TrueType$");
    Regexp r3("\\[.*\\]");

    while(ini >> w){
        if(w.m(r3)) break; // found the start of another section
        if(w.m(r1, l) != 3) continue; // ignore this line
//        cout << "Font match:" << l[1] << ", " << l[2] << endl;
        if(l[2].m(r2)){
            ttfonts.push(l[1]);
        } 
    }

    cout << "ttfonts: " << endl << ttfonts << endl;
    ini.close();

    cout << "Looking for non-truetype fonts" << endl;

    SPString s, fnt, newfnt;
    SPStringList sl;
    while(fin >> s){
        ln++;
//      cout << "line " << ln << ": <" << s << ">" << endl;
        if(s.m("\\[fnt\\]")){
            fout << s << endl; // write out [fnt] line
                               // read next line which should have font in it
            if(!(fin >> s)){
                cerr << "Error reading font line " << ln << endl;
                exit(1);
            }
            ln++;
            fnt= s.split("' '").join(" "); // This trims whitespace
//          cout << "font name: <" << fnt << ">" << endl;
            if(!ttfonts.grep("^" + fnt + "$", "i")){ // not a truetype font
                int pos= s.index(fnt); // get position in string of font
                if(pos < 0){
                    cerr << "Couldn't find <" << fnt << "> in string <" << s << "> line " << ln << endl;
                    exit(1);
                }

                // See if we already know what to exchange it with
                if(repfnts.isin(fnt)) // just replace it
                    s.substr(pos, strlen(fnt)) = repfnts(fnt);
                else{ // need to ask what the new font name will be
                    do{
                        cout << "Replace font <" << fnt << "> with:"; cout.flush();
                        cin >> newfnt;
                        if(!(sl=ttfonts.grep("^" + newfnt + "$", "i"))){
                            cerr << "<" << newfnt << "> is not a valid font" << endl;
                            continue;
                        }
                    break;
                    }while(1);
                    s.substr(pos, strlen(fnt)) = sl[0]; // replace it
                    repfnts(fnt) = sl[0];  // remember for next time
                }
                fout << s << endl;
            }else{
示例#14
0
文件: Octree.cpp 项目: sdp0et/gtp
// SPLIT toSPLIT LIST OF PHANTOMTRIANGLE'S ON PLANE.
// Uses a variant of the Sutherland-Hodgman algorithm.
void splitTris( Plane plane, list<PhantomTriangle*> & toSplit, list<PhantomTriangle*> & newTris )
{
  // We create 9 pointers, but only 3 will be used.
  // Each of the 3 points a,b,c of each tri needs
  // to be classified as negative-side, +-side, or
  // ON the splitting plane.
  Vector *nS[3] ;
  Vector *pS[3] ; // ptr to the vert on the _other_ side,
  Vector *on[3] ;

  int origTris = toSplit.size() ;

  for( list<PhantomTriangle*>::iterator iter = toSplit.begin() ; iter != toSplit.end() ; )
  {
    // these are counters for how many
    // vertices so far were on what side of the plane.
    int pSide=0, nSide=0, onPlane=0 ;

    PhantomTriangle* pTri = *iter ;
    Vector* triVectors = &pTri->a ; // start here
    
    // test 3 vertices
    for( int i = 0 ; i < 3 ; i++ )
    {
      int v = plane.iSide( triVectors[i] ) ;
      //triVectors[i].print() ;
      //printf( "  v=%f\n", v ) ;
      if( v == 0 ) on[onPlane++]= &triVectors[i];
      else if( v < 0 ) nS[nSide++]= &triVectors[i];
      else pS[pSide++]= &triVectors[i] ;
    }

    ///info( "pSide=%d, nSide=%d, onPlane=%d", pSide, nSide, onPlane ) ;

    if( nSide>=1 && pSide>=1 ) // split.
    {
      // NOT keeping the winding order.  it doesn't matter anyway because
      // these are intersectable, not renderable.

      // the first ray finds the intersection between the negative side and the ps,
      Intersection i1 ;

      //---|+++
      // o |   
      // |\|--->N
      // | |\  
      // o-X-o 

      // Make a ray FROM a point on the negative side,
      // to a point on the +side of the plane
      Ray r1( *(nS[0]), *(pS[0]) ) ;
      
      // use the plane to get the intersection point
      plane.intersectsPlane( r1, &i1 ) ;
      ///pTri->tri->intersects( r1, &mi1 ) ; // use the original tri to get the 3d space intersection point

      // A vertex is on or very near the plane, so 
      // we'll split AT the vertex (cut only one edge)
      if( onPlane==1 )
      {
        // split using the VERTEX on the plane as the splitter.
        // gen 2 tris.
        // 1) nS, D, ONPLANE,
        // 2) pS, ONPLANE, D.
        PhantomTriangle *pt1 = new PhantomTriangle( *(nS[0]), i1.point, *(on[0]), pTri->tri ) ;
        PhantomTriangle *pt2 = new PhantomTriangle( *(pS[0]), *(on[0]), i1.point, pTri->tri ) ;
        if( pt1->isDegenerate() || pt2->isDegenerate() )
        {
          // This is a very important error to catch, because it happens
          // when something is terribly screwed up.
          window->addSolidDebugTri( pTri, Vector(1,0,0) ) ;
          error( "split fail." ) ;
          delete pt1 ; delete pt2 ;
          ++iter ;
          continue ;
        }
        newTris.push_back( pt1 ) ;
        newTris.push_back( pt2 ) ;
      }
      else 
      {
        // 2 points on nSide
        // We cut 2 edges.

        // if there are 2 nsides, use nS[1] and pS[0]. If 2 psides, nS[0],ps[1].

        // get the side with 2 verts on it
        Vector** sideWith2 = (pSide>nSide)?pS:nS;
        Vector** sideWith1 = (pSide<nSide)?pS:nS;
        
        // Get the second intersection point, from sideWith2[1] to sidewith1[0]
        Ray r2( *(sideWith2[1]), *(sideWith1[0]) ) ;
        Intersection i2 ;
        plane.intersectsPlane( r2, &i2 ) ;

        // 3 tris.
        //      *   
        //     / \
        //    /___\  
        //   / __/ \ 
        //  /_/     \ 
        // *---------*
        //
        // LET D be mi1.point, E mi2.point
        // 1)  sw2[0],D,E
        // 2)  sw2[0],E,sw2[1]
        // 3)  E,D,sw1[0]
        PhantomTriangle *pt1 = new PhantomTriangle( *(sideWith2[0]), i1.point, i2.point, pTri->tri ) ;
        PhantomTriangle *pt2 = new PhantomTriangle( *(sideWith2[0]), i2.point, *(sideWith2[1]), pTri->tri ) ;
        PhantomTriangle *pt3 = new PhantomTriangle( i2.point, i1.point, *(sideWith1[0]), pTri->tri ) ;
        if( pt1->isDegenerate() || pt2->isDegenerate() || pt3->isDegenerate() )
        {
          // This is a very important error to catch, because it happens
          // when something is terribly screwed up.
          window->addSolidDebugTri( pTri, Vector(1,0,0) ) ;
          error( "split fail." ) ; // split fail.
          delete pt1 ; delete pt2 ; delete pt3 ;
          ++iter ;
          continue ;
        }
        newTris.push_back( pt1 ) ;
        newTris.push_back( pt2 ) ;
        newTris.push_back( pt3 ) ;
      }

      // destroy the old PhantomTriangle that got split,
      // we don't need it anymore.
      DESTROY( *iter ) ;
      iter = toSplit.erase( iter ) ; // ADVANCES ITER
    }
    else
    {
      // Here you cannot split the polygon, either because 
      // all 3 are on one side, or one is on the plane and the
      // other 2 are on the same side.
      // I mean this is not a big deal and it is expected to happen a lot,
      // because a lot of tris you try to split will be on one side of the plane,
      // more rarely all 3 verts will be IN the plane.

      // if it does happen then like ASUS RMA you get the same triangle back.
      ///info( "Could not split the polygon, pSide=%d, nSide=%d, onPlane=%d", pSide, nSide, onPlane ) ;
      ++iter ; // advance iterator
    }
  }

  // Splits fail a lot, because this gets called 3x per division.
  ////info( "%d tris became %d tris, %d remain", origTris, newTris.size(), toSplit.size() ) ;
}
示例#15
0
int main(int argc, char *argv[]) 
{

  Pooma::initialize(argc, argv);
  Pooma::Tester tester(argc, argv);

  Interval<1> n1(1,5);
  Interval<1> n2(4,8);
  Interval<1> n3(10,20);
  Interval<2> a(n1,n2);
  Interval<3> b(n1,n2,n3);

  Range<1> r1(1,5);
  Range<1> r2(4,8,2);
  Range<1> r3(5,9,2);
  Range<1> r4(10,20,5);
  Range<2> ra(r1,r2);
  Range<2> rb(r1,r3);
  Range<3> rc(r1,r2,r3);

  tester.out() << "1: touches(" << a[0] << "," << a[1] << ") ? ";
  tester.out() << touches(a[0], a[1]) << std::endl;
  tester.check( touches(a[0], a[1]) );
  tester.out() << "0: touches(" << a[0] << "," << b[2] << ") ? ";
  tester.out() << touches(a[0], b[2]) << std::endl;
  tester.check( touches(a[0], b[2])==0);
  tester.out() << "1: touches(" << a[0] << "," << ra[0] << ") ? ";
  tester.out() << touches(a[0], ra[0]) << std::endl;
  tester.check(touches(a[0], ra[0]));
  tester.out() << "1: touches(" << ra[0] << "," << ra[1] << ") ? ";
  tester.out() << touches(ra[0], ra[1]) << std::endl;
  tester.check( touches(ra[0], ra[1]));
  tester.out() << "0: touches(" << r2 << "," << r3 << ") ? ";
  tester.out() << touches(r2, r3) << std::endl;
  tester.check( touches(r2, r3)==0);
  tester.out() << "0: touches(" << ra << "," << rb << ") ? ";
  tester.out() << touches(ra, rb) << std::endl;
  tester.check(  touches(ra, rb) ==0);
  tester.out() << "1: touches(" << rc << "," << rc << ") ? ";
  tester.out() << touches(rc, rc) << std::endl;
  tester.check( touches(rc, rc) );
  tester.out() << "------------------------------------" << std::endl;

  tester.check(" touches ", true);

  Interval<1> c1(1,10);
  Interval<1> c2(3,8);
  Interval<1> c3(5,15);
  Interval<2> ca(c1, c1);
  Interval<2> cb(c1, c2);
  Range<1>    cr1(2,20,2);
  Range<1>    cr2(4,16,4);
  Range<1>    cr3(3,15,2);
  Range<1>    cr4(5,15,5);

  tester.out() << "1: contains(" << c1 << "," << c2 << ") ? ";
  tester.out() << contains(c1,c2) << std::endl;
  tester.check(contains(c1,c2));
  tester.out() << "0: contains(" << c2 << "," << c1 << ") ? ";
  tester.out() << contains(c2,c1) << std::endl;
  tester.check(contains(c2,c1)==0);
  tester.out() << "0: contains(" << c1 << "," << c3 << ") ? ";
  tester.out() << contains(c1,c3) << std::endl;
  tester.check(contains(c1,c3)==0);
  tester.out() << "1: contains(" << ca << "," << cb << ") ? ";
  tester.out() << contains(ca,cb) << std::endl;
  tester.check(contains(ca,cb));
  tester.out() << "0: contains(" << cb << "," << ca << ") ? ";
  tester.out() << contains(cb,ca) << std::endl;
  tester.check(contains(cb,ca)==0);
  tester.out() << "1: contains(" << cr1 << "," << cr2 << ") ? ";
  tester.out() << contains(cr1,cr2) << std::endl;
  tester.check( contains(cr1,cr2));
  tester.out() << "0: contains(" << cr1 << "," << cr3 << ") ? ";
  tester.out() << contains(cr1,cr3) << std::endl;
  tester.check(contains(cr1,cr3)==0);
  tester.out() << "1: contains(" << c3 << "," << cr4 << ") ? ";
  tester.out() << contains(c3,cr4) << std::endl;
  tester.check(contains(c3,cr4));
  tester.out() << "0: contains(" << cr4 << "," << c3 << ") ? ";
  tester.out() << contains(cr4,c3) << std::endl;
  tester.check(contains(cr4,c3)==0);
  tester.out() << "------------------------------------" << std::endl;

  Interval<2> s1, s2;
  Range<2>    sr1, sr2;

  split(cb, s1, s2);
  tester.out() << "split(" << cb << ") = " << s1 << " and " << s2 << std::endl;
  tester.check(s1==Interval<2>(Interval<1>(1,5),Interval<1>(3,5)));
  tester.check(s2==Interval<2>(Interval<1>(6,10),Interval<1>(6,8)));

 

  split(rb, sr1, sr2);
  tester.out() << "split(" << rb << ") = " << sr1 << " and " << sr2 << std::endl;
  tester.check(sr1==Range<2>(Range<1>(1,2),Range<1>(5,5,2)));
  tester.check(sr2==Range<2>(Range<1>(3,5),Range<1>(7,9,2)));

  tester.out() << "------------------------------------" << std::endl;

  tester.out() << "intersect(" << cb << "," << ca << ") = ";
  tester.out() << intersect(cb,ca) << std::endl;
  tester.check(intersect(cb,ca)==Interval<2>(Interval<1>(1,10),
					     Interval<1>(3,8)));

  tester.out() << "intersect(" << rb << "," << ra << ") = ";
  tester.out() << intersect(rb,ra) << std::endl;


  Range<1> i1(1,16,3);
  Range<1> i2(17,3,-2);
  tester.out() << "intersect(" << i1 << "," << i2 << ") = ";
  tester.out() << intersect(i1,i2) << std::endl;
  tester.check( intersect(i1,i2) == Range<1>(7,14,6));

  tester.out() << "intersect(" << i2 << "," << i1 << ") = ";
  tester.out() << intersect(i2,i1) << std::endl;
  tester.check( intersect(i2,i1) == Range<1>(13,7,-6));

  tester.out() << "------------------------------------" << std::endl;

  Interval<1> eq1(1,5);
  Range<1> eq2 = -2 * eq1 + 3;
  Range<1> eq3(-8,8,4);
  Range<1> eq4 = 3 * eq1;
  Range<1> eq5 = 2 * eq1;
  Range<1> eq6 = 6 * eq1 + 1;

  tester.out() << "For " << eq1 << " --> " << eq4 << ", then " << eq3 << " --> ";
  tester.out() << equivSubset(eq1,eq4,eq3) << std::endl;

  tester.out() << "For " << eq4 << " --> " << eq6 << ", then " << eq3 << " --> ";
  tester.out() << equivSubset(eq4,eq6,eq3) << std::endl;

  tester.out() << "For " << eq1 << " --> " << eq2 << ", then " << eq3 << " --> ";
  tester.out() << equivSubset(eq1,eq2,eq3) << std::endl;

  tester.out() << "------------------------------------" << std::endl;

  NewDomain3<Interval<1>, Interval<1>, int>::SliceType_t  ba;
  //  tester.out() << "Created initial slice domain ba = " << ba << std::endl;
  ba = NewDomain3<Interval<1>, Interval<1>, int>::combineSlice(ba,eq1,eq1,7);
  tester.out() << "After taking slice, ba = " << ba << std::endl;

  int retval = tester.results("Domain Calc");
  Pooma::finalize();
  return retval;


}
int
run_main (int, ACE_TCHAR *[])
{
  ACE_START_TEST (ACE_LIB_TEXT ("Refcounted_Auto_Ptr_Test"));


  // =========================================================================
  // The following test uses the ACE_Refcounted_Auto_Ptr in a single
  // thread of control, hence we use the ACE_Null_Mutex

  ACE_DEBUG ((LM_DEBUG,
              ACE_LIB_TEXT ("(%t) performing synchronous test...\n")));

  Printer *printer1;
  ACE_NEW_RETURN (printer1,
                  Printer ("I am printer 1"),
                  -1);
  {
    ACE_Refcounted_Auto_Ptr<Printer, ACE_Null_Mutex> r(printer1);
    ACE_Refcounted_Auto_Ptr<Printer, ACE_Null_Mutex> r1(r);
    ACE_Refcounted_Auto_Ptr<Printer, ACE_Null_Mutex> r2(r);
    ACE_Refcounted_Auto_Ptr<Printer, ACE_Null_Mutex> r3(r);
    ACE_Refcounted_Auto_Ptr<Printer, ACE_Null_Mutex> r4(r);
    ACE_Refcounted_Auto_Ptr<Printer, ACE_Null_Mutex> r5 = r2;
    ACE_Refcounted_Auto_Ptr<Printer, ACE_Null_Mutex> r6 = r1;
  }
  ACE_DEBUG ((LM_DEBUG,
              ACE_LIB_TEXT ("(%t) Printer instance count is %d, expecting 0\n"),
              Printer::instance_count_));
  ACE_ASSERT (Printer::instance_count_ == 0);

#if defined (ACE_HAS_THREADS)

  // =========================================================================
  // The following test uses the ACE_Refcounted_Auto_Ptr in multiple
  // threads of control.

  ACE_DEBUG ((LM_DEBUG,
              ACE_LIB_TEXT ("(%t) performing asynchronous test...\n")));

  Scheduler *scheduler_ptr;

  // Create active objects..
  ACE_NEW_RETURN (scheduler_ptr,
                  Scheduler (),
                  -1);

  auto_ptr<Scheduler> scheduler(scheduler_ptr);

  ACE_ASSERT (scheduler->open () != -1);

  {
    ACE_NEW_RETURN (printer1,
                    Printer ("I am printer 2"),
                    -1);

    Printer_var r (printer1);

    for (int i = 0; i < n_loops; i++)
      // Spawn off the methods, which run in a separate thread as
      // active object invocations.
      scheduler->print (r);
  }

  // Close things down.
  scheduler->end ();

  scheduler->wait ();

  ACE_DEBUG ((LM_DEBUG,
              ACE_LIB_TEXT ("(%t) Printer instance count is %d, expecting 0\n"),
              Printer::instance_count_));
  ACE_ASSERT (Printer::instance_count_ == 0);

#endif /* ACE_HAS_THREADS */
  ACE_END_TEST;

  return 0;
}
示例#17
0
文件: md5.c 项目: vni/programming
static void round1(uint32 d[4], uint32 *X)
{
#define F(X,Y,Z) (((X) & (Y)) | ((~(X)) & (Z)))
#define r1(a,b,c,d,k,s,t) ((a) = (b) + ROTATE((a) + F((b),(c),(d)) + X[(k)] + (t), (s)))
	/* [abcd k s i] ::: a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s) */

	/* [ABCD  0  7  1]  [DABC  1 12  2]  [CDAB  2 17  3]  [BCDA  3 22  4] */
	r1(d[0], d[1], d[2], d[3],  0,  7, 0xd76aa478);
	r1(d[3], d[0], d[1], d[2],  1, 12, 0xe8c7b756);
	r1(d[2], d[3], d[0], d[1],  2, 17, 0x242070db);
	r1(d[1], d[2], d[3], d[0],  3, 22, 0xc1bdceee);

	/* [ABCD  4  7  5]  [DABC  5 12  6]  [CDAB  6 17  7]  [BCDA  7 22  8] */
	r1(d[0], d[1], d[2], d[3],  4,  7, 0xf57c0faf);
	r1(d[3], d[0], d[1], d[2],  5, 12, 0x4787c62a);
	r1(d[2], d[3], d[0], d[1],  6, 17, 0xa8304613);
	r1(d[1], d[2], d[3], d[0],  7, 22, 0xfd469501);

	/* [ABCD  8  7  9]  [DABC  9 12 10]  [CDAB 10 17 11]  [BCDA 11 22 12] */
	r1(d[0], d[1], d[2], d[3],  8,  7, 0x698098d8);
	r1(d[3], d[0], d[1], d[2],  9, 12, 0x8b44f7af);
	r1(d[2], d[3], d[0], d[1], 10, 17, 0xffff5bb1);
	r1(d[1], d[2], d[3], d[0], 11, 22, 0x895cd7be);

	/* [ABCD 12  7 13]  [DABC 13 12 14]  [CDAB 14 17 15]  [BCDA 15 22 16] */
	r1(d[0], d[1], d[2], d[3], 12,  7, 0x6b901122);
	r1(d[3], d[0], d[1], d[2], 13, 12, 0xfd987193);
	r1(d[2], d[3], d[0], d[1], 14, 17, 0xa679438e);
	r1(d[1], d[2], d[3], d[0], 15, 22, 0x49b40821);
#undef r1
#undef F
}
示例#18
0
void TextPoint::Draw( ODDC& dc, wxPoint *rpn )
{
    if( !m_bIsVisible )
        return;
    
    if( m_iDisplayTextWhen == ID_TEXTPOINT_DISPLAY_TEXT_SHOW_ALWAYS || 
        ( m_iDisplayTextWhen == ID_TEXTPOINT_DISPLAY_TEXT_SHOW_ON_ROLLOVER && m_bShowDisplayTextOnRollover)  ) {
        if( m_TextPointText.Len() > 0 ) {
            CalculateTextExtents();
            int teX, teY;
            int scalefactor = round(g_ocpn_draw_pi->m_chart_scale / m_natural_scale);
            
            if(m_natural_scale > (g_ocpn_draw_pi->m_chart_scale / 2) ) {
                teX = m_TextExtents.x;
                teY = m_TextExtents.y;
            } else {
                teX = m_TextExtents.x / scalefactor;
                teY = m_TextExtents.y / scalefactor;
            }
            
            if(teX > 0 && teY > 0 && scalefactor <= 8) {
                switch ( m_iTextPosition )
                {
                    case ID_TEXT_TOP:
                        m_TextLocationOffsetX = g_iTextTopOffsetX;
                        m_TextLocationOffsetY = g_iTextTopOffsetY - teY;
                        break;
                    case ID_TEXT_CENTRE_TOP:
                        m_TextLocationOffsetX = g_iTextTopOffsetX - (teX / 2);
                        m_TextLocationOffsetY = g_iTextTopOffsetY - teY;
                        break;
                    case ID_TEXT_BOTTOM:
                        m_TextLocationOffsetX = g_iTextBottomOffsetX;
                        m_TextLocationOffsetY = g_iTextBottomOffsetY;
                        if(m_bShowName) m_TextLocationOffsetY += g_iTextBottomNameExtraOffsetY;
                        break;
                    case ID_TEXT_CENTRE_BOTTOM:
                        m_TextLocationOffsetX = g_iTextBottomOffsetX - (teX / 2);
                        m_TextLocationOffsetY = g_iTextBottomOffsetY;
                        break;
                    case ID_TEXT_CENTRE:
                        m_TextLocationOffsetX = g_iTextCentreOffsetX - (teX / 2);
                        m_TextLocationOffsetY = g_iTextCentreOffsetY - (teY / 2);
                        break;
                    case ID_TEXT_RIGHT:
                        m_TextLocationOffsetX = g_iTextRightOffsetX;
                        m_TextLocationOffsetY = g_iTextRightOffsetY;
                        break;
                    case ID_TEXT_LEFT:
                        m_TextLocationOffsetX = g_iTextLeftOffsetX - teX;
                        m_TextLocationOffsetY = g_iTextLeftOffsetY;
                        break;
                }
                int sx2 = m_pbmIcon->GetWidth() / 2;
                int sy2 = m_pbmIcon->GetHeight() / 2;
                
                //    Calculate the mark drawing extents
                wxPoint r;
                GetCanvasPixLL( g_pivp, &r,  m_lat, m_lon);    
                wxRect r1( r.x - sx2, r.y - sy2, sx2 * 2, sy2 * 2 );           // the bitmap extents
                if( m_DisplayTextFont.IsOk() ) {
                    // Added to help with display of text (stops end clipping)
                    teX += 20;
                    wxRect r2( r.x + m_TextLocationOffsetX, r.y + m_TextLocationOffsetY, teX,
                            teY );
                    r1.Union( r2 );
            
                    r.x = r.x + m_TextLocationOffsetX;
                    r.y = r.y + m_TextLocationOffsetY;
                
                    dc.SetFont( m_DisplayTextFont );
                    dc.SetTextForeground( m_colourTextColour );
                    g_ocpn_draw_pi->AlphaBlending( dc, r.x, r.y, r2.width, r2.height, 6.0, m_colourTextBackgroundColour, m_iBackgroundTransparency );
                    if(m_natural_scale > (g_ocpn_draw_pi->m_chart_scale / 2) )
                        dc.DrawText( m_TextPointText, r.x + 10, r.y );
                    else 
                        dc.DrawText( wxT(" "), r.x + 10, r.y );
                }
            }
        }
    }
    ODPoint::Draw( dc, rpn );
}
示例#19
0
static void kbic_read_block( PIA *pi, char * buf, int count )

{   int     k, a, b;

    switch (pi->mode) {

    case 0:
        w0(0x98);
        w2(4);
        w2(6);
        w2(4);
        for (k=0; k<count/2; k++) {
            w2(1);
            w0(8);
            a = r1();
            w0(0x28);
            b = r1();
            buf[2*k]   = j44(a,b);
            w2(5);
            b = r1();
            w0(8);
            a = r1();
            buf[2*k+1] = j44(a,b);
            w2(4);
        }
        break;

    case 1:
        w0(0xb8);
        w2(4);
        w2(6);
        w2(4);
        for (k=0; k<count/4; k++) {
            w0(0xb8);
            w2(4);
            w2(5);
            w0(8);
            buf[4*k]   = j53(r12w());
            w0(0xb8);
            buf[4*k+1] = j53(r12w());
            w2(4);
            w2(5);
            buf[4*k+3] = j53(r12w());
            w0(8);
            buf[4*k+2] = j53(r12w());
        }
        w2(4);
        break;

    case 2:
        w0(0x88);
        w2(4);
        w2(6);
        w2(4);
        for (k=0; k<count/2; k++) {
            w2(0xa0);
            w2(0xa1);
            buf[2*k] = r0();
            w2(0xa5);
            buf[2*k+1] = r0();
        }
        w2(4);
        break;

    case 3:
        w0(0xa0);
        w2(4);
        w2(6);
        w2(4);
        w3(0);
        for (k=0; k<count; k++) buf[k] = r4();
        w2(4);
        w2(0);
        w2(4);
        break;

    case 4:
        w0(0xa0);
        w2(4);
        w2(6);
        w2(4);
        w3(0);
        for (k=0; k<count/2; k++) ((u16 *)buf)[k] = r4w();
        w2(4);
        w2(0);
        w2(4);
        break;

    case 5:
        w0(0xa0);
        w2(4);
        w2(6);
        w2(4);
        w3(0);
        for (k=0; k<count/4; k++) ((u32 *)buf)[k] = r4l();
        w2(4);
        w2(0);
        w2(4);
        break;


    }
}
示例#20
0
void TextPoint::DrawGL( PlugIn_ViewPort &pivp )
{
    if( !m_bIsVisible )
        return;
    
    if( m_iDisplayTextWhen == ID_TEXTPOINT_DISPLAY_TEXT_SHOW_ALWAYS || m_iDisplayTextWhen == ID_TEXTPOINT_DISPLAY_TEXT_SHOW_ON_ROLLOVER ) {
        if( m_TextPointText.Len() > 0 ) {
            CalculateTextExtents();
            int teX, teY;
            int scalefactor = round(g_ocpn_draw_pi->m_chart_scale / m_natural_scale);
            
            if(m_natural_scale > (g_ocpn_draw_pi->m_chart_scale / 2) ) {
                teX = m_TextExtents.x;
                teY = m_TextExtents.y;
            } else {
                teX = m_TextExtents.x / scalefactor;
                teY = m_TextExtents.y / scalefactor;
            }
            
            if(teX > 0 && teY > 0 && scalefactor <= 8 ) {
                switch ( m_iTextPosition )
                {
                    case ID_TEXT_TOP:
                        m_TextLocationOffsetX = g_iTextTopOffsetX;
                        m_TextLocationOffsetY = g_iTextTopOffsetY - teY;
                        break;
                    case ID_TEXT_CENTRE_TOP:
                        m_TextLocationOffsetX = g_iTextTopOffsetX - (teX / 2);
                        m_TextLocationOffsetY = g_iTextTopOffsetY - teY;
                        break;
                    case ID_TEXT_BOTTOM:
                        m_TextLocationOffsetX = g_iTextBottomOffsetX;
                        m_TextLocationOffsetY = g_iTextBottomOffsetY;
                        if(m_bShowName) m_TextLocationOffsetY += g_iTextBottomNameExtraOffsetY;
                        break;
                    case ID_TEXT_CENTRE_BOTTOM:
                        m_TextLocationOffsetX = g_iTextBottomOffsetX - (teX / 2);
                        m_TextLocationOffsetY = g_iTextBottomOffsetY;
                        break;
                    case ID_TEXT_CENTRE:
                        m_TextLocationOffsetX = g_iTextCentreOffsetX - (teX / 2);
                        m_TextLocationOffsetY = g_iTextCentreOffsetY - (teY / 2);
                        break;
                    case ID_TEXT_RIGHT:
                        m_TextLocationOffsetX = g_iTextRightOffsetX;
                        m_TextLocationOffsetY = g_iTextRightOffsetY;
                        break;
                    case ID_TEXT_LEFT:
                        m_TextLocationOffsetX = g_iTextLeftOffsetX - teX;
                        m_TextLocationOffsetY = g_iTextLeftOffsetY;
                        break;
                }
                int sx2 = m_pbmIcon->GetWidth() / 2;
                int sy2 = m_pbmIcon->GetHeight() / 2;
                
                //    Calculate the mark drawing extents
                wxPoint r;
                GetCanvasPixLL( g_pivp, &r,  m_lat, m_lon);    
                wxRect r1( r.x - sx2, r.y - sy2, sx2 * 2, sy2 * 2 );           // the bitmap extents
                if( m_DisplayTextFont.IsOk() ) {
                    // Added to help with display of text (stops end clipping)
                    teX += 20;
                    wxRect r2( r.x + m_TextLocationOffsetX, r.y + m_TextLocationOffsetY, teX,
                            teY );
                    r1.Union( r2 );
                    
                    r.x = r.x + m_TextLocationOffsetX;
                    r.y = r.y + m_TextLocationOffsetY;
                    if( scalefactor != m_scale_factor || m_bTextChanged || ( !m_iDisplayTextTexture && teX != 0 && teY != 0 ) ) {
                        m_scale_factor = scalefactor;
                        m_bTextChanged = false;
                        wxBitmap tbm(teX, teY); /* render text on dc */
                        wxMemoryDC dc;
                        dc.SelectObject( tbm );               
                        dc.SetBackground( wxBrush( *wxBLACK ) );
                        dc.Clear();
                        dc.SetFont( m_DisplayTextFont );
                        dc.SetTextForeground(* wxWHITE );
                        if(m_natural_scale > (g_ocpn_draw_pi->m_chart_scale / 2))
                            dc.DrawText( m_TextPointText, 10, 0);
                        //else
                        //    dc.DrawText( wxT(""), 10, 0 );
                        dc.SelectObject( wxNullBitmap );
                        
                        /* make alpha texture for text */
                        wxImage image = tbm.ConvertToImage();
                        unsigned char *d = image.GetData();
                        unsigned char *e = new unsigned char[teX * teY];
                        if(d && e){
                            for( int p = 0; p < teX*teY; p++)
                                e[p] = d[3*p + 0];
                        }
                        /* create texture for rendered text */
                        glGenTextures(1, &m_iDisplayTextTexture);
                        glBindTexture(GL_TEXTURE_2D, m_iDisplayTextTexture);
                        
                        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
                        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
                        
                        m_iDisplayTextTextureWidth = NextPow2(teX);
                        m_iDisplayTextTextureHeight = NextPow2(teY);
                        glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, m_iDisplayTextTextureWidth, m_iDisplayTextTextureHeight,
                                    0, GL_ALPHA, GL_UNSIGNED_BYTE, NULL);
                        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, teX, teY,
                                        GL_ALPHA, GL_UNSIGNED_BYTE, e);
                        delete [] e;
                    }
                    
                    if(m_iDisplayTextTexture) {
                        // Draw backing box
                        ODDC ocpndc;
                        g_ocpn_draw_pi->AlphaBlending( ocpndc, r.x, r.y, r2.width, r2.height, 6.0, m_colourTextBackgroundColour, m_iBackgroundTransparency );
                                
                        /* draw texture with text */
                        glBindTexture(GL_TEXTURE_2D, m_iDisplayTextTexture);
                        
                        glEnable(GL_TEXTURE_2D);
                        glEnable(GL_BLEND);
                        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
                        
                        glColor3ub(m_colourTextColour.Red(), m_colourTextColour.Green(), m_colourTextColour.Blue());
                        
                        int x = r.x, y = r.y;
                        float u = (float)teX/m_iDisplayTextTextureWidth, v = (float)teY/m_iDisplayTextTextureHeight;
                        glBegin(GL_QUADS);
                        glTexCoord2f(0, 0); glVertex2f(x, y);
                        glTexCoord2f(u, 0); glVertex2f(x+teX, y);
                        glTexCoord2f(u, v); glVertex2f(x+teX, y+teY);
                        glTexCoord2f(0, v); glVertex2f(x, y+teY);
                        glEnd();
                        glDisable(GL_BLEND);
                        glDisable(GL_TEXTURE_2D);
                    }

                }
            }
        }
    }
    ODPoint::DrawGL( pivp );
}
//将已经按照姓名汇总的数据分别输出到excel文件中
void CGhQuery::OnBnClickedClassifyExcel()
{
	// 添加文件保存目录

    CString str,strPath;
	
//    ZeroMemory(szPath, sizeof(szPath));   

    BROWSEINFO bi;   
    bi.hwndOwner = m_hWnd;   
    bi.pidlRoot = NULL;   
	bi.pszDisplayName = str.GetBuffer(MAX_PATH);   
    bi.lpszTitle = "请选择汇总信息存放目录:";   
    bi.ulFlags = 0;   
    bi.lpfn = NULL;   
    bi.lParam = 0;   
    bi.iImage = 0;   
    //弹出选择目录对话框
    LPITEMIDLIST lp = SHBrowseForFolder(&bi);   
	str.ReleaseBuffer();

	SHGetPathFromIDList(lp,strPath.GetBuffer(MAX_PATH)) ;
    strPath.ReleaseBuffer();
    
	if(strPath.GetLength() <3){
		AfxMessageBox("选择的目录无效,请重新选择可读写的目录....");
		return;
	}


	UpdateData();

	CFormGhList *pf=(CFormGhList*)theApp.pParentGrid.pGrid;
	int iRows=pf->m_grid.GetRowCount();
	int iCols=pf->m_grid.GetColumnCount();
	if( iRows < 3) {
		AfxMessageBox("没有数据需要进行分类汇总输出,请先进行数据分类汇总....");
		return;
	}
	int iType=m_Type.GetCurSel();
	CString strJournalType;
	if( iType == CB_ERR || iType == 1 )strJournalType="报刊合计";
	else m_Type.GetLBText(iType,strJournalType);

	CString strPath2;
	strPath2.Format("(%s)%s-%s",strJournalType,m_strStart,m_strEnd);
	if( strPath.Right(1) == '\\' )  //路径选择为根目录时,目录后会自动附加'\\'字符,如果是正常的目录,则没有附加的'\\',所以要进行判断
		strPath=strPath+strPath2;
	else 
		strPath=strPath+"\\"+strPath2;

	//判断目录是否存在    
	WIN32_FIND_DATA fd;  
    HANDLE hFind = FindFirstFile(strPath, &fd);  
   // BOOL bFilter = (FALSE == dwFilter) ? TRUE : fd.dwFileAttributes & dwFilter;  
   // BOOL RetValue = ((hFind != INVALID_HANDLE_VALUE) && bFilter) ? TRUE : FALSE;  

    FindClose(hFind);  
	if( fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
		{
			AfxMessageBox("当前目前下已存在要导出的文件目录,如需导出,请重新选择目录...");
			return;
	}
	


	if( ! CreateDirectory(strPath,NULL) ){
		AfxMessageBox("Create directory is error !!");
		return;
	}
	strPath+="\\";
	const int COL_FACTORY=1,COL_NAME=2,COL_PRICE=3,COL_SQ=0;

	_Application app2;
	Workbooks books2;
	_Workbook book2;
	Worksheets sheets2;
	_Worksheet sheet2;
	 COleVariant vOpt(DISP_E_PARAMNOTFOUND,VT_ERROR);
const int  IDC_PROGRESS_EXCEL=WM_USER+10003;
	CProgressEx pp;
	CRect r1(0,0,400,25);
	pp.Create(WS_CHILD |PBS_SMOOTH|WS_BORDER ,r1,AfxGetMainWnd()->GetForegroundWindow(),IDC_PROGRESS_EXCEL);
	pp.UpdateWindow();
	pp.ShowWindow(SW_SHOW);
	pp.CenterWindow();
	pp.Invalidate();
	pp.SetRange32(0,iRows );
	pp.strView="正在准备导出...请稍等!!";

	app2.CreateDispatch("excel.application");
	if(!app2){
		AfxMessageBox("请注意系统中必须装有EXCEL97 或者 EXCEL2000 ,否则此功能不能使用...");
		return;
	}
	CString strFileName;
	strFileName.Format("%sspec.xls",LoginInformation.path);
	books2=app2.GetWorkbooks();


	Range vRange;
	SQ_EXCEL9::Font font;
	long x,y;
	CString str1,str2;
	
	app2.SetVisible(false);
//	pp.strView="";
	books2=app2.GetWorkbooks(); //OPEN excel template
	book2=books2.Open(strFileName,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt,vOpt);
	sheets2=book2.GetWorksheets();
	sheet2=sheets2.GetItem(COleVariant((short)1));


	CString szFlgFactory,szTmp;
	CString szOutFile,szCell;
	int xlsRow(3),clrRow(0);	//clrRow记录文件最后一行行号
	for(int i=1; i< iRows ;i++)
	{
		szFlgFactory=pf->m_grid.GetItemText(i,COL_FACTORY);

		if( xlsRow ==3 ){			
			szCell="a1";
			vRange=sheet2.GetRange(_variant_t(szCell),_variant_t(szCell) );
			vRange.SetValue(_variant_t(szFlgFactory));
			szOutFile.Format("%s%s(%s-%s).xls",strPath,szFlgFactory,m_strStart,m_strEnd);
			if(  clrRow ){
				szCell.Format("A3:%c%d",'A'+COL_PRICE,clrRow+1);
				vRange=sheet2.GetRange(_variant_t(szCell),_variant_t(szCell) );
				szCell="";
				vRange.SetValue(_variant_t(szCell));
				clrRow=0;
			}
		}

		if( i !=1 && xlsRow!= 3 ){
	
			szTmp=pf->m_grid.GetItemText(i-1,COL_FACTORY);
			if( szTmp.Compare(szFlgFactory) !=0 ){
	
				szCell.Format("%c%d",'A'+COL_PRICE,xlsRow);
				vRange=sheet2.GetRange(_variant_t(szCell),_variant_t(szCell) );
				szCell.Format("=sum(D3:D%d)",xlsRow-1);
				vRange.SetValue(_variant_t(szCell));
			
				book2.SaveAs(_variant_t(szOutFile),vOpt,vOpt,vOpt,vOpt,vOpt,0L,vOpt,vOpt,vOpt,vOpt);
			
				xlsRow=3;
				i--;
				continue;
			}

		}
		for(int iCol=0; iCol< iCols ; iCol++){	//输出到excel表格
			szCell.Format("%c%d",'A'+iCol,xlsRow);
			vRange=sheet2.GetRange(_variant_t(szCell),_variant_t(szCell) );
			if( iCol == 0 ) szCell.Format("%d",xlsRow-2);   //xlsRow 起始行为3,第一列为序号列,
			else 	
				szCell=pf->m_grid.GetItemText(i,iCol);
			vRange.SetValue(_variant_t(szCell));
		}
		xlsRow++;
		clrRow=xlsRow;
	
		pp.strView.Format("%2.0f%%",double(i)/iRows*100);
		pp.SetPos(i);

	}

	pp.SendMessage(WM_CLOSE);

	sheet2.ReleaseDispatch();

	sheets2.ReleaseDispatch();

	book2.SetSaved(true);	//设置已存储标志,在quit是不提示更改保存
	book2.Close(_variant_t(false ),vOpt,vOpt);

	books2.Close();
	book2.ReleaseDispatch();
	books2.ReleaseDispatch();
	app2.Quit();
	app2.ReleaseDispatch();	
	
}
void bi::RK43IntegratorHost<B,S,T1>::update(const T1 t1, const T1 t2,
    State<B,ON_HOST>& s) {
  /* pre-condition */
  BI_ASSERT(t1 < t2);

  typedef typename temp_host_vector<real>::type vector_type;
  typedef Pa<ON_HOST,B,host,host,host,host> PX;
  typedef RK43VisitorHost<B,S,S,real,PX,real> Visitor;

  static const int N = block_size<S>::value;
  const int P = s.size();

  #pragma omp parallel
  {
    vector_type r1(N), r2(N), err(N), old(N);
    real t, h, e, e2, logfacold, logfac11, fac;
    int n, id, p;
    PX pax;

    #pragma omp for
    for (p = 0; p < P; ++p) {
      t = t1;
      h = h_h0;
      logfacold = bi::log(BI_REAL(1.0e-4));
      n = 0;
      host_load<B,S>(s, p, old);
      r1 = old;

      /* integrate */
      while (t < t2 && n < h_nsteps) {
        if (BI_REAL(0.1)*bi::abs(h) <= bi::abs(t)*h_uround) {
          // step size too small
        }
        if (t + BI_REAL(1.01)*h - t2 > BI_REAL(0.0)) {
          h = t2 - t;
          if (h <= BI_REAL(0.0)) {
            t = t2;
            break;
          }
        }

        /* stages */
        Visitor::stage1(t, h, s, p, pax, r1.buf(), r2.buf(), err.buf());
        host_store<B,S>(s, p, r1);

        Visitor::stage2(t, h, s, p, pax, r1.buf(), r2.buf(), err.buf());
        host_store<B,S>(s, p, r2);

        Visitor::stage3(t, h, s, p, pax, r1.buf(), r2.buf(), err.buf());
        host_store<B,S>(s, p, r1);

        Visitor::stage4(t, h, s, p, pax, r1.buf(), r2.buf(), err.buf());
        host_store<B,S>(s, p, r2);

        Visitor::stage5(t, h, s, p, pax, r1.buf(), r2.buf(), err.buf());
        host_store<B,S>(s, p, r1);

        /* compute error */
        e2 = BI_REAL(0.0);
        for (id = 0; id < N; ++id) {
          e = err(id)*h/(h_atoler + h_rtoler*bi::max(bi::abs(old(id)), bi::abs(r1(id))));
          e2 += e*e;
        }
        e2 /= N;

        if (e2 <= BI_REAL(1.0)) {
          /* accept */
          t += h;
          if (t < t2) {
            old = r1;
          }
        } else {
          /* reject */
          r1 = old;
          host_store<B,S>(s, p, old);
        }

        /* compute next step size */
        if (t < t2) {
          logfac11 = h_expo*bi::log(e2);
          if (e2 > BI_REAL(1.0)) {
            /* step was rejected */
            h *= bi::max(h_facl, bi::exp(h_logsafe - logfac11));
          } else {
            /* step was accepted */
            fac = bi::exp(h_beta*logfacold + h_logsafe - logfac11); // Lund-stabilization
            fac = bi::min(h_facr, bi::max(h_facl, fac)); // bound
            h *= fac;
            logfacold = BI_REAL(0.5)*bi::log(bi::max(e2, BI_REAL(1.0e-8)));
          }
        }

        ++n;
      }
    }
  }
}
示例#23
0
 void RefTests::Run()
 {
     // dereferencing
     {
         Ref<int> r(new int(1234));
         
         // get the value back out
         EXPECT_EQUAL(1234, *r);
     }
     
     // nested reference
     {
         {
             Ref<DestructorTester> r1(new DestructorTester());
             
             {
                 Ref<DestructorTester> r2 = r1;
                 Ref<DestructorTester> r3 = r1;
                 Ref<DestructorTester> r4 = r2;
             }
             
             EXPECT_EQUAL(false, DestructorTester::Destructed());
         }
         
         EXPECT_EQUAL(true, DestructorTester::Destructed());
     }
     
     // chained reference
     {
         {
             Ref<DestructorTester> r1;
             
             {
                 Ref<DestructorTester> r2(new DestructorTester());
                 r1 = r2;
             }
             
             EXPECT_EQUAL(false, DestructorTester::Destructed());
         }
         
         EXPECT_EQUAL(true, DestructorTester::Destructed());
     }
     
     // setting to null
     {
         Ref<DestructorTester> r1(new DestructorTester());
         
         EXPECT_EQUAL(false, DestructorTester::Destructed());
         
         r1 = Ref<DestructorTester>();
         
         EXPECT_EQUAL(true, DestructorTester::Destructed());
     }
     
     {
         Ref<int> a(new int(123));
         Ref<int> b = a;
         
         b = Ref<int>();
     }
 }
示例#24
0
void QtGradientWidget::mousePressEvent(QMouseEvent *e)
{
    if (e->button() != Qt::LeftButton)
        return;

    QPoint p = e->pos();
    if (d_ptr->m_gradientType == QGradient::LinearGradient) {
        QPointF startPoint = d_ptr->toViewport(d_ptr->m_startLinear);
        double x = p.x() - startPoint.x();
        double y = p.y() - startPoint.y();

        if ((d_ptr->m_handleSize * d_ptr->m_handleSize / 4) > (x * x + y * y)) {
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::StartLinearHandle;
            d_ptr->m_dragOffset = QPointF(x, y);
            update();
            return;
        }

        QPointF endPoint = d_ptr->toViewport(d_ptr->m_endLinear);
        x = p.x() - endPoint.x();
        y = p.y() - endPoint.y();

        if ((d_ptr->m_handleSize * d_ptr->m_handleSize / 4) > (x * x + y * y)) {
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::EndLinearHandle;
            d_ptr->m_dragOffset = QPointF(x, y);
            update();
            return;
        }
    } else if (d_ptr->m_gradientType == QGradient::RadialGradient) {
        QPointF focalPoint = d_ptr->toViewport(d_ptr->m_focalRadial);
        double x = p.x() - focalPoint.x();
        double y = p.y() - focalPoint.y();

        if ((d_ptr->m_handleSize * d_ptr->m_handleSize / 9) > (x * x + y * y)) {
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::FocalRadialHandle;
            d_ptr->m_dragOffset = QPointF(x, y);
            update();
            return;
        }

        QPointF centralPoint = d_ptr->toViewport(d_ptr->m_centralRadial);
        x = p.x() - centralPoint.x();
        y = p.y() - centralPoint.y();

        if ((d_ptr->m_handleSize * d_ptr->m_handleSize / 4) > (x * x + y * y)) {
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::CentralRadialHandle;
            d_ptr->m_dragOffset = QPointF(x, y);
            update();
            return;
        }

        QPointF central = d_ptr->toViewport(d_ptr->m_centralRadial);
        QRectF r = d_ptr->pointRect(central, 2 * d_ptr->m_handleSize / 3);
        QRectF r1(0, r.y(), size().width(), r.height());
        QRectF r2(r.x(), 0, r.width(), r.y());
        QRectF r3(r.x(), r.y() + r.height(), r.width(), size().height() - r.y() - r.height());
        QPointF pF(p.x(), p.y());
        if (r1.contains(pF) || r2.contains(pF) || r3.contains(pF)) {
            x = pF.x() / size().width() - d_ptr->m_centralRadial.x();
            y = pF.y() / size().height() - d_ptr->m_centralRadial.y();
            double clickRadius = sqrt(x * x + y * y);
            //d_ptr->m_radiusOffset = d_ptr->m_radiusRadial - clickRadius;
            d_ptr->m_radiusFactor = d_ptr->m_radiusRadial / clickRadius;
            if (d_ptr->m_radiusFactor == 0)
                d_ptr->m_radiusFactor = 1;
            d_ptr->m_dragRadius = d_ptr->m_radiusRadial;
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::RadiusRadialHandle;
            mouseMoveEvent(e);
            update();
            return;
        }
    } else if (d_ptr->m_gradientType == QGradient::ConicalGradient) {
        QPointF centralPoint = d_ptr->toViewport(d_ptr->m_centralConical);
        double x = p.x() - centralPoint.x();
        double y = p.y() - centralPoint.y();

        if ((d_ptr->m_handleSize * d_ptr->m_handleSize / 4) > (x * x + y * y)) {
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::CentralConicalHandle;
            d_ptr->m_dragOffset = QPointF(x, y);
            update();
            return;
        }
        double radius = size().width();
        if (size().height() < radius)
            radius = size().height();
        radius /= 2;
        double corr = d_ptr->m_handleSize / 3;
        radius -= corr;
        QPointF vp = d_ptr->toViewport(d_ptr->m_centralConical);
        x = p.x() - vp.x();
        y = p.y() - vp.y();
        if (((radius - corr) * (radius - corr) < (x * x + y * y)) &&
                ((radius + corr) * (radius + corr) > (x * x + y * y))) {
            QPointF central = d_ptr->toViewport(d_ptr->m_centralConical);
            QPointF current(e->pos().x(), e->pos().y());
            x = current.x() - central.x();
            y = current.y() - central.y();
            x /= size().width() / 2;
            y /= size().height() / 2;
            double r = sqrt(x * x + y * y);

            double arcSin = asin(y / r);
            double arcCos = acos(x / r);

            double angle = arcCos * 180 / M_PI;
            if (arcSin > 0) {
                angle = -angle;
            }

            d_ptr->m_angleOffset = d_ptr->m_angleConical - angle;
            d_ptr->m_dragAngle = d_ptr->m_angleConical;
            d_ptr->m_dragHandle = QtGradientWidgetPrivate::AngleConicalHandle;
            update();
            return;
        }
    }
}
示例#25
0
void TKComboBox::paintEvent(QPaintEvent*)
{
  QRect r;
  if (editable()){
#ifdef __GNUC__
#warning "Left out for now, lacking a style expert (Werner)"
#endif
    //r = QRect( style().comboButtonRect( 0, 0, width(), height() ) );
    r = QRect(4, 2, width()-height()-2, height()-4);
  } else {
    r = QRect(4, 2, width()-height()-2, height()-4);
  }
  int by = 2;
  int bx = r.x() + r.width();
  int bw = width() - bx - 2;
  int bh = height()-4;

  QPainter p( this );
  const QColorGroup& g = colorGroup();

  QRect fr(2,2,width()-4,height()-4);

  if ( hasFocus()) {
    p.fillRect( fr, g.brush( QColorGroup::Highlight ) );
  } else {
    p.fillRect( fr, g.brush( QColorGroup::Base ) );
  }

  QRect r1(1,1,width()-1,height()-1);
  qDrawShadePanel( &p, r1, g, true, 1 );

  static const char* arrow_down[] = {
  "7 7 2 1",
  "X c Gray0",
  "  c None",
  "XXXXXXX",
  "XXXXXXX",
  "       ",
  "XXXXXXX",
  " XXXXX ",
  "  XXX  ",
  "   X   "};

  QPixmap pixmap(arrow_down);


  style().drawControl( QStyle::CE_PushButton, &p, this, QRect( bx, by, bw, bh ), colorGroup() );
  style().drawItem( &p, QRect( bx, by, bw, bh), AlignCenter, colorGroup(), isEnabled(), &pixmap, QString::null );

  if ( hasFocus()) {
    style().drawPrimitive( QStyle::PE_FocusRect, &p, fr, g );
  }

  if (!editable()) {
    p.setClipRect(r);
    p.setPen( g.text() );
    p.setBackgroundColor( g.background() );

    if ( listBox()->item(currentItem()) ) {
      QListBoxItem * item = listBox()->item(currentItem());
      const QPixmap *pix = item->pixmap();
      QString text = item->text();
      int x = r.x();
      if ( pix ) {
        p.drawPixmap( x, r.y() + ( r.height() - pix->height() ) / 2 +1, *pix );
        x += pix->width()+3;
      }
      if (!text.isEmpty())
        p.drawText( x, r.y(), r.width()-x, r.height(), AlignLeft|AlignVCenter|SingleLine, text );
    }
  }
  p.end();
}
示例#26
0
void QtGradientWidget::paintEvent(QPaintEvent *e)
{
    Q_UNUSED(e)

    QPainter p(this);

    if (d_ptr->m_backgroundCheckered) {
        int pixSize = 40;
        QPixmap pm(2 * pixSize, 2 * pixSize);

        QPainter pmp(&pm);
        pmp.fillRect(0, 0, pixSize, pixSize, Qt::white);
        pmp.fillRect(pixSize, pixSize, pixSize, pixSize, Qt::white);
        pmp.fillRect(0, pixSize, pixSize, pixSize, Qt::black);
        pmp.fillRect(pixSize, 0, pixSize, pixSize, Qt::black);

        p.setBrushOrigin((size().width() % pixSize + pixSize) / 2, (size().height() % pixSize + pixSize) / 2);
        p.fillRect(rect(), pm);
        p.setBrushOrigin(0, 0);
    }

    QGradient *gradient = 0;
    switch (d_ptr->m_gradientType) {
    case QGradient::LinearGradient:
        gradient = new QLinearGradient(d_ptr->m_startLinear, d_ptr->m_endLinear);
        break;
    case QGradient::RadialGradient:
        gradient = new QRadialGradient(d_ptr->m_centralRadial, d_ptr->m_radiusRadial, d_ptr->m_focalRadial);
        break;
    case QGradient::ConicalGradient:
        gradient = new QConicalGradient(d_ptr->m_centralConical, d_ptr->m_angleConical);
        break;
    default:
        break;
    }
    if (!gradient)
        return;

    gradient->setStops(d_ptr->m_gradientStops);
    gradient->setSpread(d_ptr->m_gradientSpread);

    p.save();
    p.scale(size().width(), size().height());
    p.fillRect(QRect(0, 0, 1, 1), *gradient);
    p.restore();

    p.setRenderHint(QPainter::Antialiasing);

    QColor c = QColor::fromRgbF(0.5, 0.5, 0.5, 0.5);
    QBrush br(c);
    p.setBrush(br);
    QPen pen(Qt::white);
    pen.setWidthF(1);
    p.setPen(pen);
    QPen dragPen = pen;
    dragPen.setWidthF(2);
    if (d_ptr->m_gradientType == QGradient::LinearGradient) {
        p.save();
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::StartLinearHandle)
            p.setPen(dragPen);
        d_ptr->paintPoint(&p, d_ptr->m_startLinear, d_ptr->m_handleSize);
        p.restore();

        p.save();
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::EndLinearHandle)
            p.setPen(dragPen);
        d_ptr->paintPoint(&p, d_ptr->m_endLinear, d_ptr->m_handleSize);
        p.restore();
    } else if (d_ptr->m_gradientType == QGradient::RadialGradient) {
        QPointF central = d_ptr->toViewport(d_ptr->m_centralRadial);

        p.save();
        QRectF r = d_ptr->pointRect(central, 2 * d_ptr->m_handleSize / 3);
        QRectF r1(0, r.y(), size().width(), r.height());
        QRectF r2(r.x(), 0, r.width(), r.y());
        QRectF r3(r.x(), r.y() + r.height(), r.width(), size().height() - r.y() - r.height());
        p.fillRect(r1, c);
        p.fillRect(r2, c);
        p.fillRect(r3, c);
        p.setBrush(Qt::NoBrush);
        p.save();
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::CentralRadialHandle)
            p.setPen(dragPen);
        d_ptr->paintPoint(&p, d_ptr->m_centralRadial, d_ptr->m_handleSize);
        p.restore();

        QRectF rect = QRectF(central.x() - d_ptr->m_radiusRadial * size().width(),
                             central.y() - d_ptr->m_radiusRadial * size().height(),
                             2 * d_ptr->m_radiusRadial * size().width(),
                             2 * d_ptr->m_radiusRadial * size().height());
        p.setClipRect(r1);
        p.setClipRect(r2, Qt::UniteClip);
        p.setClipRect(r3, Qt::UniteClip);
        p.drawEllipse(rect);
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::RadiusRadialHandle) {
            p.save();
            p.setPen(dragPen);
            QRectF rect = QRectF(central.x() - d_ptr->m_radiusRadial / d_ptr->m_radiusFactor * size().width(),
                                 central.y() - d_ptr->m_radiusRadial / d_ptr->m_radiusFactor * size().height(),
                                 2 * d_ptr->m_radiusRadial / d_ptr->m_radiusFactor * size().width(),
                                 2 * d_ptr->m_radiusRadial / d_ptr->m_radiusFactor * size().height());
            p.drawEllipse(rect);

            p.restore();
        }
        p.restore();

        p.save();
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::FocalRadialHandle)
            p.setPen(dragPen);
        d_ptr->paintPoint(&p, d_ptr->m_focalRadial, 2 * d_ptr->m_handleSize / 3);
        p.restore();
    } else if (d_ptr->m_gradientType == QGradient::ConicalGradient) {
        double radius = size().width();
        if (size().height() < radius)
            radius = size().height();
        radius /= 2;
        double corr = d_ptr->m_handleSize / 3;
        radius -= corr;
        QPointF central = d_ptr->toViewport(d_ptr->m_centralConical);

        p.save();
        p.setBrush(Qt::NoBrush);
        QPen pen2(c);
        pen2.setWidthF(2 * d_ptr->m_handleSize / 3);
        p.setPen(pen2);
        p.drawEllipse(d_ptr->pointRect(central, 2 * radius));
        p.restore();

        p.save();
        p.setBrush(Qt::NoBrush);
        int pointCount = 2;
        for (int i = 0; i < pointCount; i++) {
            QPointF ang(cos(M_PI * (i * 180.0 / pointCount + d_ptr->m_angleConical) / 180) * size().width() / 2,
                        -sin(M_PI * (i * 180.0 / pointCount + d_ptr->m_angleConical) / 180) * size().height() / 2);
            double mod = sqrt(ang.x() * ang.x() + ang.y() * ang.y());
            p.drawLine(QPointF(central.x() + ang.x() * (radius - corr) / mod,
                               central.y() + ang.y() * (radius - corr) / mod),
                       QPointF(central.x() + ang.x() * (radius + corr) / mod,
                               central.y() + ang.y() * (radius + corr) / mod));
            p.drawLine(QPointF(central.x() - ang.x() * (radius - corr) / mod,
                               central.y() - ang.y() * (radius - corr) / mod),
                       QPointF(central.x() - ang.x() * (radius + corr) / mod,
                               central.y() - ang.y() * (radius + corr) / mod));
        }
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::AngleConicalHandle) {
            p.save();
            p.setPen(dragPen);
            QPointF ang(cos(M_PI * (d_ptr->m_angleConical - d_ptr->m_angleOffset) / 180) * size().width() / 2,
                        -sin(M_PI * (d_ptr->m_angleConical - d_ptr->m_angleOffset) / 180) * size().height() / 2);
            double mod = sqrt(ang.x() * ang.x() + ang.y() * ang.y());
            p.drawLine(QPointF(central.x() + ang.x() * (radius - corr) / mod,
                               central.y() + ang.y() * (radius - corr) / mod),
                       QPointF(central.x() + ang.x() * (radius + corr) / mod,
                               central.y() + ang.y() * (radius + corr) / mod));
            p.restore();
        }

        p.restore();

        p.save();
        if (d_ptr->m_dragHandle == QtGradientWidgetPrivate::CentralConicalHandle)
            p.setPen(dragPen);
        d_ptr->paintPoint(&p, d_ptr->m_centralConical, d_ptr->m_handleSize);
        p.restore();

    }

    delete gradient;
}
示例#27
0
void RoutePoint::Draw( ocpnDC& dc, wxPoint *rpn )
{
    wxPoint r;
    wxRect hilitebox;

    cc1->GetCanvasPointPix( m_lat, m_lon, &r );

    //  return the home point in this dc to allow "connect the dots"
    if( NULL != rpn ) *rpn = r;

    if( !m_bIsVisible )     // pjotrc 2010.02.13, 2011.02.24
        return;

    //    Optimization, especially apparent on tracks in normal cases
    if( m_IconName == _T("empty") && !m_bShowName && !m_bPtIsSelected ) return;

    wxPen *pen;
    if( m_bBlink )
        pen = g_pRouteMan->GetActiveRoutePointPen();
    else
        pen = g_pRouteMan->GetRoutePointPen();

//    Substitue icon?
    wxBitmap *pbm;
    if( ( m_bIsActive ) && ( m_IconName != _T("mob") ) )
        pbm = pWayPointMan->GetIconBitmap( _T ( "activepoint" ) );
    else
        pbm = m_pbmIcon;

    wxBitmap *pbms = NULL;
    if( g_ChartScaleFactorExp > 1.0){
        if(m_IconScaleFactor != g_ChartScaleFactorExp){
            wxImage scaled_image = pbm->ConvertToImage();
            int new_width = pbm->GetWidth() * g_ChartScaleFactorExp;
            int new_height = pbm->GetHeight() * g_ChartScaleFactorExp;
            m_ScaledBMP = wxBitmap(scaled_image.Scale(new_width, new_height, wxIMAGE_QUALITY_HIGH));
           
            m_IconScaleFactor = g_ChartScaleFactorExp;
        }
        if( m_ScaledBMP.IsOk() )
            pbm = &m_ScaledBMP;
    }
        
    int sx2 = pbm->GetWidth() / 2;
    int sy2 = pbm->GetHeight() / 2;

//    Calculate the mark drawing extents
    wxRect r1( r.x - sx2, r.y - sy2, sx2 * 2, sy2 * 2 );           // the bitmap extents

    if( m_bShowName ) {
        if( 0 == m_pMarkFont ) {
            m_pMarkFont = FontMgr::Get().GetFont( _( "Marks" ) );
            m_FontColor = FontMgr::Get().GetFontColor( _( "Marks" ) );
            CalculateNameExtents();
        }

        if( m_pMarkFont ) {
            wxRect r2( r.x + m_NameLocationOffsetX, r.y + m_NameLocationOffsetY, m_NameExtents.x,
                    m_NameExtents.y );
            r1.Union( r2 );
        }
    }

    hilitebox = r1;
    hilitebox.x -= r.x;
    hilitebox.y -= r.y;
    float radius;
    if( g_btouch ){
        hilitebox.Inflate( 20 );
        radius = 20.0f;
    }
    else{
        hilitebox.Inflate( 4 );
        radius = 4.0f;
    }

    wxColour hi_colour = pen->GetColour();
    unsigned char transparency = 100;
    if( m_bIsBeingEdited ){
        hi_colour = GetGlobalColor( _T ( "YELO1" ) );
        transparency = 150;
    }
    
        
    //  Highlite any selected point
    if( m_bPtIsSelected || m_bIsBeingEdited) {
        AlphaBlending( dc, r.x + hilitebox.x, r.y + hilitebox.y, hilitebox.width, hilitebox.height, radius,
                hi_colour, transparency );
    }

    bool bDrawHL = false;

    if( m_bBlink && ( gFrame->nBlinkerTick & 1 ) ) bDrawHL = true;

    if( ( !bDrawHL ) && ( NULL != m_pbmIcon ) ) {
        dc.DrawBitmap( *pbm, r.x - sx2, r.y - sy2, true );
        // on MSW, the dc Bounding box is not updated on DrawBitmap() method.
        // Do it explicitely here for all platforms.
        dc.CalcBoundingBox( r.x - sx2, r.y - sy2 );
        dc.CalcBoundingBox( r.x + sx2, r.y + sy2 );
    }

    if( m_bShowName ) {
        if( m_pMarkFont ) {
            dc.SetFont( *m_pMarkFont );
            dc.SetTextForeground( m_FontColor );

            dc.DrawText( m_MarkName, r.x + m_NameLocationOffsetX, r.y + m_NameLocationOffsetY );
        }
    }

    // Draw waypoint radar rings if activated
    if( m_iWaypointRangeRingsNumber && m_bShowWaypointRangeRings ) {
        double factor = 1.00;
        if( m_iWaypointRangeRingsStepUnits == 1 )          // nautical miles
            factor = 1 / 1.852;

        factor *= m_fWaypointRangeRingsStep;

        double tlat, tlon;
        wxPoint r1;
        ll_gc_ll( m_lat, m_lon, 0, factor, &tlat, &tlon );
        cc1->GetCanvasPointPix( tlat, tlon, &r1 );

        double lpp = sqrt( pow( (double) (r.x - r1.x), 2) +
                           pow( (double) (r.y - r1.y), 2 ) );
        int pix_radius = (int) lpp;

        wxPen ppPen1( m_wxcWaypointRangeRingsColour, 2 );
        wxBrush saveBrush = dc.GetBrush();
        wxPen savePen = dc.GetPen();
        dc.SetPen( ppPen1 );
        dc.SetBrush( wxBrush( m_wxcWaypointRangeRingsColour, wxBRUSHSTYLE_TRANSPARENT ) );

        for( int i = 1; i <= m_iWaypointRangeRingsNumber; i++ )
            dc.StrokeCircle( r.x, r.y, i * pix_radius );
        dc.SetPen( savePen );
        dc.SetBrush( saveBrush );
    }
    
    //  Save the current draw rectangle in the current DC
    //    This will be useful for fast icon redraws
    CurrentRect_in_DC.x = r.x + hilitebox.x;
    CurrentRect_in_DC.y = r.y + hilitebox.y;
    CurrentRect_in_DC.width = hilitebox.width;
    CurrentRect_in_DC.height = hilitebox.height;

    if( m_bBlink ) g_blink_rect = CurrentRect_in_DC;               // also save for global blinker

    delete pbms;        // the potentially scaled bitmap
}
示例#28
0
static void epat_read_block( PIA *pi, char * buf, int count )

{	int  k, ph, a, b;

	switch (pi->mode) {

	case 0:	w0(7); w2(1); w2(3); w0(0xff);
		ph = 0;
		for(k=0;k<count;k++) {
			if (k == count-1) w0(0xfd);
			w2(6+ph); a = r1();
			if (a & 8) b = a; 
			  else { w2(4+ph); b = r1(); }
			buf[k] = j44(a,b);
			ph =  1 - ph;
		}
		w0(0); w2(4);
		break;

	case 1: w0(0x47); w2(1); w2(5); w0(0xff);
		ph = 0;
		for(k=0;k<count;k++) {
			if (k == count-1) w0(0xfd); 
			w2(4+ph);
			a = r1(); b = r2();
			buf[k] = j53(a,b);
			ph = 1 - ph;
		}
		w0(0); w2(4);
		break;

	case 2: w0(0x27); w2(1); w2(0x25); w0(0);
		ph = 0;
		for(k=0;k<count-1;k++) {
			w2(0x24+ph);
			buf[k] = r0();
			ph = 1 - ph;
		}
		w2(0x26); w2(0x27); buf[count-1] = r0(); 
		w2(0x25); w2(4);
		break;

	case 3: w3(0x80); w2(0x24);
		for(k=0;k<count-1;k++) buf[k] = r4();
		w2(4); w3(0xa0); w2(0x24); buf[count-1] = r4();
		w2(4);
		break;

	case 4: w3(0x80); w2(0x24);
		for(k=0;k<(count/2)-1;k++) ((u16 *)buf)[k] = r4w();
		buf[count-2] = r4();
		w2(4); w3(0xa0); w2(0x24); buf[count-1] = r4();
		w2(4);
		break;

	case 5: w3(0x80); w2(0x24);
		for(k=0;k<(count/4)-1;k++) ((u32 *)buf)[k] = r4l();
		for(k=count-4;k<count-1;k++) buf[k] = r4();
		w2(4); w3(0xa0); w2(0x24); buf[count-1] = r4();
		w2(4);
		break;

	}
}
示例#29
0
文件: main.cpp 项目: ducthangho/3D
int test1()
{	
	//srand(1989);
	MyRectangle enclosingRect(40, 40);
	MyRectangle r1(15, 30);
	MyRectangle r2(20, 25);
	MyRectangle r3(9, 7);
	MyRectangle r4(20, 8);
	MyRectangle r5(10, 10);

	std::vector<MyRectangle> listRect;
	listRect.push_back(r1);
	listRect.push_back(r2);
	listRect.push_back(r3);
	listRect.push_back(r4);
	listRect.push_back(r5);

	std::vector<std::vector<AreaRect>> listArea;
	std::vector<AreaRect> row1;
	row1.emplace_back(15, 25, 0, 0, false);
	row1.emplace_back(20, 25, 15, 0, false);
	row1.emplace_back(5, 25, 35, 0, true);

	std::vector<AreaRect> row2;
	row2.emplace_back(15, 5, 0, 25, false);
	row2.emplace_back(20, 5, 15, 25, true);
	row2.emplace_back(5, 5, 35, 25, true);

	std::vector<AreaRect> row3;
	row3.emplace_back(15, 10, 0, 30, true);
	row3.emplace_back(20, 10, 15, 30, true);
	row3.emplace_back(5, 10, 35, 30, true);

	std::vector<AreaRect> row4;
	row4.emplace_back(15, 9, 0, 40, true);
	row4.emplace_back(20, 9, 15, 40, true);
	row4.emplace_back(5, 9, 35, 40, true);

	listArea.push_back(row1);
	listArea.push_back(row2);
	listArea.push_back(row3);
	listArea.push_back(row4);

	vector<vector<AreaRect>> listArea2;
	listArea2.reserve(100000);
	listArea2.emplace_back(1, AreaRect(enclosingRect.w, enclosingRect.h, 0, 0, true));
	
	PackingAlogorithm pa;
	float places[6];

	/*if (pa.findPlace(r1, enclosingRect, listArea2, places))
	{
		r1.x = places[0];
		r1.y = places[1];
		r1.print();
		pa.updateListArea(listArea2, r1, places[2], places[3], places[4], places[5]);
		pa.printListArea(listArea2);
	}
	cout << "--------------------------------" << endl;
	if (pa.findPlace(r2, enclosingRect, listArea2, places))
	{
		r2.x = places[0];
		r2.y = places[1];
		r2.print();
		pa.updateListArea(listArea2, r2, places[2], places[3], places[4], places[5]);
		pa.printListArea(listArea2);
	}
	cout << "--------------------------------" << endl;
	if (pa.findPlace(r5, enclosingRect, listArea2, places))
	{
		r5.x = places[0];
		r5.y = places[1];
		r5.print();
		pa.updateListArea(listArea2, r5, places[2], places[3], places[4], places[5]);
		pa.printListArea(listArea2);
	}
	cout << "--------------------------------" << endl;
	if (pa.findPlace(r4, enclosingRect, listArea2, places))
	{
		r4.x = places[0];
		r4.y = places[1];
		r4.print();
		pa.updateListArea(listArea2, r4, places[2], places[3], places[4], places[5],true);
		pa.printListArea(listArea2);
	}
	cout << "--------------------------------" << endl;
	if (pa.findPlace(r3, enclosingRect, listArea2, places))
	{
		r3.x = places[0];
		r3.y = places[1];
		r3.print();
		cout << "i: " << places[2] << "j: " << places[3] << "er: " << places[4] << "ec: " << places[5];
		pa.updateListArea(listArea2, r3, places[2], places[3], places[4], places[5],true);
		pa.printListArea(listArea2);
	}*/
	/*std::vector<MyRectangle> result = pa.pack(listRect, enclosingRect);
	for (auto& a : result)
	{
		a.print();
	}*/
	

	//std::vector<MyRectangle> listRect;
	Time tt;
	for (int i = 0; i < 20000; i++)
	{
		auto w = rand() % 30 + 1;
		auto h = rand() % 40 + 1;
		MyRectangle a(w,h);
		listRect.push_back(a);
	}
	std::cout << "Data creation time = " << tt.duration() << " ms" << std::endl;
	Time t;
	MyRectangle enclosingRect2(500,500);
	std::vector<MyRectangle> r = pa.pack(listRect, enclosingRect2);
	cout << r.size() << endl;
	std::cout << "Execution time = " << t.duration() << " ms" << std::endl;
	for (auto& a : r)
	{
		a.print();
	}
	return 0;
}
示例#30
0
/*!
  Returns the region specified by \a decorationRegion for the
  top-level \a widget. \a rect specifies the rectangle the decoration
  wraps. The value of \a decorationRegion is a combination of the
  bitmask values of enum DecorationRegion.
 */
QRegion QDecorationDefault::region(const QWidget *widget,
                                   const QRect &rect,
                                   int decorationRegion)
{
    Qt::WindowFlags flags = widget->windowFlags();
    bool hasBorder = !widget->isMaximized();
    bool hasTitle = flags & Qt::WindowTitleHint;
    bool hasSysMenu = flags & Qt::WindowSystemMenuHint;
    bool hasContextHelp = flags & Qt::WindowContextHelpButtonHint;
    bool hasMinimize = flags & Qt::WindowMinimizeButtonHint;
    bool hasMaximize = flags & Qt::WindowMaximizeButtonHint;
    int state = widget->windowState();
    bool isMinimized = state & Qt::WindowMinimized;
    bool isMaximized = state & Qt::WindowMaximized;

    int titleHeight = hasTitle ? titleBarHeight(widget) : 0;
    int bw = hasBorder ? BORDER_WIDTH : 0;
    int bbw = hasBorder ? BOTTOM_BORDER_WIDTH : 0;

    QRegion region;
    switch (decorationRegion) {
        case All: {
                QRect r(rect.left() - bw,
                        rect.top() - titleHeight - bw,
                        rect.width() + 2 * bw,
                        rect.height() + titleHeight + bw + bbw);
                region = r;
                region -= rect;
            }
            break;

        case Title: {
                QRect r(rect.left()
                        + (hasSysMenu ? menu_width : 0),
                        rect.top() - titleHeight,
                        rect.width()
                        - (hasSysMenu ? menu_width : 0)
                        - close_width
                        - (hasMaximize ? maximize_width : 0)
                        - (hasMinimize ? minimize_width : 0)
                        - (hasContextHelp ? help_width : 0),

                        titleHeight);
                if (r.width() > 0)
                    region = r;
            }
            break;

        case Top: {
                QRect r(rect.left() + CORNER_GRAB,
                        rect.top() - titleHeight - bw,
                        rect.width() - 2 * CORNER_GRAB,
                        bw);
                region = r;
            }
            break;

        case Left: {
                QRect r(rect.left() - bw,
                        rect.top() - titleHeight + CORNER_GRAB,
                        bw,
                        rect.height() + titleHeight - 2 * CORNER_GRAB);
                region = r;
            }
            break;

        case Right: {
                QRect r(rect.right() + 1,
                        rect.top() - titleHeight + CORNER_GRAB,
                        bw,
                        rect.height() + titleHeight - 2 * CORNER_GRAB);
                region = r;
            }
            break;

        case Bottom: {
                QRect r(rect.left() + CORNER_GRAB,
                        rect.bottom() + 1,
                        rect.width() - 2 * CORNER_GRAB,
                        bw);
                region = r;
            }
            break;

        case TopLeft: {
                QRect r1(rect.left() - bw,
                        rect.top() - bw - titleHeight,
                        CORNER_GRAB + bw,
                        bw);

                QRect r2(rect.left() - bw,
                        rect.top() - bw - titleHeight,
                        bw,
                        CORNER_GRAB + bw);

                region = QRegion(r1) + r2;
            }
            break;

        case TopRight: {
                QRect r1(rect.right() - CORNER_GRAB,
                        rect.top() - bw - titleHeight,
                        CORNER_GRAB + bw,
                        bw);

                QRect r2(rect.right() + 1,
                        rect.top() - bw - titleHeight,
                        bw,
                        CORNER_GRAB + bw);

                region = QRegion(r1) + r2;
            }
            break;

        case BottomLeft: {
                QRect r1(rect.left() - bw,
                        rect.bottom() + 1,
                        CORNER_GRAB + bw,
                        bw);

                QRect r2(rect.left() - bw,
                        rect.bottom() - CORNER_GRAB,
                        bw,
                        CORNER_GRAB + bw);
                region = QRegion(r1) + r2;
            }
            break;

        case BottomRight: {
                QRect r1(rect.right() - CORNER_GRAB,
                        rect.bottom() + 1,
                        CORNER_GRAB + bw,
                        bw);

                QRect r2(rect.right() + 1,
                        rect.bottom() - CORNER_GRAB,
                        bw,
                        CORNER_GRAB + bw);
                region = QRegion(r1) + r2;
            }
            break;

        case Menu: {
                if (hasSysMenu) {
                    region = QRect(rect.left(), rect.top() - titleHeight,
                                   menu_width, titleHeight);
                }
            }
            break;

        case Help: {
                if (hasContextHelp) {
                    QRect r(rect.right()
                            - close_width
                            - (hasMaximize ? maximize_width : 0)
                            - (hasMinimize ? minimize_width : 0)
                            - help_width + 1, rect.top() - titleHeight,
                            help_width, titleHeight);
                    if (r.left() > rect.left() + titleHeight)
                        region = r;
                }
            }
            break;


        case Minimize: {
                if (hasMinimize && !isMinimized) {
                    QRect r(rect.right() - close_width
                            - (hasMaximize ? maximize_width : 0)
                            - minimize_width + 1, rect.top() - titleHeight,
                            minimize_width, titleHeight);
                    if (r.left() > rect.left() + titleHeight)
                        region = r;
                }
            }
            break;

        case Maximize: {
                if (hasMaximize && !isMaximized) {
                    QRect r(rect.right() - close_width - maximize_width + 1,
                            rect.top() - titleHeight, maximize_width, titleHeight);
                    if (r.left() > rect.left() + titleHeight)
                        region = r;
                }
            }
            break;

        case Normalize: {
                if (hasMinimize && isMinimized) {
                    QRect r(rect.right() - close_width
                            - (hasMaximize ? maximize_width : 0)
                            - minimize_width + 1, rect.top() - titleHeight,
                            minimize_width, titleHeight);
                    if (r.left() > rect.left() + titleHeight)
                        region = r;
                } else if (hasMaximize && isMaximized) {
                    QRect r(rect.right() - close_width - maximize_width + 1,
                            rect.top() - titleHeight, maximize_width, titleHeight);
                    if (r.left() > rect.left() + titleHeight)
                        region = r;
                }
            }
            break;

        case Close: {
                QRect r(rect.right() - close_width + 1, rect.top() - titleHeight,
                        close_width, titleHeight);
                if (r.left() > rect.left() + titleHeight)
                    region = r;
            }
            break;

    default: {
        int i = 1;
        while (i) {
            if (i & decorationRegion)
                region += this->region(widget, rect, i);
            i <<= 1;
        }
    }
            break;
    }

    return region;
}