Search code examples
wpftexture-mappinghelix-3d-toolkit

Apply a texture on a box


I'm trying to applya texture on each faces of my box, here's the code:

        int boxWidth = 40;

        Point3D location = new Point3D(0, 0, 0);
        var meshBuilder = new MeshBuilder();
        meshBuilder.AddBox(new Point3D(location.X, location.Y, location.Z), boxWidth, boxWidth, boxWidth);

        PointCollection pntCol = new PointCollection();
        pntCol.Add(new Point(boxWidth, boxWidth));
        pntCol.Add(new Point(0, boxWidth));
        pntCol.Add(new Point(0, 0));
        pntCol.Add(new Point(boxWidth, 0));

        pntCol.Add(new Point(boxWidth, boxWidth));
        pntCol.Add(new Point(0, boxWidth));
        pntCol.Add(new Point(0, 0));
        pntCol.Add(new Point(boxWidth, 0));

        pntCol.Add(new Point(boxWidth, boxWidth));
        pntCol.Add(new Point(0, boxWidth));
        pntCol.Add(new Point(0, 0));
        pntCol.Add(new Point(boxWidth, 0));

        pntCol.Add(new Point(boxWidth, boxWidth));
        pntCol.Add(new Point(0, boxWidth));
        pntCol.Add(new Point(0, 0));
        pntCol.Add(new Point(boxWidth, 0));

        pntCol.Add(new Point(boxWidth, boxWidth));
        pntCol.Add(new Point(0, boxWidth));
        pntCol.Add(new Point(0, 0));
        pntCol.Add(new Point(boxWidth, 0));

        pntCol.Add(new Point(boxWidth, boxWidth));
        pntCol.Add(new Point(0, boxWidth));
        pntCol.Add(new Point(0, 0));
        pntCol.Add(new Point(boxWidth, 0));
        meshBuilder.TextureCoordinates = pntCol;

        ImageBrush brush = new ImageBrush();
        brush.ImageSource = new BitmapImage(new Uri(@"mv-pallet-cubi.jpg", UriKind.Relative));
        brush.TileMode = TileMode.Tile;
        brush.ViewportUnits = BrushMappingMode.RelativeToBoundingBox;
        brush.ViewboxUnits = BrushMappingMode.Absolute;
        brush.Stretch = Stretch.None;
        brush.AlignmentX = AlignmentX.Left;
        brush.AlignmentY = AlignmentY.Top;
        brush.Viewbox = new Rect(0, 0, brush.ImageSource.Width, brush.ImageSource.Height);
        brush.Viewport = new Rect(0, 0, 1, 1);

        DiffuseMaterial mat = new DiffuseMaterial(brush);
        GeometryModel3D gModel3D = new GeometryModel3D { Geometry = meshBuilder.ToMesh(), Material = mat };
        ModelVisual3D mvt = new ModelVisual3D();
        mvt.Content = gModel3D;
        viewport.Children.Add(mvt);

The width and height of my box are 40 and the size of the texture are 90x90. Basically the effect I got is this:

Texture 90x90, Box 40x40

If I set the dimensions of my box as 90 (same of the texture), the effect is what I want.

Texture 90x90, Box 90x90

Basically I would stretch the whole texture on a box of any dimension. Any helps?


Solution

  • Your texture coordinate need to set to 0 to 1 range instead of 0 to box width