1 /*
2 * Copyright © 2015 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24 #include "nir.h"
25 #include "nir_builtin_builder.h"
26
27 /*
28 * Lower cubemap coordinate to have normalized coordinates where the largest
29 * magnitude component is -1.0 or 1.0.
30 */
31 static bool
normalize_cubemap_coords(nir_builder * b,nir_instr * instr,void * data)32 normalize_cubemap_coords(nir_builder *b, nir_instr *instr, void *data)
33 {
34 if (instr->type != nir_instr_type_tex)
35 return false;
36
37 nir_tex_instr *tex = nir_instr_as_tex(instr);
38 if (tex->sampler_dim != GLSL_SAMPLER_DIM_CUBE)
39 return false;
40
41 b->cursor = nir_before_instr(instr);
42
43 int idx = nir_tex_instr_src_index(tex, nir_tex_src_coord);
44 if (idx < 0)
45 return false;
46
47 nir_def *orig_coord =
48 tex->src[idx].src.ssa;
49 assert(orig_coord->num_components >= 3);
50
51 nir_def *orig_xyz = nir_trim_vector(b, orig_coord, 3);
52 nir_def *norm = nir_fmax_abs_vec_comp(b, orig_xyz);
53 nir_def *normalized = nir_fmul(b, orig_coord, nir_frcp(b, norm));
54
55 /* Array indices don't have to be normalized, so make a new vector
56 * with the coordinate's array index untouched.
57 */
58 if (tex->coord_components == 4) {
59 normalized = nir_vector_insert_imm(b, normalized,
60 nir_channel(b, orig_coord, 3), 3);
61 }
62
63 nir_src_rewrite(&tex->src[idx].src, normalized);
64 return true;
65 }
66
67 bool
nir_normalize_cubemap_coords(nir_shader * shader)68 nir_normalize_cubemap_coords(nir_shader *shader)
69 {
70 return nir_shader_instructions_pass(shader, normalize_cubemap_coords,
71 nir_metadata_control_flow,
72 NULL);
73 }
74