Friday, 27 February 2009

D3DX UVAtlas for mesh parameterization fails with some meshes (Partition, Pack and Create)

I have been searching for a solution to this situation for a long time. Searched and searched with no luck on the net. I guess that not many people is using the UVAtlas functionality that comes with DirectX9. So, these are my findings:

Partition and Pack always fail?

If you are using the Managed version of DirectX, the Partition and Pack methods will ALWAYS fail. I´m not sure if it´s related to the MDX implementation itself or (as ZMan suggested), may be due to MDX being based on an old version of DirectX. However, if you want to use them, you will have to deal with the native version: D3DXUVAtlasPartition and D3DXUVAtlasPack.

If you have been experiencing random failures in the UVAtlas generation, keep reading:

I have found that the problem is related to the MaxStretch parameter. If you don´t care much about stretching your geometry in the Atlas, the reasonable value is "1" (any amount of stretch allowed), but this value will cause errors with some meshes. I still wasn´t able to detect why and when it fails exactly.

More precisely, what happens then is that Partition method returns wrong values as output texture coordinates, even when returning S_OK as result. If you don´t detect this situation (as D3DXUVAtlasCreate doesn´t) and pass the resulting wrong mesh to the Pack method, it will throw an exception. The worst thing is that this exception is sometimes a native memory violation exception, so a managed try-catch won´t handle it and will force your application to exit.

To detect wrong texture information, Lock the mesh VertexBuffer (to get into its contents) and check for wrong resulting U,V values: +/- infinity, NaN, or extremely big values.

The general criteria to fix this situations is to low MaxStretch down. Most of the times (if not always), using 0.999f instead of 1 makes it, but maybe sometimes you will have to make it even lower, depending on your meshes.

Hope this helps.

Cheers!

Wednesday, 25 February 2009

How to sign C++ CLI assemblies with a strong name

If your application is signed with a strong name, Visual Studio will require you to sign every assembly you reference. Now, even if you are a .Net only developer, it happens sometimes that you have to deal with some kind of interop with C++/CLI DLLs. If both situations happen, you will find yourself in the need to sign a C++ assembly with a strong name.
To do so, you have to specify the key file you will use at:
Project->Properties->Configuration Properties->Linker->Advanced->Key File. Something like this:
image
Don´t try to sign the assembly with a .Pfx file. It won´t work. To do so, you need a .SNK file (Strong Name Key). You can generate one with the SN.EXE tool, using:
sn.exe –k [directory]\[filename].snk
Where to find SN.EXE ?
In the Microsoft .Net Framework SDK (usually c:\program files\microsoft .net\sdk\bin, or something similar). You can download the SDK from here.
Note: In order to install that SDK, you will also need the .Net Framework 1.1 installed. As it´s a bit old, many people don´t have it in their machines.

Wednesday, 18 February 2009

Avoid that strange “Form going to background” effect in WinForms

Someone asked me yesterday about a strange effect he was getting in a WinForms application.

Scenario:

  1. Form1 is the main form of the application
  2. Form2 is a child form shown sometimes to make additional operations. This form is shown using the Show() method, not the ShowDialog() method. I´m not sure if this affects this specific situation, but in his program, Form2 is forced to never be closed (except when app exiting), so it can be reopened whenever the user wants, without loosing information. This way, when user closes the form, it´s in fact being hidden, not closed.

Symptoms:

Apparently sometimes, when user closes Form2 (actually hides it), the focus doesn´t come back to the main form. Instead, Form1 is minimized, what is very frustrating from the user experience point of view.

Solution:

What looked like a random behavior, it is in fact due to Form2 opening additional modal dialogs, like MessageBoxes, and setting their owner to himself (Form2). Something like this:

class Form2

{

MessageBox.Show(this, “Hello”, “World”…);

}

The solution is to set the MessageBox´s Owner to Form1 (the main form), instead of Form2, like this:

MessageBox.Show(this.Owner, “Hello”, “World”…);

And that´s it ;)

Qué perro aquel perro…

 

El otro día, me fui a recordar como era eso que llaman “naturaleza”… Y es que estando tantas horas encerrado en una “cueva” mirando a una pantalla que emite “lucecicas” de colores, ya lo necesitaba.

Escogimos un paseo muy chulo que empieza en la playa de Orio (Guipúzcoa), remonta hacia la derecha por un sendero inicialmente asfaltado, y recorre la costa pudiendo llegar incluso hasta San Sebastián. Muy bonito, la verdad…

El caso es que a unos 10 minutos de marcha, se pasa al lado de un caserío con un perro muy puñetero en la puerta. Es un moco de perro, pues no levanta ni un palmo del suelo, pero es de esos que ladran, ladran y ladran, probablemente porque sus negligentes dueños no se han molestado en educarlo. Al pasar, en la ida, ladró hasta reventar, por lo que ya me esperaba que, a la vuelta, iba a hacer lo mismo.

Con lo cual. Antes de acercarnos a menos de 50 metros, el perro ya estaba dando el coñazo, pero esta vez acercándose más al camino. Y a mi que me encantan los perros (entre mis padres y mi hermana tenemos nada menos que 5, y de todos los tamaños), me propuse hacer lo que hay que hacer en estos casos: ignorarlo para que vea que no somos una amenaza… Así que me pongo delante, miro hacia el camino ignorando al perro, y sigo caminando.

En esas estaba, cuando de pronto noto algo en la pierna, miro, y el puto perro estaba mordiéndome con todas sus putas ganas. QÚE CABRON! Por un momento me vi como Phoebe (en Friends), con el perro colgando de la pierna y diciendo… “pero por qué me muerdes? A mi me encantan los perros!…”  El caso es que le pegué el peor y más amenazante grito que pude, y el perrito por poco se hace caca. Echó a correr sin necesidad de nada más.

Que nunca me haya mordido un perro, y el primero tuviera que ser ese… manda webs… Si al menos me hubiera dejado una cicatriz digna de ser enseñada como herida de guerra… Pero no, me ha dejado la marca de sus dos colmillos bien clavados, tan juntos que parece que me ha mordido una serpiente más que un perro… En fin…

A todo esto, que voy a la casa a echarle la bronca al dueño. Le pego cuatro gritos: “que si el perro muerde debería estar atado, etc etc”, y a él lo uno que se le ocurre contestarme es…

“Te ha mordido? Uh uh… pues… haberle pegado una patada! “

Con semejante “intelecto” como dueño, ahora entiendo por qué el perrillo está tan desquiciado.

Lo más jodido es que, por pequeña que fuera la herida, oyes cosas, que si los perros pueden pegarte infecciones, la rabia, etc etc… así que él lunes perdí casi toda la mañana en ir al médico a que me vacunaran (gran eficiencia la del sistema sanitario de nuestro país). Solo me pusieron la Antitetánica, por si las moscas (me dijeron que la antirábica no era necesaria).

La gracia es que la mordedura no me duele nada, pero el brazo donde me han puesto la vacuna está hinchado y me duele un huevo… Me he informado y es normal (al menos durante 2-3 días) pero… joder con la vacuna, casi prefería la mordedura!

Salu2

Tuesday, 17 February 2009

ListView highlighting effects (and how to force it to keep highlight when lost focus)

 

Many people ask about how to force a List View to keep the selected item highlight when the control lost its focus.

The obvious and fast answer is: Set “HideSelection” property to false, as it seems to be designed with such purpose. In part, this is true, because when the the list view losses the focus the item remains highlighted, but with the “inactive” color, instead the default highlight one.

A VERY EASY way to achieve is:

1.- Mark your list view as “Owner Draw” (OwnerDraw property = true)

2.- Write an event handler for the even “DrawItem” or “DrawSubItem” of the list view, doing something like this:

 

private void lvModelsInfo_DrawItem(object sender, DrawListViewItemEventArgs e)
       {
           if (e.Item.Selected)
           {
               e.Graphics.FillRectangle(new SolidBrush(COLOR1), e.Bounds);
               e.Graphics.DrawString(e.Item.Text, listview1.Font, COLOR2, e.Bounds.Location);
           }
           else
           {
               e.Graphics.DrawString(e.Item.Text, listview1.Font, COLOR3, e.Bounds.Location);
           }
       }

 

Et´voila. The list view keeps the highlight.

In addition to that, I´ve marked three variables: COLOR1, COLOR2 AND COLOR3. This vars allow you to customize the selection highlight color, item fore color (when selected), and item fore color (when not selected), respectively.

Hope this helps.

Cheers!

Bungie´s Lighting and Rendering pipeline

Yesterday, I found a very interesting website with publications and articles from Bungie, the creators of Halo. You can find them here.

One of them talks about lighting and rendering and there is a specially interesting slide that will explain a lot of people how they achieve such a wonderful visuals. It shows, step by step, the rendering stages they process (which doesn't necessarily have to be done in different passes). Starting from the transformed geometry:

1.- Draw geometry with shaders using the following information:

  • Albedo (on the right): This includes normal textures, taken form pictures and processed to be seamless, normalized lighting, etc.
  • Normal Maps (on the left): Special textures storing surface information, instead of visual appearance or color.

One thing to note: Watching the albedo, they don´t use HDR textures. This is something logical, as it frees content creators form processing every single texture to adapt it to scene lighting conditions. This ifnormation is applied in the next step.

image

2.- Static Lighting

Applies lighting calculations from static lights. This process is probably the responsible to add the HDR information to the result of the previous stage. You can clearly appreciate it in the following picure (the level of contrast between the outside and inside parts is huge).

image

3.- Dynamic Lights

This stage adds the lighting information coming from lights that may change each frame (moving or changing lights, etc). In the picture, you can clearly see the new light that will simulate an explosion later. Of course, this light needs to be dynamic, as it´s intensity will vary to simulate the explosion effect.

image

4.- Transparents

To achieve some visual effects, like lens flares, explosions, fire, etc, using 2D impostors is still the way to go. You can appreciate the ray or explosion effect in the picture.

image

5.- Post-processing

And finally, with some 2d post processing (some bloom, tone mapping, etc), and the final result.

image

Microsoft Research and Bungie… talented people, for sure…

image

Saturday, 7 February 2009

Simax + Microsoft + Toyota

Today, we have published another Simax Video, about the Simax ECO-Experience, a product developed for Toyota and with the collaboration of Microsoft focused in ECO-Driving Training.

 

You can download the Hi-Res version from here.

Thursday, 5 February 2009

Skateboarding glories pt. 2 – Rodney Mullen –

 

In this last post, I talked about some of the most influencer skateboarders of all times. It´s time today for Rodney Mullen again. Want to know more? Check his bio:

Bio pt 1

 

Bio pt 2

Bio pt 3

 

 

And an additional gift. Impressive video… a must:

 

Take Care!

Tuesday, 3 February 2009

Earl, skateboarding glories, and the MegaRamp

 

Skate1_thumb_thumbI used to (or at least tried to) be a skateboarder when I was younger… much younger…

<-- This is me… no kidding…

 

Stop laughing please… ;)

However… Earl, with no doubt, is the responsible of a ninety per cent of my laughter in the last years. For those of you who don´t know, Jason Lee was is a very good professional skateboarder, and co-founder of Stereo Skateboards. The point is that, Earl still has it... (Look at the tre flip)

 

Hilarious! As a youtube freak says:

“Jason Lee is now officially my new favorite person... sorry Jesus”

 

Another guy from my old times that still rocks riding a skateboard. Rodney Mullen. Is he around 45 right? I´d like to be like that when I´m 45…

 

Next: Danny Way. I watched him skateboarding here in Pamplona like around 15 years ago. You have to be insane to jump over the Great Wall of China with a skateboard… don´t you?

 

But probably you have to be even worse to do a backflip in the same MegaRamp WITH A TRYCICLE!!!… by Travis Pastrana

 

Juas!