This started with a face that could be pulled out of shape. Javi (@rameerez) had posted an interactive portrait on his website, and I wanted to try the idea with my own photograph. I used ChatGPT to build a browser version and then to develop a native Wolfram Language implementation. Once the portrait behaved like a rubber sheet, it suggested the next experiment: let the sheet hang from a rail and pull it in three dimensions.
Here are the original tweet and the interactive portrait website created with ChatGPT. They are the inspiration and companion demonstration. Everything computed and displayed in this post - the portrait deformation, grids, cloth, figures and animation - runs in Wolfram Language. No browser component or JavaScript is used in the notebook.
To try the live examples, download the attached FaceDistortionToCurtain.nb and open it in desktop Wolfram or Mathematica, and evaluate the initialization cell below. This single notebook contains the source and required images; its initialization cell unpacks them into a temporary folder and imports the source. The buttons marked desktop notebook open the live experiments there. In the Community web view, use the looping animation and static previews; if a control is shown only as an image or does not respond, use the downloaded notebook.
elasticProjectDirectory=CreateDirectory[];KeyValueMap[With[{file=FileNameJoin[{elasticProjectDirectory,#1}]},If[!DirectoryQ[DirectoryName[file]],CreateDirectory[DirectoryName[file],CreateIntermediateDirectoriesTrue]];BinaryWrite[file,Normal[#2],"Byte"];Close[file]]&,Uncompress[CurrentValue[EvaluationNotebook[],{TaggingRules,"EmbeddedProject"}]]];Get[FileNameJoin[{elasticProjectDirectory,"ElasticLab.wl"}]];
The visual similarity hides a useful distinction. For the face I prescribe a smooth transformation of the plane. For the curtain I prescribe how connected particles move and how their distances are corrected. We can understand both with a relatively small amount of geometry, and we can use a grid to see where the first idea goes wrong.
Load the examples
Load the examples
Evaluate the short initialization cell at the beginning once. It reconstructs the bundled ElasticLab.wl, ElasticPortrait.wl and runtime images in a temporary directory, then imports ElasticLab.wl. No companion download is needed. The full implementation stays in the companion source files so that this post can concentrate on the ideas. No network connection, external runtime or API key is required.
HeroAnimation[]
The hero uses AnimatedImage with embedded, resized and colour-quantized frames, following the animation format of my earlier Community posts. It plays without loading a local MP4 or evaluating the source. The companion file figures/face-curtain-hero-community.gif is the looping image to insert through Community's image uploader if assembling the post manually. The MP4 remains available separately through HeroVideo[]. Live mouse interaction requires the desktop notebook and its kernel.
1. Pulling a face
1. Pulling a face
Let us begin with the result. Move the pointer over the portrait to direct the eyes, then click and drag. A gentle pull produces a smile, a larger pull produces surprise, and release lets the deformation spring back. The expression buttons are also useful for separating the image changes from the geometric deformation.
Interactive portrait: download the attached notebook and run it in desktop Wolfram or Mathematica for gaze, mouse dragging and expression controls. The figure below is a static preview.
ElasticPortrait[]
A native Wolfram Language portrait. The neutral, smiling and surprised images are pre-generated gpt-image edits of the supplied photograph. The runtime performs no facial inference and makes no AI calls.
The image and its coordinates are different things
The image and its coordinates are different things
Write the undeformed image as I(u), where u = (u,v) is a material or texture coordinate. A deformation F moves the point u to a displayed point x. The colour seen at x is therefore the colour at the corresponding original coordinate. Conceptually this is the following inverse mapping:
deformed
-1
F
There is no need to compute that inverse separately at every image pixel. We triangulate the image, move the triangle vertices, and leave a texture coordinate attached to each vertex. Within a triangle, barycentric interpolation supplies the coordinates between the vertices. The same mechanism will later attach the image to the 3D cloth.
x++
λ
1
x
1
λ
2
x
2
λ
3
x
3
u++
λ
1
u
1
λ
2
u
2
λ
3
u
3
λ
1
λ
2
λ
3
The lambda values are non-negative inside the triangle. In Wolfram Language, GraphicsComplex stores the vertex positions and VertexTextureCoordinates stores the corresponding image coordinates. Texture supplies the image. The geometry can therefore be studied independently of the photograph.
2. Remove the photograph and inspect the grid
2. Remove the photograph and inspect the grid
The grid is more informative than my face. It shows local compression and expansion, and it makes an orientation reversal visible. Try a long pull with One large step and then switch to Composed steps. The faint grid is the undeformed reference.
Interactive grid: download the attached notebook and run it to drag the mesh, change the radius and switch methods. The Community figure is a static preview.
ElasticGrid[]
Blue triangles contract, orange triangles expand, and red triangles have reversed their orientation. This colour scheme describes local area change; it is not a stress calculation.
Module[{m=PortraitMesh[24,20,1.`]},GraphicsRow[(DeformedGridFrame[m,{0.5`,0.5`},{0.48`,0.`},0.16`,#1,430]&)/@{"Single","Composed"},ImageSize900]]
Method | Smallest area ratio | Inverted triangles |
One large step | -2.085 | 38 |
Composed steps | 0.072 | 0 |
The same displacement and nominal influence radius. In this computed example the single step inverts 38 sampled triangles; the composed map inverts none.
3. The first deformation: a weighted translation
3. The first deformation: a weighted translation
Suppose a is the grabbed point and d is the requested displacement. The simplest local rule adds a Gaussian-weighted fraction of d to each point. We work in physical image coordinates q = (u, aspect v), so the distance calculation does not depend on whether the photograph is square.
w(q)exp-
2
q-a
2
ρ
F(q)q+dw(q)
At the grab point w is one, so F(a) = a + d. Far away, w tends to zero and the image is almost unchanged. The parameter rho controls the size of the affected neighbourhood. This explains the immediate appearance of a local stretch, but it does not yet guarantee a valid deformation.
The Jacobian tells us when the map turns over
The Jacobian tells us when the map turns over
Differentiating the map gives a rank-one update of the identity. The gradient of the Gaussian points back towards its centre. The determinant is particularly simple:
This is the two-dimensional determinant identity computed symbolically. Ahead of the drag, the dot product is negative. A sufficiently large d can make the determinant negative. The surface then reverses orientation locally: the apparent fracture comes from the map folding over itself.
For a triangle, the discrete version is a signed area. Dividing by its original signed area removes the arbitrary choice of clockwise or anticlockwise vertex order. Positive ratios preserve the orientation; zero means a degenerate triangle; negative ratios indicate inversion.
Smallest sampled area ratio as the pull grows. The zero line is the important boundary. The composed method remains positive over the plotted range.
4. Carry the grabbed point along a path
4. Carry the grabbed point along a path
Instead of doing all of the displacement at once, divide d into n small steps s = d/n. At step j put the Gaussian centre at a + j s. A point at the moving centre receives the whole small translation and follows the path. This is a composition of local maps, rather than an interpolation between the original and a folded final mesh.
A useful quantitative bound
A useful quantitative bound
The largest gradient magnitude of the Gaussian occurs at distance rho/Sqrt[2] from its centre. Thus the displacement field of one small step has the following Lipschitz bound:
When L < 1, the reverse triangle inequality supplies a lower bound on the separation of two transformed points. Distinct points cannot be mapped to the same point. Each small map is injective, and so is their composition.
In the implementation rho = Sqrt[0.65] r and the step length is no more than 0.12 r. The resulting upper bound is about 0.128. The smooth-map argument is useful, but a finite triangle mesh can still undersample a sharp bend. We therefore check every sampled triangle and widen the influence if a triangle would invert.
5. Giving the portrait a response
5. Giving the portrait a response
Spring return
Spring return
The spring acts on the grab displacement, not on thousands of independent image vertices. Let z be the current handle displacement, v its velocity, and zTarget the requested displacement. The visual update is a damped spring step. Releasing the mouse sets zTarget to zero:
The safe geometric map is recomputed from this handle state, including during the overshoot on release. The parameters k and eta tune the response of the interface; they are not elastic material constants.
Eye motion and expressions are texture operations
Eye motion and expressions are texture operations
For the eyes we make a small, smoothly tapered sampling displacement g inside each eye region. If Meye is the local mask, the texture is sampled at u - g Meye(u). Moving the pointer changes g, giving the impression of gaze while the mesh itself stays still.
The expression is also independent of the deformation. Let C0, Cs and Cu be the neutral, smiling and surprised RGB images, and let M be a face-region mask. Two small blends give a smooth transition without replacing the hair or silhouette. The original alpha channel is retained.
The pull magnitude chooses alpha and beta, and the reaction buttons let us inspect the individual ingredients. These are generated expression variants, not inferred muscle motion or a fitted face model.
6. The portrait suggests a hanging curtain
6. The portrait suggests a hanging curtain
Once the image could be carried by a sheet, I wanted to give that sheet depth and let it move after release. This is where the second procedure begins. A 3D curtain has vertex positions p_i in three-dimensional space and a state that changes with time. Neighbouring vertices constrain each other, so a tug propagates through the sheet instead of being prescribed by one Gaussian field.
Interactive 3D curtain: download the attached notebook and run it for mouse dragging, wind, stiffness and texture controls. These controls run local Wolfram computations; the Community figure below is a snapshot.
A hanging cloth with a pinned top row. Drag a free point, change the view with the buttons, or use Pull curtain for a reproducible example. Grid, plain fabric and portrait textures all ride on the same moving surface.
Predict the motion
Predict the motion
The model uses a damped Verlet predictor. The difference between the current and previous positions stores the velocity implicitly. Gravity acts downward, and an optional wind term acts in depth. A small time step h advances the unconstrained prediction:
Prediction alone allows the mesh to stretch. We next project its edge lengths back towards their rest values. This is a small teaching implementation of the position-based dynamics idea [1]. It is designed for interactive geometric experiments, not for identifying a real fabric's material parameters.
7. Correct the distances between neighbours
7. Correct the distances between neighbours
For an edge joining particles i and j, let ell_ij be its rest length. The constraint is the current length minus that rest length. One can also regard its square as a spring-energy penalty:
Rather than integrate the forces of very stiff springs explicitly, the solver directly corrects positions. Put n along the edge and write w_i = 1/m_i for inverse mass. A first-order constraint correction is distributed according to these inverse masses:
An inverse mass of zero makes a point immovable. This pins the top row exactly. When a vertex is grabbed, it is temporarily kinematic and is placed at the mouse target on every solver pass. The other vertices must accommodate that choice.
Structural neighbours resist extension, diagonal neighbours resist shear, and weaker two-hop distances provide a simple bending surrogate. A factor kappa scales each correction. For one isolated constraint, N repeated corrections leave the residual factor (1 - kappaIteration)^N; this motivates the following conversion from an overall correction parameter:
A network of coupled constraints is more complicated than one edge. The adjustment reduces one source of iteration dependence, but it does not eliminate it. A hard, rapidly moved grip can still produce finite stretch, which is why the diagnostics below measure the error rather than assume that the cloth is inextensible.
8. Turning a mouse position into a 3D target
8. Turning a mouse position into a 3D target
A screen position specifies a ray, not a unique point in three dimensions. MousePosition["Graphics3DBoxIntercepts"] supplies its front and back intersections with the graphics box. We pick the nearest free cloth vertex to this ray. Through that vertex we define a plane parallel to the view, and subsequent mouse rays intersect that plane.
This supplies the missing depth convention for a two-dimensional input device. A nearly parallel ray is rejected. The top row is excluded from picking, and the target is kept inside a bounded demonstration region. The view buttons keep cloth dragging separate from the front end's usual 3D rotation gesture.
9. Measure what the model actually does
9. Measure what the model actually does
The two procedures need different checks. In the flat image map an area inversion is a failure. A curtain is allowed to fold in three dimensions, so the signed area of its screen projection is not the right test. We instead monitor the actual triangle area, edge strain, finite coordinates and the error at pinned vertices.
A computed pulled state. The mesh connectivity is unchanged. The strong kinematic grip creates visible folds and some residual distance error; it is not a tearing model.
The fresh-kernel checks keep the pinned row fixed, inspect the signed areas in the flat map, exercise the ray-plane calculation and advance the cloth through held and released states. The code and tests are included with the notebook. The working GitHub repository remains private, while the separate browser demonstration remains public.
What the two experiments teach
What the two experiments teach
For the portrait, the main object is a coordinate transformation: the image is carried by a map, and the Jacobian tells us when that map fails. For the curtain, the main object is a connected particle system: prediction supplies motion and projections enforce geometric relationships. Both use a mesh and texture coordinates, so the same photograph can be attached to either construction.
There are useful next steps, but also clear limits. The curtain has no self-collision, tearing or contact friction, and its two-hop bending surrogate is not a dihedral-angle shell model. Its parameters are not measured fabric properties. XPBD compliance, a proper bending energy and triangle-interior picking would be natural extensions. Wolfram Cloud, CDF and conference-profile embedding remain separate deployment questions; the examples here are native desktop Wolfram Language.
References and links
References and links
[1] M. Muller, B. Heidelberger, M. Hennix and J. Ratcliff, Position Based Dynamics, VRIPHYS 2006. Author-hosted paper
Original inspiration: @rameerez tweet. Companion demonstration: ChatGPT-created elastic portrait website.
How the source is organised
How the source is organised
The first initialization cell imports the long implementation. ElasticPortrait.wl contains the flat-map flow, orientation test, gaze sampling and expression textures. ElasticLab.wl adds the diagnostic grid, cloth solver and mouse picking. The post uses short function calls so that code, equations and evaluated results can be read together.
The time loop and the drawing code are separate from the numerical kernels. This makes it possible to compute frames without an interface, advance a reproducible held-and-released cloth experiment, and test the geometry in a fresh kernel. RunChecks.wls and tests/LabChecks.wls provide those checks. The attached notebook contains the source and runtime assets, so readers need only that one file. The initialization cell reconstructs readable .wl packages in a temporary folder and loads them with Get. The development repository is private.
CITE THIS NOTEBOOK
CITE THIS NOTEBOOK
From a rubber face to a hanging curtain: image deformation, Jacobians and an interactive 3D cloth
by Marco Thiel
Wolfram Community, STAFF PICKS, October 31, 2026
https://community.wolfram.com/t/28452
by Marco Thiel
Wolfram Community, STAFF PICKS, October 31, 2026
https://community.wolfram.com/t/28452