# How to implement uvs on indices instead of positions

for example, I’d like to unwrap my box just like below:

Then I make my 3d box geometry using vertices, and proper number of indices:

Problems comes when I trying to implement uvs on each loop of indices. I read many example of three.js and knows that every uv should be correspond to a vertex. But at this point, I need the uv correspond to index. A vertex may correspond to different uv on different triangles it belongs to.

What should I do to achieve this? Is the only way I can do is just using non-indexd geometry?

In such situations, I create seperate vertices for each wall, so instead of having 8 vertices for the cube i end up with 24. I’m pretty sure that 3d modeling programs do the same.

I think those are some times refered to as “seams”. There are books written on these topics, but the simple example where this is often encountered on a daily basis are normals. To index a cube you would render with `MeshBasicMaterial` you’d need only 8 vertices. But when you want to light it and have sharp edges, each vertex needs to hold exactly 3 different normals. Hence, you end up needing 3 unique vertices, and have to duplicate those positions. Considering that there are 12 triangles and a triangle soup would yield 36 vertices, you still get a considerable saving when indexing.

This example has 36 uvs, which means it’s already a triangle soup. There’s no further extrapolation there, each entry corresponds to an index in the index attribute.

Try this

``````const map = {}
for ( let i = 0 ; i < g.index.array.length ; i ++ ){
const vertexIndex = g.index.array[i]
if(!map[vertexIndex]){
map[vertexIndex] = [
g.attributes.uv.array[i*2],
g.attributes.uv.array[i*2 + 1]
]
}
}

const uvs = []

Object.keys(map).sort().forEach(index=> uvs.push(map[index][0],map[index][1]))
``````

Thanks for your answer, and I’m so appreciate your explaining on ‘seams’. But I don’t think your code is suit for my situation. The code would eliminate extra uvs belongs to a single vertexIndex. see the picture below:

A and B should be the same vertex, but different uv values. Your code would eliminate one of them.

true, so you need to split your vertices based on that, if it’s too complicated why use indexing?

1 Like

Absolutely !