void addConnector(OSG::AttachmentContainer *pContainer,
                  OSG::BasicFieldConnector *pConn     )
{
    if(pContainer == NULL)
    {
        FFATAL(("addConnector: no container?!?"));
        return;
    }

    if(pConn == NULL)
    {
        FFATAL(("addConnector: no connector?!?"));
        return;
    }

    ConnectorAttachmentUnrecPtr pCA = NULL;

    Attachment          *att = pContainer->findAttachment(
        ConnectorAttachment::getClassType().getGroupId());

    if(att == NULL)
    {
        pCA = ConnectorAttachment::createDependent(
            pContainer->getFieldFlags()->_bNamespaceMask);

        pContainer->addChangedFunctor(
            boost::bind(&ConnectorAttachment::processChanged, 
                        pCA.get(), 
                        _1, 
                        _2),
            "");

        pContainer->addAttachment(pCA);
    }
    else
    {
        pCA = dynamic_cast<ConnectorAttachment *>(att);

        if(pCA == NULL)
        {
            FFATAL(("setName: Attachment is not castable to Conn?!?"));
            return;
        }
    }

    if(pCA->hasConnectionTo(pConn->getDst()) == false)
    {
        FieldContainer *pDst = pConn->getDst();

        pDst->addChangedFunctor(
            boost::bind(&ConnectorAttachment::targetDestroyed, 
                        pCA.get(), 
                        _1, 
                        _2),
            "");
    }

    pCA->addConnection(pConn);
}
OSG_BASE_DLLMAPPING 
void extend(      OSG::FrustumVolume &OSG_CHECK_ARG(srcVol), 
            const OSG::BoxVolume     &OSG_CHECK_ARG(vol   ))
{
    FFATAL(("extend (frustum/box) is not impl.\n"));
    return;
}
void
OSBNodeElement::read(const std::string &typeName)
{
    OSG_OSB_LOG(("OSBNodeElement::read [%s]\n", typeName.c_str()));

    BinaryReadHandler *rh        = editRoot()->getReadHandler();
    UInt8              fcPtrType;
    UInt16             version;

    rh->getValue(fcPtrType);
    rh->getValue(version  );

    OSG_OSB_LOG(("OSBNodeElement::read: version: [%u]\n", version));

    if(fcPtrType != OSBCommonElement::FCPtrNode)
    {
        FFATAL(("OSBNodeElement::read: fcPtrType has unexpected value.\n"));

        skipFields();
        return;
    }

    NodeUnrecPtr node = Node::create();

    setContainer(node);
    readFields("'volume'", "");
}
/*! Updates the camera transformation matrix directly in the node specified as
    the cart.
*/
void Navigator::updateCameraTransformation()
{
    theMatrix.setIdentity();
    if(_absolute && _cartN != NULL && _cartN->getParent() != NULL)
    {
        _cartN->getParent()->getToWorld(theMatrix);
        theMatrix.inverse(theMatrix);
    }

    _engine->onUpdateCameraTransformation(this);
    theMatrix.mult(_engine->getMatrix());

    if(_cartN != NULL)
    {
        Transform *t = dynamic_cast<Transform *>(_cartN->getCore());
        if(t == NULL)
        {
            FWARNING (("Navigator: updateCamTrans, core is not TransformPtr\n"));
        }
        else
        {
            if(t->getMatrix() != theMatrix)
            {
                t->setMatrix(theMatrix);
            }
        }
    }
    else
    {
        FFATAL (("!_cartN in Navigator::updateCameraTrans\n"));
    }
}
void setBoostPath(      AttachmentContainer *pContainer, 
                  const BoostPath            &oPath     )
{
    if(pContainer == NULL)
    {
        FFATAL(("setBoostPath: no container?!?\n"));
        return;
    }

    // Get attachment pointer

    Attachment *pAtt  = 
        pContainer->findAttachment(
            BoostPathAttachment::getClassType().getGroupId());

    if(pAtt != NULL)
    {
        pContainer->subAttachment(pAtt);
    }

    BoostPathAttachmentUnrecPtr pPathAttachment = BoostPathAttachment::create();

    pPathAttachment->setPath(oPath);   

    pContainer->addAttachment(pPathAttachment);
}
示例#6
0
OSG_BASE_DLLMAPPING 
void extend(      FrustumVolume &OSG_CHECK_ARG(srcVol), 
            const SphereVolume  &OSG_CHECK_ARG(vol   ))
{
    FFATAL(("extend (frustum/sphere) is not impl.\n"));
    return;
}
示例#7
0
OSG_BASE_DLLMAPPING 
bool intersect(const FrustumVolume &OSG_CHECK_ARG(frustum1),
               const FrustumVolume &OSG_CHECK_ARG(frustum2))
{
    FFATAL(("intersect (frustum/frustum) is not impl.\n"));
    return false;
}
示例#8
0
OSG_BASE_DLLMAPPING 
void extend(      BoxVolume     &OSG_CHECK_ARG(srcVol), 
            const FrustumVolume &OSG_CHECK_ARG(vol   ))
{
    FFATAL(("extend (box/frustum) is not impl.\n"));
    return;
}
OSG_BASE_DLLMAPPING 
void extend(      OSG::SphereVolume  &OSG_CHECK_ARG(srcVol), 
            const OSG::FrustumVolume &OSG_CHECK_ARG(vol   ))
{
    FFATAL(("extend (sphere/frustum) is not impl.\n"));
    return;
}
示例#10
0
OSG_BASE_DLLMAPPING 
void extend(      FrustumVolume  &OSG_CHECK_ARG(srcVol),
            const CylinderVolume &OSG_CHECK_ARG(vol   ))
{
    FFATAL(("extend (frustum/cylinder) is not impl.\n"));
    return;
}
示例#11
0
/*!
Constructor which takes a suffix array and size to add the
ImageFileType to the Singleton ImageFileHandler
*/
ImageFileType::ImageFileType( const char *mimeType,
                              const Char8 *suffixArray[], 
                              UInt16 suffixByteCount,
                              UInt32 flags)
{
    Int32 suffixCount = suffixByteCount / sizeof(const Char8 *);
    Int32 i = 0;
    std::list<IDString>::iterator sI;

    if (!mimeType) {
      FFATAL (("ImageFileType without valid mimeType\n"));
    }
    _mimeType.set(mimeType);

    _suffixList.resize(suffixCount);
    for(sI = _suffixList.begin(); sI != _suffixList.end(); sI++)
    {
        sI->set(suffixArray[i++]);
        SINFO << "add image suffix: " << *sI << endLog;
    }

    _flags = flags;
    
    ImageFileHandler::addImageFileType(*this);
}
示例#12
0
void NormalQuantifier::build (UInt32 numberSubdivisions)
{
    UInt32 index = 0;
    UInt32 nN    = ((1 << (2 * numberSubdivisions)) * 8);
    
    _numberSubdivisions = numberSubdivisions;

    _normalTable.resize(nN);
  
    if(_numberSubdivisions != 0) 
    {
        for(UInt32 octant = 0; octant < 8; octant++) 
        {
            Int32 xoctant = (octant & 4)>0?-1:1;
            Int32 yoctant = (octant & 2)>0?-1:1;
            Int32 zoctant = (octant & 1)>0?-1:1;
            
            Vec3f point1(0.f * xoctant, 0.f * yoctant, 1.f * zoctant);
            Vec3f point2(1.f * xoctant, 0.f * yoctant, 0.f * zoctant);
            Vec3f point3(0.f * xoctant, 1.f * yoctant, 0.f * zoctant);
            
            subdivide(point1, point2, point3, _numberSubdivisions+1, index);
        }
        
        if(index != nN)
        {
            FFATAL(("NormalQuantifier::build() index missmatch!\n"));
        }
        else
        {
            FLOG(("NormalQuantifier init: %d subdivision, %d normal\n",
                  _numberSubdivisions, _normalTable.size()));
        }
    }  
}
bool SharePtrGraphOp::traverse(Node *root)
{
    if(!_includeSet.empty() && !_excludeSet.empty())
    {
        FFATAL(("SharePtrGraphOp : Setting both the includes and excludes"
                "is not allowed!\n"));
        return false;
    }

    _typeMap   .clear();
    _shareCount.clear();

    _totalTime   = 0.0f;
    _compareTime = 0.0f;

    Time startTime = getSystemTime();

    shareFC(root);

    _totalTime = getSystemTime() - startTime;

    // DEBUG
    SINFO << "SharePtrGraphOp::traverse: _totalTime: " << _totalTime
          << " _compareTime: " << _compareTime << "\n";
    SINFO << "SharePtrGraphOp::traverse: Unique containers by type:\n";

    FCTypeMapIt tmIt  = _typeMap.begin();
    FCTypeMapIt tmEnd = _typeMap.end  ();

    for(; tmIt != tmEnd; ++tmIt)
    {
        UInt32              typeId = tmIt->first;
        FieldContainerType *fcType = FieldContainerFactory::the()->findType(typeId);

        SINFO << "TypeId [" << typeId << "] [" << (fcType != NULL ? fcType->getCName() : "")
              << "] -- [" << tmIt->second.size() << "]\n";
    }

    SINFO << "SharePtrGraphOp::traverse: Shared containers by type:\n";

    ShareCountIt scIt  = _shareCount.begin();
    ShareCountIt scEnd = _shareCount.end  ();

    for(; scIt != scEnd; ++scIt)
    {
        UInt32              typeId = scIt->first;
        FieldContainerType *fcType = FieldContainerFactory::the()->findType(typeId);

        SINFO << "TypeId [" << typeId << "] [" << (fcType != NULL ? fcType->getCName() : "")
              << "] -- [" << scIt->second << "]\n";
    }

    SINFO << std::flush;

    _typeMap   .clear();
    _shareCount.clear();

    return true;
}
static void osg_jpeg_output_message(j_common_ptr cinfo)
{
    char buffer[JMSG_LENGTH_MAX];

    /* Create the message */
    (*cinfo->err->format_message) (cinfo, buffer);

    /* Send it to the OSG logger, adding a newline */
    FFATAL (("JPG: %s\n", buffer));
}
示例#15
0
Action::ResultE changeGeo(NodePtr& node)
{   
    GeometryPtr geo = GeometryPtr::dcast(node->getCore());
    
    if(geo == NullFC)
        return Action::Continue;


    GeoColors3fPtr colors = GeoColors3fPtr::dcast(geo->getColors());
    if(colors == NullFC)
    {
        colors = GeoColors3f::create();

        colors->resize(geo->getPositions()->getSize());
        
        // Change the geometry to use the new colors
        beginEditCP(geo, Geometry::ColorsFieldMask);
            geo->setColors(colors);
            // If multi-indexed, make the colors use the same index as
            // the geometry
            if(geo->getMFIndexMapping()->size() > 0)
            {
                Int16 pind = geo->calcMappingIndex(Geometry::MapPosition);
                
                if(pind < 0)
                {
                    FFATAL(("Multi-indexed, but no positions index???\n"));
                    return Action::Continue; 
                }
                
                // This makes the colors use the same indices as the positions
                geo->editIndexMapping(pind) |= Geometry::MapColor;
            }
        endEditCP  (geo, Geometry::ColorsFieldMask);
    }
    

    beginEditCP(geo, Geometry::ColorsFieldMask);
    beginEditCP(colors);
    Real32 size = colors->getSize();
    for(UInt32 i=0;i<size;++i)
    {
        Color3f c;
        c[0] = ((Real32) i) / size;
        c[1] = 0.0f;
        c[2] = 0.0f;
        colors->setValue(c, i);
    }
    endEditCP(colors);
    endEditCP(geo, Geometry::ColorsFieldMask);
    
    return Action::Continue; 
}
void OFVertexPalette::addRecord(OFVertexPaletteRecord *pVertexPal)
{
    if(_pVertexPalette == NULL)
    {
        _pVertexPalette = pVertexPal;
    }
    else
    {
        FFATAL(("OFVertexPalette::addRecord: VertexPaletteRecord "
                "already present\n"));
    }
}
void OFColorPalette::addRecord(OFColorPaletteRecord *pColorPal)
{
    if(_pColorPalette == NULL)
    {
        _pColorPalette = pColorPal;
    }
    else
    {
        FFATAL(("OFColorPalette::addRecord: ColorPaletteRecord "
                "already present\n"));
    }
}
示例#18
0
bool OSGSceneFileType::write(const NodePtr &root, std::ostream &os,
                             const Char8 *) const
{
    if(!os)
    {
        FFATAL(("Can not open output stream!\n"));
        return false;
    }

    OSGWriter writer(os, 4);
    writer.write(root);

    return true;
}
void setVoidP(AttachmentContainer * const  pContainer, 
              void                *        pData,
              bool                         bInternal)
{
    if(pContainer == NULL)
    {
        FFATAL(("setVoidP: no container?!?"));
        return;
    }
   
    // Get attachment pointer

    VoidPAttachmentUnrecPtr  voidP = NULL;
    Attachment              *att   = 
        pContainer->findAttachment(
            VoidPAttachment::getClassType().getGroupId());
    
    if(att == NULL)
    {
        voidP = VoidPAttachment::create();

        pContainer->addAttachment(voidP);
    }
    else
    {   
        voidP = dynamic_cast<VoidPAttachment *>(att);

        if(voidP == NULL)
        {
            FFATAL(("setVoidP: VoidP Attachment is not castable to Name?!?"));
            return;
        }
    }
     
    voidP->editFieldPtr()->setValue(pData);
    voidP->setInternal(bInternal);
}
void setName(AttachmentContainer * const  pContainer, 
             std::string           const &namestring)
{
    if(pContainer == NULL)
    {
        FFATAL(("setName: no container?!?\n"));
        return;
    }
   
    // Get attachment pointer

    NameUnrecPtr  name = NULL;
    Attachment   *att  = 
        pContainer->findAttachment(Name::getClassType().getGroupId());
    
    if(att == NULL)
    {
        name = Name::createDependent(
            pContainer->getFieldFlags()->_bNamespaceMask);

        pContainer->addAttachment(name);
    }
    else
    {   
        name = dynamic_cast<Name *>(att);

        if(name == NULL)
        {
            FFATAL(("setName: Name Attachment is not castable to Name?!?\n"));
            return;
        }
    }
    
  
    name->editFieldPtr()->getValue().assign(namestring);   
}
void OFMaterialPalette::addRecord(OFMaterialPaletteRecord *pMat)
{
    if(pMat != NULL)
    {
        MaterialStoreIt mIt = _mMaterials.find(pMat->getMaterialIdx());

        if(mIt == _mMaterials.end())
        {
            _mMaterials[pMat->getMaterialIdx()] = pMat;
        }
        else
        {
            FFATAL(("OFMaterialPalette::addRecord: Material with idx [%d] "
                    "already present.\n", pMat->getMaterialIdx()));
        }
    }
}
bool OSGSceneFileType::write(Node * const  root, 
                             std::ostream &os,
                             Char8  const *    ) const
{
    if(!os)
    {
        FFATAL(("Can not open output stream!\n"));
        return false;
    }

    IndentOutStreamMixin<OutStream> iOStream(os);

    OSGWriter writer(iOStream, 4);
    writer.write(root);

    return true;
}
void OFTexturePalette::addRecord(OFTexturePaletteRecord *pTex)
{
    if(pTex != NULL)
    {
        TextureStoreIt tIt = _mTextures.find(pTex->getPatternIdx());

        if(tIt == _mTextures.end())
        {
            _mTextures[pTex->getPatternIdx()] = pTex;
        }
        else
        {
            FFATAL(("OFTexturePalette::addRecord: Texture with idx [%d] "
                    "already present.\n", pTex->getPatternIdx()));
        }
    }
}
ImageFileType *ImageFileHandlerBase::getDefaultType(void)
{
    std::string dSuffix("opensg");
    
    std::map<std::string, 
             ImageFileType *>::iterator sI = _suffixTypeMap.find(dSuffix);


    ImageFileType *type = (sI == _suffixTypeMap.end()) ? 0 : sI->second;

    if(!type)
    {
        FFATAL(("Can not find any default (suffix:%s) image handler\n",
                dSuffix.c_str()));
    }

    return type;
}
void subConnector(OSG::AttachmentContainer *pSrcContainer, 
                  OSG::BitVector            bSrcMask,
                  OSG::FieldContainer      *pDstContainer, 
                  OSG::BitVector            bDstMask)
{
    if(pSrcContainer == NULL)
    {
        FFATAL(("subConnector: no container?!?"));
        return;
    }

    ConnectorAttachmentUnrecPtr pCA = NULL;

    Attachment          *att = pSrcContainer->findAttachment(
        ConnectorAttachment::getClassType().getGroupId());

    pCA = dynamic_cast<ConnectorAttachment *>(att);
    
    if(pCA != NULL)
    {
        pCA->removeConnections(bSrcMask, pDstContainer, bDstMask);
    }
}
UChar8 *ImageFileHandlerBase::store(Image  const *pImage, 
                                    UInt64       &memSize,
                                    Char8  const *mimeType)
{
    ImageFileType   *type = 0;
    UChar8          *mem = 0;

    type    = mimeType ? getFileType(mimeType) : getDefaultType();
    memSize = type->maxBufferSize(pImage);

    if(memSize)
    {
        mem     = new UChar8[size_t(memSize)];

        memSize = type->store(pImage, mem, Int32(memSize));
    }
    else
    {
        FFATAL(("Can not store the image as %s\n", type->getMimeType()));
    }

    return mem;
}
示例#27
0
Int32 OBJSceneFileType::readMTL ( const Char8 *fileName,
                                  std::map<std::string,
                                  SimpleTexturedMaterialUnrecPtr> & mtlMap )
  const
{
    if(fileName == NULL || strlen(fileName) == 0)
        return 0;

    Int32 mtlCount = 0;

    PathHandler *pathHandler = SceneFileHandler::the()->getPathHandler();
    std::string fullFilePath;

    if(pathHandler != NULL)
        fullFilePath = pathHandler->findFile(fileName);
    else
        fullFilePath = fileName;

    if(fullFilePath.empty())
    {
        FWARNING (("Couldn't open '%s'!\n", fileName));
        return 0;
    }

    std::ifstream in(fullFilePath.c_str());
    SimpleTexturedMaterialUnrecPtr mtlPtr = NULL;
    Real32 a,b,c;
    std::string elem;
    std::map<std::string, MaterialElem>::const_iterator elemI;
    MaterialElem mtlElem;
    std::map<std::string, OSG::ImageUnrecPtr> imageMap;
    std::map<std::string, OSG::ImageUnrecPtr>::iterator iI;
    ImageUnrecPtr image = NULL;
    bool constDiffuse = false, constAmbient = false, constSpecular = false;

    if (in)
    {
        for (in >> elem; in.eof() == false; in >> elem)
        {
            if (elem[0] == '#' || elem[0] == '$' )
            {
                in.ignore(INT_MAX, '\n');
            }
            else
            {
                elemI = _mtlElemMap.find(elem);
                mtlElem = ((elemI == _mtlElemMap.end()) ?
                     UNKNOWN_ME : elemI->second);
                if (mtlElem == NEW_MTL_ME)
                {
                    in >> elem;
                    mtlPtr = SimpleTexturedMaterial::create();
                    mtlPtr->setColorMaterial(GL_NONE);
                    mtlPtr->setEnvMode(GL_MODULATE);
                    mtlMap[elem] = mtlPtr;
                    mtlCount++;
                    constDiffuse  = false;
                    constAmbient  = false;
                    constSpecular = false;
                }
                else
                {
                    if (mtlPtr == NULL)
                    {
                        FFATAL (( "Invalid Mtl token: %s, newmtl expected in %s\n",
                                elem.c_str(), fileName ));
                        in.ignore(INT_MAX, '\n');
                    }
                    else
                    {
                        switch (mtlElem)
                        {
                            case MTL_DIFFUSE_ME:
                                in >> a >> b >> c;
                                if (!constDiffuse)
                                    mtlPtr->setDiffuse( Color3f( a,b,c ));
                            break;
                            case MTL_AMBIENT_ME:
                                in >> a >> b >> c;
                                if (!constAmbient)
                                    mtlPtr->setAmbient( Color3f( a,b,c ));
                            break;
                            case MTL_SPECULAR_ME:
                                in >> a >> b >> c;
                                if (!constSpecular)
                                    mtlPtr->setSpecular( Color3f( a,b,c ));
                            break;
                            case MTL_SHININESS_ME:
                                in >> a;
                                mtlPtr->setShininess(a);
                            break;
                            case MTL_ILLUM_ME:
                                ; // TODO: What to do with illum ?!?
                                in >> elem;
                                // FFATAL (("obj mtl illum not handled yet\n"));
                            break;
                            case MTL_REFL_ME:
                                mtlPtr->setEnvMap(true);
                            break;
                            case MTL_TRANSPARENCY_ME:
                                in >> a;
                                mtlPtr->setTransparency(a);
                            break;
                            case MTL_DISSOLVE_ME:
                                in >> a;
                                mtlPtr->setTransparency(1.f - a);
                                break;
                            case MTL_MAP_KD_ME:
                            case MTL_MAP_KA_ME:
                            case MTL_MAP_KS_ME:
                                image = NULL;
                                in >> elem;
                                iI = imageMap.find(elem);
                                if (iI == imageMap.end())
                                {
                                    std::string fullElemPath;
                                    if(pathHandler != NULL)
                                        fullElemPath = pathHandler->findFile(elem.c_str());
                                    else
                                        fullElemPath = elem.c_str();
                                    image = OSG::ImageFileHandler::the()->read(fullElemPath.c_str());

                                    if(image != NULL)
                                    {
                                        image->setForceAlphaBinary(
                                            image->calcIsAlphaBinary());

                                        imageMap[elem] = image;
                                    }
                                }
                                else
                                {
                                    image = iI->second;
                                }
                                if (image != NULL)
                                {
                                    mtlPtr->setImage(image);
                                    switch (mtlElem)
                                    {
                                        case MTL_MAP_KD_ME:
                                            constDiffuse = true;
                                            mtlPtr->setDiffuse  ( Color3f( 1.f, 1.f, 1.f) );
                                        break;
                                        case MTL_MAP_KA_ME:
                                            constAmbient = true;
                                            mtlPtr->setAmbient  ( Color3f( 1.f, 1.f, 1.f) );
                                        break;
                                        case MTL_MAP_KS_ME:
                                            constSpecular = true;
                                            mtlPtr->setSpecular ( Color3f( 1.f, 1.f, 1.f) );
                                        break;
                                        default:
                                        break;
                                    }
                                }
                                else
                                {
                                    FFATAL (( "Can not find %s texture file in mtl %s \n",
                                            elem.c_str(), fileName ));
                                }
                            break;
                            default:
                                FWARNING (( "Invalid %s entry in %s\n",
                                            elem.c_str(), fileName ));
                                in.ignore(INT_MAX, '\n');
                        }
                    }
                }
            }
        }
示例#28
0
//----------------------------
// Function name: read
//----------------------------
//
//Parameters:
//p: Scene &image, const char *fileName
//GlobalVars:
//g:
//Returns:
//r:bool
// Caution
//c:
//Assumations:
//a:
//Describtions:
//d: read the image from the given file
//SeeAlso:
//s:
//
//------------------------------
NodeTransitPtr OBJSceneFileType::read(      std::istream &is,
                                      const Char8        *,
                                            Resolver        ) const
{
    NodeUnrecPtr rootPtr, nodePtr;
    std::string elem;
    std::map<std::string, DataElem>::const_iterator elemI;
    Vec3f vec3r;
    Pnt3f pnt3r;
    Vec2f vec2r;
    Real32 x,y,z;
    GeoPnt3fPropertyUnrecPtr coordPtr    = GeoPnt3fProperty::create();
    GeoVec2fPropertyUnrecPtr texCoordPtr = GeoVec2fProperty::create();
    GeoVec3fPropertyUnrecPtr normalPtr   = GeoVec3fProperty::create();
    GeometryUnrecPtr geoPtr;
    GeoIntegralPropertyUnrecPtr posIndexPtr, texIndexPtr, normalIndexPtr;
    GeoIntegralPropertyUnrecPtr lensPtr;
    GeoIntegralPropertyUnrecPtr typePtr;
    DataElem dataElem;
    DataElem lastDataElem;
    Char8 strBuf[8192], *token, *nextToken;
    Int32 strBufSize = sizeof(strBuf)/sizeof(Char8);
    Int32 index, posIndex = 0, indexType;
    Int32 i,j,n,primCount[3];
    std::list<Mesh> meshList;
    std::map<std::string, SimpleTexturedMaterialUnrecPtr> mtlMap;
    std::map<std::string, SimpleTexturedMaterialUnrecPtr>::iterator mtlI;
    Mesh emptyMesh;
    Face emptyFace;
    TiePoint  emptyTie;
    Int32 indexMask, meshIndexMask;
    std::list<Face>::iterator faceI;
    std::list<Mesh>::iterator meshI;
    bool isSingleIndex;

    // create the first mesh entry
    meshList.push_back(emptyMesh);
    meshI = meshList.begin();

    if(is)
    {
        primCount[0] = 0;
        primCount[1] = 0;
        primCount[2] = 0;

        for(is >> elem; is.eof() == false; is >> elem)
        {
            if(elem[0] == '#' || elem[0] == '$')
            {
                is.ignore(INT_MAX, '\n');
            }
            else
            {
                SceneFileHandler::the()->updateReadProgress();

                elemI = _dataElemMap.find(elem);
                dataElem = ((elemI == _dataElemMap.end()) ?
                        UNKNOWN_DE : elemI->second );
                switch (dataElem)
                {
                    case OBJECT_DE:
                    case GROUP_DE:
                    case SMOOTHING_GROUP_DE:
                        is.ignore(INT_MAX, '\n');
                    break;
                    case VERTEX_DE:
                        primCount[0]++;
                        is >> x >> y >> z;
                        pnt3r.setValues(x,y,z);
                        coordPtr->addValue(pnt3r);
                    break;
                    case VERTEX_TEXTURECOORD_DE:
                        primCount[1]++;
                        is >> x >> y;
                        vec2r.setValues(x,y);
                        texCoordPtr->addValue(vec2r);
                    break;
                    case VERTEX_NORMAL_DE:
                        primCount[2]++;
                        is >> x >> y >> z;
                        vec3r.setValues(x,y,z);
                        normalPtr->addValue(vec3r);
                    break;
                    case LIB_MTL_DE:
                        is >> elem;
                        readMTL ( elem.c_str(), mtlMap );
                        is.ignore(INT_MAX, '\n');
                    break;
                    case USE_MTL_DE:
                        is >> elem;
                        if (meshI->faceList.empty() == false)
                        {
                            meshList.push_front(emptyMesh);
                            meshI = meshList.begin();
                        }
                        mtlI = mtlMap.find(elem);
                        if (mtlI == mtlMap.end())
                        {
                            FFATAL (("Unkown mtl %s\n", elem.c_str()));
                        }
                        else
                        {
                            meshI->mtlPtr = mtlI->second;
                        }
                    break;
                    case FACE_DE:
                        meshI->faceList.push_front(emptyFace);
                        faceI = meshI->faceList.begin();
                        is.get(strBuf,strBufSize);
                        token = strBuf;
                        indexType = 0;
                        while(token && *token)
                        {
                            // some tools use line continuation for long
                            // face definitions - these use a \ at the line
                            // end
                            if(*token == '\\')
                            {
                                is.ignore(1, '\n');
                                is.get(strBuf,strBufSize);
                                token = strBuf;
                                indexType = 0;
                                continue;
                            }
                            for (; *token == '/'; token++)
                                indexType++;
                            for (; isspace(*token); token++)
                                indexType = 0;
                            index = strtol(token, &nextToken, 10);
                            if (token == nextToken)
                                break;
                            if (indexType == 0)
                                faceI->tieVec.push_back(emptyTie);
                            if (index >= 0)
                                index--;
                            else
                                index =  primCount[indexType] + index;
                            faceI->tieVec.back().index[indexType] = index;
                            token = nextToken;
                        }
                    break;

                    case UNKNOWN_DE:
                    default:
                        // don't warn about 3rd tex coord
                        if(lastDataElem != VERTEX_TEXTURECOORD_DE)
                        {
                            FWARNING (( "Unkown obj data elem: %s\n", 
                                        elem.c_str()));
                        }
                        is.ignore(INT_MAX, '\n');
                    break;
                }

                lastDataElem = dataElem;
            }
        }

#if 0
        std::cerr << "------------------------------------------------" << std::endl;
        i = 0;
        for (meshI = meshList.begin(); meshI != meshList.end(); meshI++)
        {
            std::cerr << "Mesh " << i << " faceCount :"
                      << meshI->faceList.size() << std::endl;
            j = 0 ;
            for ( faceI = meshI->faceList.begin(); faceI != meshI->faceList.end();
                  faceI++)
            std::cerr << "MESH " <<  i << "face: " << j++ << "tie num: "
                      << faceI->tieVec.size() << std::endl;
            i++;
        }
        std::cerr << "------------------------------------------------" << std::endl;
#endif

        // create Geometry objects
        for (meshI = meshList.begin(); meshI != meshList.end(); meshI++)
        {
            geoPtr   = Geometry::create();
            posIndexPtr = NULL;
            texIndexPtr = NULL;
            normalIndexPtr = NULL;
            lensPtr  = GeoUInt32Property::create();
            typePtr  = GeoUInt8Property ::create();

            // create and check mesh index mask
            meshIndexMask = 0;
            isSingleIndex = true;
            if ( meshI->faceList.empty() == false)
            {
                for ( faceI = meshI->faceList.begin();
                  faceI != meshI->faceList.end(); faceI++)
                {
                    indexMask = 0;
                    n = UInt32(faceI->tieVec.size());
                    for (i = 0; i < n; i++)
                    {
                        for (j = 0; j < 3; j++)
                        {
                            if ((index = (faceI->tieVec[i].index[j])) >= 0)
                            {
                                indexMask |= (1 << j);
                                if (j)
                                    isSingleIndex &= (posIndex == index);
                                else
                                    posIndex = index;
                            }
                        }
                    }
                    if (meshIndexMask == 0)
                    {
                        meshIndexMask = indexMask;
                    }
                    else if (meshIndexMask != indexMask)
                    {
                        // consider this real-world example:
                       // [...]
                       // f 1603//1747 1679//1744 1678//1743
                       // s 1
                       // f 9/1/10 5/2/9 1680/3/1748 1681/4/174
                       // [...]
                       // Some faces contain texture coords and others do not.
                       // The old version did just skip this geometry.
                       // This version should continue if there's at least
                       // the vertex index
                       // I've seen the change in the maskIndex only after a smooth group,
                       // so it's perhaps smarter to not ignore the smooth group further up in this code
                       if( !(indexMask & 1) )
                       {
                         // if there are vertex indices there's no reason to get in here
                          FFATAL (( "IndexMask unmatch, can not create geo\n"));
                          meshIndexMask = 0;
                          break;
                       }
                       else
                       {
                         // consider the minimum similarities of mesh masks
                         meshIndexMask &= indexMask;
                       }
                    }
                }
            }
            else
            {
                FWARNING (("Mesh with empty faceList\n"));
            }

            // fill the geo properties
            if (meshIndexMask)
            {
                geoPtr->setPositions ( coordPtr );
                posIndexPtr = GeoUInt32Property::create();
                if(!isSingleIndex)
                    geoPtr->setIndex(posIndexPtr, Geometry::PositionsIndex);
                geoPtr->setLengths   ( lensPtr );
                geoPtr->setTypes     ( typePtr );

                if ( (meshIndexMask & 2) && texCoordPtr->size() > 0 )
                {
                    geoPtr->setTexCoords ( texCoordPtr );
                    texIndexPtr = GeoUInt32Property::create();
                    if(!isSingleIndex)
                        geoPtr->setIndex(texIndexPtr, Geometry::TexCoordsIndex);
                }
                else
                {
                    geoPtr->setTexCoords ( NULL );
                }

                if ( (meshIndexMask & 4) && normalPtr->size() > 0 )
                {
                    geoPtr->setNormals   ( normalPtr );
                    normalIndexPtr = GeoUInt32Property::create();
                    if(!isSingleIndex)
                        geoPtr->setIndex(normalIndexPtr, Geometry::NormalsIndex);
                }
                else
                {
                    geoPtr->setNormals   ( NULL );
                }

                if (meshI->mtlPtr == NULL)
                {
                    meshI->mtlPtr = SimpleTexturedMaterial::create();
                    meshI->mtlPtr->setDiffuse( Color3f( .8f, .8f, .8f ) );
                    meshI->mtlPtr->setSpecular( Color3f( 1.f, 1.f, 1.f ) );
                    meshI->mtlPtr->setShininess( 20.f );
                }
                geoPtr->setMaterial  ( meshI->mtlPtr );

                for ( faceI = meshI->faceList.begin();
                      faceI != meshI->faceList.end(); faceI++)
                {
                    n = UInt32(faceI->tieVec.size());

                    // add the lens entry
                    lensPtr->push_back(n);

                    // add the type entry
                    typePtr->push_back(GL_POLYGON);

                    // create the index values
                    for (i = 0; i < n; i++)
                    {
                        if (isSingleIndex)
                        {
                            posIndexPtr->push_back(faceI->tieVec[i].index[0]);
                        }
                        else
                        {
                            posIndexPtr->push_back(faceI->tieVec[i].index[0]);
                            if(texIndexPtr != NULL)
                                texIndexPtr->push_back(faceI->tieVec[i].index[1]);
                            if(normalIndexPtr != NULL)
                                normalIndexPtr->push_back(faceI->tieVec[i].index[2]);
                        }
                    }
                }

                if(isSingleIndex)
                {
                    geoPtr->setIndex(posIndexPtr, Geometry::PositionsIndex);
                    geoPtr->setIndex(posIndexPtr, Geometry::NormalsIndex  );
                    geoPtr->setIndex(posIndexPtr, Geometry::TexCoordsIndex);
                }

                // need to port the geometry functions ...
                createSharedIndex( geoPtr );

                // check if we have normals
                // need to port the geometry functions ...

                if(geoPtr->getNormals() == NULL)
                    calcVertexNormals(geoPtr);

                // create and link the node
                nodePtr = Node::create();
                nodePtr->setCore( geoPtr );

                if (meshList.size() > 1)
                {
                    if (rootPtr == NULL)
                    {
                        rootPtr = Node::create();

                        GroupUnrecPtr tmpPtr = Group::create();

                        rootPtr->setCore ( tmpPtr );
                        rootPtr->addChild(nodePtr);
                    }
                    else
                    {
                        rootPtr->addChild(nodePtr);
                    }
                }
                else
                {
                    rootPtr = nodePtr;
                }
            }
        }
    }

    SceneFileHandler::the()->updateReadProgress(100);

    commitChanges();

    return NodeTransitPtr(rootPtr);
}
示例#29
0
bool Text::fillImage(ImagePtr & image, 
                     std::vector<std::string> &lineVec, 
                     Color4ub *fg,
                     Color4ub *bg, 
                     bool forcePower2, 
                     Real32 *maxX,
                     Real32 *maxY,
                     ImageCreationMode OSG_CHECK_ARG(creationMode),
                     MergeMode OSG_CHECK_ARG(mergeMode), 
                     Int32 pixelDepth,
					 bool bConvertToBitmap ) const
{
    ImageFontGlyph  ***g;
    UChar8          *img = 0;
    const Int32     *res;
    const Char8     *text = 0;
    Int32           pen_x, pen_y, line, xoff, yoff;
    Int32           width = 0, overallWidth = 0, height = 0, overallHeight = 0;
    Int32           i, j, k, l, tmpMinY, tmpMaxY, strStart, strEnd, strStep;
    Int32           p, tmpWidth;
    UChar8          *srcPixel, *imageBuffer = 0, *row = 0, *dstPixel;
    bool            retVal;

    if(forcePower2 && (!maxX || !maxY))
        return false;

    if(_fontInstance)
    {
        g = new ImageFontGlyph **[lineVec.size()];
        for(line = 0; line < Int32(lineVec.size()); line++)
        {
            text = lineVec[line].c_str();
            g[line] = new ImageFontGlyph *[strlen(text)];
            tmpMinY = INT_MAX;
            tmpMaxY = -INT_MAX;
            for(i = 0; i < Int32(strlen(text)); i++)
            {
                g[line][i] = _fontInstance->getImageGlyph(text[i]);
                if(g[line][i])
                {
                    retVal = g[line][i]->create();
                    if(!retVal)
                    {
                        FWARNING(("Glyph generation failed."));
                        for(line = 0; line < Int32(lineVec.size()); line++)
                            delete[] g[line];
                        delete[] g;
                    }

                    width += (i + 1 == Int32(strlen(text)) ? 
                                g[line][i]->getImageSize()[0] : 
                                g[line][i]->getAdvance());
                    tmpMinY = g[line][i]->getBoundingBox()[2] < tmpMinY ? 
                                g[line][i]->getBoundingBox()[2] : 
                                tmpMinY;
                    tmpMaxY = g[line][i]->getBoundingBox()[3] > tmpMaxY ? 
                                g[line][i]->getBoundingBox()[3] : 
                                tmpMaxY;
                }
            }

            if(width > overallWidth)
                overallWidth = width;

            if(!tmpMinY && !tmpMaxY)
            {   // TXF-character not present -> all blanks..
                tmpMaxY = 
                    Int32(osgfloor(Real32(_fontInstance->getBaselineSkip())));
            }

            overallHeight += ( line + 1 == lineVec.size() ? 
                               Int32(osgfloor((abs(tmpMaxY) + 
                                               abs(tmpMinY)) * _spacing)) :
                               
                               Int32(osgfloor(
                                         Real32(_fontInstance->getBaselineSkip()) *
                                         Real32(_fontInstance->getYRes()) * 
                                         _spacing)));
            width = 0;
        }

        if(forcePower2)
        {
            height = 1;
            while(height < overallHeight)
                height *= 2;
            *maxY = (Real32(height)) / (Real32(overallHeight));
            overallHeight = height;

            width = 1;
            while(width < overallWidth)
                width *= 2;
            *maxX = (Real32(width)) / (Real32(overallWidth));
            overallWidth = width;
        }

        imageBuffer = new UChar8[overallWidth * overallHeight * pixelDepth];
        row = new UChar8[overallWidth * pixelDepth];

        for(i = 0; i < overallWidth * pixelDepth;)
        {
            for(l = 0; l < pixelDepth; l++, i++)
                row[i] = (*bg)[l];
        }

        for(i = 0; i < overallHeight; i++)
        {
            memcpy(imageBuffer + i * overallWidth * pixelDepth, row,
                               overallWidth * pixelDepth);
        }

        delete[] row;

        tmpMinY = INT_MAX;
        tmpMaxY = -INT_MAX;

        tmpWidth = 0;
        line = 0;
        for(i = 0; i != Int32(strlen(lineVec[line].c_str())); i++)
        {
            tmpMinY = g[line][i]->getBoundingBox()[2] < tmpMinY ? 
                        g[line][i]->getBoundingBox()[2] : 
                        tmpMinY;
            tmpMaxY = g[line][i]->getBoundingBox()[3] > tmpMaxY ? 
                        g[line][i]->getBoundingBox()[3] : 
                        tmpMaxY;
            tmpWidth += (i + 1 == Int32(strlen(text)) ? 
                            g[line][i]->getImageSize()[0] : 
                            g[line][i]->getAdvance());
        }

        height = abs(tmpMaxY) + abs(tmpMinY);
        yoff = _topToBottom ? overallHeight - height : 0;

        switch(_justifyMajor)
        {
        case FIRST_JT:
        case BEGIN_JT:
            xoff = 0;
            break;
        case MIDDLE_JT:
            xoff = (overallWidth - tmpWidth) / 2 * pixelDepth;
            break;
        case END_JT:
            xoff = (overallWidth - tmpWidth) * pixelDepth;
            break;
        default:
            FFATAL(("Invalid _justifyMajor entry (%d)\n", _justifyMajor));
            xoff = 0;
        }

        xoff -= g[line][0]->getBoundingBox()[0] * pixelDepth;

        tmpWidth = 0;

        for(line = 0; line < Int32(lineVec.size()); line++)
        {
            text = lineVec[line].c_str();

            if(_leftToRight)
            {
                strStart = 0;
                strEnd = strlen(text);
                strStep = 1;
            }
            else
            {
                strStart = strlen(text) - 1;
                strEnd = -1;
                strStep = -1;
            }

            for(i = strStart; i != strEnd; i += strStep)
            {
                pen_y = yoff + abs(tmpMinY) + g[line][i]->getBoundingBox()[2];
                pen_x = xoff + (g[line][i]->getBoundingBox()[0] * pixelDepth);
                img = g[line][i]->getImage();
                res = g[line][i]->getImageSize();

                for(j = res[1] - 1; j >= 0; j--)
                {
                    srcPixel = img + ((res[1] - j - 1) * res[2]);

                    dstPixel = imageBuffer + ((pen_y + j) * overallWidth * 
                                    pixelDepth) + pen_x;

                    for(k = 0; k < res[0]; k++, srcPixel++)
                    {
                        if(!(p = *(srcPixel)))
                        {
                            dstPixel += pixelDepth;
                            continue;
                        }

                        for(l = 0; l < pixelDepth; l++, dstPixel++)
                        {
                            *(dstPixel) =
                                    (
                                        (*fg)[l] *
                                        p +
                                        (*bg)[l] *
                                        (4 - p)
                                    ) >>
                                    2;
                        }
                    }
                }

                xoff += (g[line][i]->getAdvance() * pixelDepth);
            }

            if(line + 1 < Int32(lineVec.size()))
            {
                tmpWidth = 0;
                if(_justifyMajor == MIDDLE_JT || _justifyMajor == END_JT)
                {
                    for(i = 0; i != Int32(strlen(lineVec[line + 1].c_str()));
                                            i++)
                    {
                        tmpWidth += 
                            Int32(osgfloor(g[line + 1][i]->getAdvance()));
                    }
                }

                switch(_justifyMajor)
                {
                case FIRST_JT:
                case BEGIN_JT:
                    xoff = 0;
                    break;
                case MIDDLE_JT:
                    xoff = (overallWidth - tmpWidth) / 2 * pixelDepth;
                    break;
                case END_JT:
                    xoff = (overallWidth - tmpWidth) * pixelDepth;
                    break;
                }

                if(line + 1 == Int32(lineVec.size()) - 1)
                {
                    yoff = _topToBottom ? 0 : overallHeight - height;
                }
                else
                {
                    yoff += (_topToBottom ? -1 : 1) * 
                        Int32(osgfloor(
                                  Real32(_fontInstance->getBaselineSkip())*
                                  _fontInstance->getYRes() * _spacing));
                }
            }
        }

        for(line = 0; line < Int32(lineVec.size()); line++)
            delete[] g[line];
        delete[] g;


		// AT: Convert Image Buffer for usage with glBitmap
		Image::PixelFormat pixelFormat;
		if( bConvertToBitmap )
		{		
			pixelFormat = Image::OSG_L_PF;
#if 1
			//Int32 newOverallWidth = ceil(((float)(overallWidth))/8.0);

			UChar8* bitmapBuffer = new UChar8[ overallWidth * overallHeight ];
			memset( bitmapBuffer, '\0', overallWidth * overallHeight );

			for( int nY=0; nY<overallHeight; nY++ )
			{
				for( int nX=0; nX<overallWidth; nX +=8 )
				{	
					for( int nXplus = 0; (nXplus < 8) && (nXplus+nX < overallWidth); nXplus++ )
					{
						if( (imageBuffer[ ( nY*overallWidth*pixelDepth ) + nX + nXplus ] > 0) )
							bitmapBuffer[ ( nY*overallWidth ) + nX/8 ] += (128 >> nXplus) ;
					}
				}
			}
			delete [] imageBuffer;
			imageBuffer = bitmapBuffer;
			//overallWidth = newOverallWidth;
#endif

			// AT's conversion ready
		}
		else
		{
			pixelFormat = Image::OSG_RGBA_PF;
		}
		
        bool retval = image->set(pixelFormat, // Image::OSG_RGB_PF, 
                                 overallWidth, overallHeight, 1, 
                                 1, 
                                 1, 0.0, imageBuffer);
        delete [] imageBuffer;
        return retval;
    }
示例#30
0
bool Text::fillTXFArrays(std::vector<std::string> &lineVec, 
                         Pnt3f *points, Vec2f *texcoords)
{
    Int32           j, k;
    UInt32          i;
    Int32           sStart, sStop, sStep, lStart, lStop, lStep;
    Int32           numChars, numLineChars;
    Real32          xOff, yOff, scale, tmpWidth, oaWidth;
    TXFGlyphInfo    *currentGlyph;

    numChars = 0;
    for(i = 0; i < Int32(lineVec.size()); i++)
    {
        numChars += strlen(lineVec[i].c_str());
    }

    scale = ( Real32(_fontInstance->getBaselineSkip()) *
              _fontInstance->getYRes() );

    oaWidth = 0.f;
    tmpWidth = 0.f;
    for(i = 0; i < Int32(lineVec.size()); i++)
    {
        const Char8 *text = lineVec[i].c_str();
        numLineChars = strlen(text);
        for(j = 0; j < numLineChars; j++)
        {
            tmpWidth += _fontInstance->getTXFGlyphInfo(text[j])->getAdvance() / 
                        scale;
        }

        oaWidth = tmpWidth > oaWidth ? tmpWidth : oaWidth;
        tmpWidth = 0;
    }

    yOff = 0.0;
    if(_topToBottom)
    {
        lStart = 0;
        lStop = lineVec.size();
        lStep = 1;
    }
    else
    {
        lStart = lineVec.size() - 1;
        lStop = -1;
        lStep = -1;
    }

    for(k = lStart; k != lStop; k += lStep)
    {
        numLineChars = strlen(lineVec[k].c_str());

        const Char8 *text = lineVec[k].c_str();

        if(_justifyMajor == MIDDLE_JT || _justifyMajor == END_JT)
        {
            for(j = 0; j < numLineChars; j++)
            {
                tmpWidth += 
                        _fontInstance->getTXFGlyphInfo(text[j])->getAdvance() /
                        scale;
            }
        }

        switch(_justifyMajor)
        {
        case FIRST_JT:
        case BEGIN_JT:
            xOff = 0.0;
            break;
        case MIDDLE_JT:
            xOff = tmpWidth / -2;
            break;
        case END_JT:
            xOff = -tmpWidth;
            break;
        default:
            FFATAL(("Invalid _jusifyMajor entry\n"));
            xOff = 0;
        }

        tmpWidth = 0;

        if(_leftToRight)
        {
            sStart = 0;
            sStop = numLineChars;
            sStep = 1;
        }
        else
        {
            sStart = numLineChars - 1;
            sStop = -1;
            sStep = -1;
        }

        for(i = sStart; i != sStop; i += sStep)
        {
            for(j = 0; j < 4; j++, points++, texcoords++)
            {
                currentGlyph = _fontInstance->getTXFGlyphInfo(text[i]);
                points->setValues(currentGlyph->getVertexCoords(j)[0] /
                                                 scale + xOff,
                                  currentGlyph->getVertexCoords(j)[1] /
                                                 scale + yOff, 0.0);

                texcoords->setValues(currentGlyph->getTextureCoords(j)[0],
                                     currentGlyph->getTextureCoords(j)[1]);
            }

            xOff += currentGlyph->getAdvance() / scale;
        }

        yOff -= Real32(_fontInstance->getBaselineSkip());
    }

    return true;
}